blob: c1c6c57fbac8a7aa1a1e90eca2168e0c69e5f363 [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()
Hochi Huang327cb702014-09-21 09:47:31 +080029#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
Eric Laurente552edb2014-03-10 17:42:56 -070030// 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 Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070047#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070048#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070049#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurent3b73df72014-03-11 09:06:29 -070051namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070052
53// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070054// Definitions for audio_policy.conf file parsing
55// ----------------------------------------------------------------------------
56
57struct StringToEnum {
58 const char *name;
59 uint32_t value;
60};
61
62#define STRING_TO_ENUM(string) { #string, string }
63#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64
65const StringToEnum sDeviceNameToEnumTable[] = {
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070069 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070081 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070087 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
91 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070092 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050093 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070094 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
98 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700108 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
110 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
111 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700112 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900113 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700114};
115
Eric Laurent5dbe4712014-09-19 19:04:57 -0700116const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700123 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700124};
125
Eric Laurent5dbe4712014-09-19 19:04:57 -0700126const StringToEnum sInputFlagNameToEnumTable[] = {
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
128 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
129};
130
Eric Laurent3a4311c2014-03-17 12:00:47 -0700131const StringToEnum sFormatNameToEnumTable[] = {
132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
137 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
138 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
149 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
152 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
153 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
154 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
155 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156};
157
158const StringToEnum sOutChannelsNameToEnumTable[] = {
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
163 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
164};
165
166const StringToEnum sInChannelsNameToEnumTable[] = {
167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
169 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
170};
171
Eric Laurent1afeecb2014-05-14 08:52:28 -0700172const StringToEnum sGainModeNameToEnumTable[] = {
173 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
174 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
175 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
176};
177
Eric Laurent3a4311c2014-03-17 12:00:47 -0700178
179uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
180 size_t size,
181 const char *name)
182{
183 for (size_t i = 0; i < size; i++) {
184 if (strcmp(table[i].name, name) == 0) {
185 ALOGV("stringToEnum() found %s", table[i].name);
186 return table[i].value;
187 }
188 }
189 return 0;
190}
191
192const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
193 size_t size,
194 uint32_t value)
195{
196 for (size_t i = 0; i < size; i++) {
197 if (table[i].value == value) {
198 return table[i].name;
199 }
200 }
201 return "";
202}
203
204bool AudioPolicyManager::stringToBool(const char *value)
205{
206 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
207}
208
209
210// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700211// AudioPolicyInterface implementation
212// ----------------------------------------------------------------------------
213
Eric Laurente0720872014-03-11 09:30:41 -0700214status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700216 const char *device_address)
217{
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800218 return setDeviceConnectionStateInt(device, state, device_address);
219}
220
221status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
222 audio_policy_dev_state_t state,
223 const char *device_address)
224{
Eric Laurent22226012014-08-01 17:00:54 -0700225 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700226 // handle legacy remote submix case where the address was not always specified
227 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
228 address = String8("0");
229 }
Eric Laurente552edb2014-03-10 17:42:56 -0700230
Eric Laurent22226012014-08-01 17:00:54 -0700231 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
232 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700233
234 // connect/disconnect only 1 device at a time
235 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
236
Eric Laurente552edb2014-03-10 17:42:56 -0700237 // handle output devices
238 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700239 SortedVector <audio_io_handle_t> outputs;
240
Eric Laurent1afeecb2014-05-14 08:52:28 -0700241 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
242 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700243 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
244
Eric Laurente552edb2014-03-10 17:42:56 -0700245 // save a copy of the opened output descriptors before any output is opened or closed
246 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
247 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700248 switch (state)
249 {
250 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700251 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700253 ALOGW("setDeviceConnectionState() device already connected: %x", device);
254 return INVALID_OPERATION;
255 }
256 ALOGV("setDeviceConnectionState() connecting device %x", device);
257
Eric Laurente552edb2014-03-10 17:42:56 -0700258 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700259 index = mAvailableOutputDevices.add(devDesc);
260 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700261 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700262 if (module == 0) {
263 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
264 device);
265 mAvailableOutputDevices.remove(devDesc);
266 return INVALID_OPERATION;
267 }
268 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700269 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700270 } else {
271 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700272 }
273
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700274 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700275 mAvailableOutputDevices.remove(devDesc);
276 return INVALID_OPERATION;
277 }
278 // outputs should never be empty here
279 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
280 "checkOutputsForDevice() returned no outputs but status OK");
281 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
282 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700283 break;
284 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700285 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700286 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700287 ALOGW("setDeviceConnectionState() device not connected: %x", device);
288 return INVALID_OPERATION;
289 }
290
Paul McLean5c477aa2014-08-20 16:47:57 -0700291 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
292
293 // Set Disconnect to HALs
294 AudioParameter param = AudioParameter(address);
295 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
296 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
297
Eric Laurente552edb2014-03-10 17:42:56 -0700298 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700300
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700301 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700302 } break;
303
304 default:
305 ALOGE("setDeviceConnectionState() invalid state: %x", state);
306 return BAD_VALUE;
307 }
308
Eric Laurent3a4311c2014-03-17 12:00:47 -0700309 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
310 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700311 checkA2dpSuspend();
312 checkOutputForAllStrategies();
313 // outputs must be closed after checkOutputForAllStrategies() is executed
314 if (!outputs.isEmpty()) {
315 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700316 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700317 // close unused outputs after device disconnection or direct outputs that have been
318 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700319 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700320 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
321 (desc->mDirectOpenCount == 0))) {
322 closeOutput(outputs[i]);
323 }
324 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 // check again after closing A2DP output to reset mA2dpSuspended if needed
326 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700327 }
328
329 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700330 if (mPhoneState == AUDIO_MODE_IN_CALL) {
331 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
332 updateCallRouting(newDevice);
333 }
Eric Laurente552edb2014-03-10 17:42:56 -0700334 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700335 audio_io_handle_t output = mOutputs.keyAt(i);
336 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
337 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
338 true /*fromCache*/);
339 // do not force device change on duplicated output because if device is 0, it will
340 // also force a device 0 for the two outputs it is duplicated to which may override
341 // a valid device selection on those outputs.
342 bool force = !mOutputs.valueAt(i)->isDuplicated()
343 && (!deviceDistinguishesOnAddress(device)
344 // always force when disconnecting (a non-duplicated device)
345 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
346 setOutputDevice(output, newDevice, force, 0);
347 }
Eric Laurente552edb2014-03-10 17:42:56 -0700348 }
349
Eric Laurent72aa32f2014-05-30 18:51:48 -0700350 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700351 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700352 } // end if is output device
353
Eric Laurente552edb2014-03-10 17:42:56 -0700354 // handle input devices
355 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700356 SortedVector <audio_io_handle_t> inputs;
357
Eric Laurent1afeecb2014-05-14 08:52:28 -0700358 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
359 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700360 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700361 switch (state)
362 {
363 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700364 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700365 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700366 ALOGW("setDeviceConnectionState() device already connected: %d", device);
367 return INVALID_OPERATION;
368 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700369 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700370 if (module == NULL) {
371 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
372 device);
373 return INVALID_OPERATION;
374 }
Eric Laurentd4692962014-05-05 18:13:44 -0700375 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
376 return INVALID_OPERATION;
377 }
378
Eric Laurent3a4311c2014-03-17 12:00:47 -0700379 index = mAvailableInputDevices.add(devDesc);
380 if (index >= 0) {
381 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700382 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700383 } else {
384 return NO_MEMORY;
385 }
Eric Laurentd4692962014-05-05 18:13:44 -0700386 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700387
388 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700389 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700390 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700391 ALOGW("setDeviceConnectionState() device not connected: %d", device);
392 return INVALID_OPERATION;
393 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700394
395 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
396
397 // Set Disconnect to HALs
398 AudioParameter param = AudioParameter(address);
399 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
400 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700403 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700406
407 default:
408 ALOGE("setDeviceConnectionState() invalid state: %x", state);
409 return BAD_VALUE;
410 }
411
Eric Laurentd4692962014-05-05 18:13:44 -0700412 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700413
Eric Laurentc2730ba2014-07-20 15:47:07 -0700414 if (mPhoneState == AUDIO_MODE_IN_CALL) {
415 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
416 updateCallRouting(newDevice);
417 }
418
Eric Laurentb52c1522014-05-20 11:27:36 -0700419 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700420 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700421 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700422
423 ALOGW("setDeviceConnectionState() invalid device: %x", device);
424 return BAD_VALUE;
425}
426
Eric Laurente0720872014-03-11 09:30:41 -0700427audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700428 const char *device_address)
429{
Eric Laurent3b73df72014-03-11 09:06:29 -0700430 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700431 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700432 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700433 // handle legacy remote submix case where the address was not always specified
434 if (deviceDistinguishesOnAddress(device) && (devDesc->mAddress.length() == 0)) {
435 devDesc->mAddress = String8("0");
436 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700437 ssize_t index;
438 DeviceVector *deviceVector;
439
Eric Laurente552edb2014-03-10 17:42:56 -0700440 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700441 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700442 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700443 deviceVector = &mAvailableInputDevices;
444 } else {
445 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
446 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700447 }
448
Eric Laurent3a4311c2014-03-17 12:00:47 -0700449 index = deviceVector->indexOf(devDesc);
450 if (index >= 0) {
451 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
452 } else {
453 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
454 }
Eric Laurente552edb2014-03-10 17:42:56 -0700455}
456
Eric Laurentc2730ba2014-07-20 15:47:07 -0700457void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
458{
459 bool createTxPatch = false;
460 struct audio_patch patch;
461 patch.num_sources = 1;
462 patch.num_sinks = 1;
463 status_t status;
464 audio_patch_handle_t afPatchHandle;
465 DeviceVector deviceList;
466
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800467 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
469
470 // release existing RX patch if any
471 if (mCallRxPatch != 0) {
472 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
473 mCallRxPatch.clear();
474 }
475 // release TX patch if any
476 if (mCallTxPatch != 0) {
477 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
478 mCallTxPatch.clear();
479 }
480
481 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
482 // via setOutputDevice() on primary output.
483 // Otherwise, create two audio patches for TX and RX path.
484 if (availablePrimaryOutputDevices() & rxDevice) {
485 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
486 // If the TX device is also on the primary HW module, setOutputDevice() will take care
487 // of it due to legacy implementation. If not, create a patch.
488 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
489 == AUDIO_DEVICE_NONE) {
490 createTxPatch = true;
491 }
492 } else {
493 // create RX path audio patch
494 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
495 ALOG_ASSERT(!deviceList.isEmpty(),
496 "updateCallRouting() selected device not in output device list");
497 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
498 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
499 ALOG_ASSERT(!deviceList.isEmpty(),
500 "updateCallRouting() no telephony RX device");
501 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
502
503 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
504 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
505
506 // request to reuse existing output stream if one is already opened to reach the RX device
507 SortedVector<audio_io_handle_t> outputs =
508 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700509 audio_io_handle_t output = selectOutput(outputs,
510 AUDIO_OUTPUT_FLAG_NONE,
511 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700512 if (output != AUDIO_IO_HANDLE_NONE) {
513 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
514 ALOG_ASSERT(!outputDesc->isDuplicated(),
515 "updateCallRouting() RX device output is duplicated");
516 outputDesc->toAudioPortConfig(&patch.sources[1]);
517 patch.num_sources = 2;
518 }
519
520 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
521 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
522 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
523 status);
524 if (status == NO_ERROR) {
525 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
526 &patch, mUidCached);
527 mCallRxPatch->mAfPatchHandle = afPatchHandle;
528 mCallRxPatch->mUid = mUidCached;
529 }
530 createTxPatch = true;
531 }
532 if (createTxPatch) {
533
534 struct audio_patch patch;
535 patch.num_sources = 1;
536 patch.num_sinks = 1;
537 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
538 ALOG_ASSERT(!deviceList.isEmpty(),
539 "updateCallRouting() selected device not in input device list");
540 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
541 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
542 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
543 ALOG_ASSERT(!deviceList.isEmpty(),
544 "updateCallRouting() no telephony TX device");
545 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
546 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
547
548 SortedVector<audio_io_handle_t> outputs =
549 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700550 audio_io_handle_t output = selectOutput(outputs,
551 AUDIO_OUTPUT_FLAG_NONE,
552 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700553 // request to reuse existing output stream if one is already opened to reach the TX
554 // path output device
555 if (output != AUDIO_IO_HANDLE_NONE) {
556 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
557 ALOG_ASSERT(!outputDesc->isDuplicated(),
558 "updateCallRouting() RX device output is duplicated");
559 outputDesc->toAudioPortConfig(&patch.sources[1]);
560 patch.num_sources = 2;
561 }
562
563 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
564 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
565 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
566 status);
567 if (status == NO_ERROR) {
568 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
569 &patch, mUidCached);
570 mCallTxPatch->mAfPatchHandle = afPatchHandle;
571 mCallTxPatch->mUid = mUidCached;
572 }
573 }
574}
575
Eric Laurente0720872014-03-11 09:30:41 -0700576void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700577{
578 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700579 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700580 ALOGW("setPhoneState() invalid state %d", state);
581 return;
582 }
583
584 if (state == mPhoneState ) {
585 ALOGW("setPhoneState() setting same state %d", state);
586 return;
587 }
588
589 // if leaving call state, handle special case of active streams
590 // pertaining to sonification strategy see handleIncallSonification()
591 if (isInCall()) {
592 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700593 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800594 if (stream == AUDIO_STREAM_PATCH) {
595 continue;
596 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700597 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700598 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800599
600 // force reevaluating accessibility routing when call starts
601 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700602 }
603
604 // store previous phone state for management of sonification strategy below
605 int oldState = mPhoneState;
606 mPhoneState = state;
607 bool force = false;
608
609 // are we entering or starting a call
610 if (!isStateInCall(oldState) && isStateInCall(state)) {
611 ALOGV(" Entering call in setPhoneState()");
612 // force routing command to audio hardware when starting a call
613 // even if no device change is needed
614 force = true;
615 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
616 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
617 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
618 }
619 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
620 ALOGV(" Exiting call in setPhoneState()");
621 // force routing command to audio hardware when exiting a call
622 // even if no device change is needed
623 force = true;
624 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
625 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
626 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
627 }
628 } else if (isStateInCall(state) && (state != oldState)) {
629 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
630 // force routing command to audio hardware when switching between telephony and VoIP
631 // even if no device change is needed
632 force = true;
633 }
634
635 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700636 checkA2dpSuspend();
637 checkOutputForAllStrategies();
638 updateDevicesAndOutputs();
639
Eric Laurent1f2f2232014-06-02 12:01:23 -0700640 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700641
Eric Laurente552edb2014-03-10 17:42:56 -0700642 int delayMs = 0;
643 if (isStateInCall(state)) {
644 nsecs_t sysTime = systemTime();
645 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700646 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700647 // mute media and sonification strategies and delay device switch by the largest
648 // latency of any output where either strategy is active.
649 // This avoid sending the ring tone or music tail into the earpiece or headset.
650 if ((desc->isStrategyActive(STRATEGY_MEDIA,
651 SONIFICATION_HEADSET_MUSIC_DELAY,
652 sysTime) ||
653 desc->isStrategyActive(STRATEGY_SONIFICATION,
654 SONIFICATION_HEADSET_MUSIC_DELAY,
655 sysTime)) &&
656 (delayMs < (int)desc->mLatency*2)) {
657 delayMs = desc->mLatency*2;
658 }
659 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
660 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
661 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
662 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
663 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
664 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
665 }
666 }
667
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
669 // the device returned is not necessarily reachable via this output
670 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
671 // force routing command to audio hardware when ending call
672 // even if no device change is needed
673 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
674 rxDevice = hwOutputDesc->device();
675 }
Eric Laurente552edb2014-03-10 17:42:56 -0700676
Eric Laurentc2730ba2014-07-20 15:47:07 -0700677 if (state == AUDIO_MODE_IN_CALL) {
678 updateCallRouting(rxDevice, delayMs);
679 } else if (oldState == AUDIO_MODE_IN_CALL) {
680 if (mCallRxPatch != 0) {
681 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
682 mCallRxPatch.clear();
683 }
684 if (mCallTxPatch != 0) {
685 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
686 mCallTxPatch.clear();
687 }
688 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
689 } else {
690 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
691 }
Eric Laurente552edb2014-03-10 17:42:56 -0700692 // if entering in call state, handle special case of active streams
693 // pertaining to sonification strategy see handleIncallSonification()
694 if (isStateInCall(state)) {
695 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700696 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800697 if (stream == AUDIO_STREAM_PATCH) {
698 continue;
699 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700700 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700701 }
702 }
703
704 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700705 if (state == AUDIO_MODE_RINGTONE &&
706 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700707 mLimitRingtoneVolume = true;
708 } else {
709 mLimitRingtoneVolume = false;
710 }
711}
712
Eric Laurente0720872014-03-11 09:30:41 -0700713void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700714 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700715{
716 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
717
718 bool forceVolumeReeval = false;
719 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700720 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
721 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
722 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700723 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
724 return;
725 }
726 forceVolumeReeval = true;
727 mForceUse[usage] = config;
728 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700729 case AUDIO_POLICY_FORCE_FOR_MEDIA:
730 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
731 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
732 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
733 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800734 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700735 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
736 return;
737 }
738 mForceUse[usage] = config;
739 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700740 case AUDIO_POLICY_FORCE_FOR_RECORD:
741 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
742 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700743 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
744 return;
745 }
746 mForceUse[usage] = config;
747 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700748 case AUDIO_POLICY_FORCE_FOR_DOCK:
749 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
750 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
751 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
752 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
753 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700754 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
755 }
756 forceVolumeReeval = true;
757 mForceUse[usage] = config;
758 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700759 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
760 if (config != AUDIO_POLICY_FORCE_NONE &&
761 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700762 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
763 }
764 forceVolumeReeval = true;
765 mForceUse[usage] = config;
766 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900767 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
768 if (config != AUDIO_POLICY_FORCE_NONE &&
769 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
770 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
771 }
772 mForceUse[usage] = config;
773 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700774 default:
775 ALOGW("setForceUse() invalid usage %d", usage);
776 break;
777 }
778
779 // check for device and output changes triggered by new force usage
780 checkA2dpSuspend();
781 checkOutputForAllStrategies();
782 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700783 if (mPhoneState == AUDIO_MODE_IN_CALL) {
784 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
785 updateCallRouting(newDevice);
786 }
Eric Laurente552edb2014-03-10 17:42:56 -0700787 for (size_t i = 0; i < mOutputs.size(); i++) {
788 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700789 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700790 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
791 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
792 }
Eric Laurente552edb2014-03-10 17:42:56 -0700793 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
794 applyStreamVolumes(output, newDevice, 0, true);
795 }
796 }
797
798 audio_io_handle_t activeInput = getActiveInput();
799 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700800 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700801 }
802
803}
804
Eric Laurente0720872014-03-11 09:30:41 -0700805audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700806{
807 return mForceUse[usage];
808}
809
Eric Laurente0720872014-03-11 09:30:41 -0700810void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700811{
812 ALOGV("setSystemProperty() property %s, value %s", property, value);
813}
814
815// Find a direct output profile compatible with the parameters passed, even if the input flags do
816// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700817sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700818 audio_devices_t device,
819 uint32_t samplingRate,
820 audio_format_t format,
821 audio_channel_mask_t channelMask,
822 audio_output_flags_t flags)
823{
824 for (size_t i = 0; i < mHwModules.size(); i++) {
825 if (mHwModules[i]->mHandle == 0) {
826 continue;
827 }
828 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700829 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent275e8e92014-11-30 15:14:47 -0800830 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -0700831 NULL /*updatedSamplingRate*/, format, channelMask,
832 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
833 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700834 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
835 return profile;
836 }
Eric Laurente552edb2014-03-10 17:42:56 -0700837 }
838 }
839 return 0;
840}
841
Eric Laurente0720872014-03-11 09:30:41 -0700842audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700843 uint32_t samplingRate,
844 audio_format_t format,
845 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700846 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700847 const audio_offload_info_t *offloadInfo)
848{
Eric Laurent3b73df72014-03-11 09:06:29 -0700849 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700850 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
851 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
852 device, stream, samplingRate, format, channelMask, flags);
853
Eric Laurente83b55d2014-11-14 10:06:21 -0800854 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
855 stream, samplingRate,format, channelMask,
856 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700857}
858
Eric Laurente83b55d2014-11-14 10:06:21 -0800859status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
860 audio_io_handle_t *output,
861 audio_session_t session,
862 audio_stream_type_t *stream,
863 uint32_t samplingRate,
864 audio_format_t format,
865 audio_channel_mask_t channelMask,
866 audio_output_flags_t flags,
867 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700868{
Eric Laurente83b55d2014-11-14 10:06:21 -0800869 audio_attributes_t attributes;
870 if (attr != NULL) {
871 if (!isValidAttributes(attr)) {
872 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
873 attr->usage, attr->content_type, attr->flags,
874 attr->tags);
875 return BAD_VALUE;
876 }
877 attributes = *attr;
878 } else {
879 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
880 ALOGE("getOutputForAttr(): invalid stream type");
881 return BAD_VALUE;
882 }
883 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700884 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800885
Eric Laurent275e8e92014-11-30 15:14:47 -0800886 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
887 sp<AudioOutputDescriptor> desc;
888 if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) {
889 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
890 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
891 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) ||
892 (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
893 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) {
894 desc = mPolicyMixes[i]->mOutput;
895 break;
896 }
897 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
898 strncmp(attributes.tags + strlen("addr="),
899 mPolicyMixes[i]->mMix.mRegistrationId.string(),
900 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
901 desc = mPolicyMixes[i]->mOutput;
902 break;
903 }
904 }
905 } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) {
906 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE &&
907 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
908 strncmp(attributes.tags + strlen("addr="),
909 mPolicyMixes[i]->mMix.mRegistrationId.string(),
910 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
911 desc = mPolicyMixes[i]->mOutput;
Eric Laurent275e8e92014-11-30 15:14:47 -0800912 }
913 }
914 if (desc != 0) {
915 if (!audio_is_linear_pcm(format)) {
916 return BAD_VALUE;
917 }
Eric Laurentc722f302014-12-10 11:21:49 -0800918 desc->mPolicyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -0800919 *stream = streamTypefromAttributesInt(&attributes);
920 *output = desc->mIoHandle;
921 ALOGV("getOutputForAttr() returns output %d", *output);
922 return NO_ERROR;
923 }
924 }
925 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
926 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
927 return BAD_VALUE;
928 }
929
Eric Laurent93c3d412014-08-01 14:48:35 -0700930 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800931 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700932
Eric Laurente83b55d2014-11-14 10:06:21 -0800933 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700934 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700935
Eric Laurente83b55d2014-11-14 10:06:21 -0800936 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700937 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
938 }
939
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700940 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700941 device, samplingRate, format, channelMask, flags);
942
Eric Laurente83b55d2014-11-14 10:06:21 -0800943 *stream = streamTypefromAttributesInt(&attributes);
944 *output = getOutputForDevice(device, session, *stream,
945 samplingRate, format, channelMask,
946 flags, offloadInfo);
947 if (*output == AUDIO_IO_HANDLE_NONE) {
948 return INVALID_OPERATION;
949 }
950 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700951}
952
953audio_io_handle_t AudioPolicyManager::getOutputForDevice(
954 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800955 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700956 audio_stream_type_t stream,
957 uint32_t samplingRate,
958 audio_format_t format,
959 audio_channel_mask_t channelMask,
960 audio_output_flags_t flags,
961 const audio_offload_info_t *offloadInfo)
962{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700963 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700964 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700965 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700966
Eric Laurente552edb2014-03-10 17:42:56 -0700967#ifdef AUDIO_POLICY_TEST
968 if (mCurOutput != 0) {
969 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
970 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
971
972 if (mTestOutputs[mCurOutput] == 0) {
973 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700974 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700975 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700976 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700977 outputDesc->mFlags =
978 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700979 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700980 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
981 config.sample_rate = mTestSamplingRate;
982 config.channel_mask = mTestChannels;
983 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700984 if (offloadInfo != NULL) {
985 config.offload_info = *offloadInfo;
986 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700987 status = mpClientInterface->openOutput(0,
988 &mTestOutputs[mCurOutput],
989 &config,
990 &outputDesc->mDevice,
991 String8(""),
992 &outputDesc->mLatency,
993 outputDesc->mFlags);
994 if (status == NO_ERROR) {
995 outputDesc->mSamplingRate = config.sample_rate;
996 outputDesc->mFormat = config.format;
997 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700998 AudioParameter outputCmd = AudioParameter();
999 outputCmd.addInt(String8("set_id"),mCurOutput);
1000 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
1001 addOutput(mTestOutputs[mCurOutput], outputDesc);
1002 }
1003 }
1004 return mTestOutputs[mCurOutput];
1005 }
1006#endif //AUDIO_POLICY_TEST
1007
1008 // open a direct output if required by specified parameters
1009 //force direct flag if offload flag is set: offloading implies a direct output stream
1010 // and all common behaviors are driven by checking only the direct flag
1011 // this should normally be set appropriately in the policy configuration file
1012 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001013 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001014 }
Eric Laurent93c3d412014-08-01 14:48:35 -07001015 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1016 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1017 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001018 // only allow deep buffering for music stream type
1019 if (stream != AUDIO_STREAM_MUSIC) {
1020 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1021 }
Eric Laurente552edb2014-03-10 17:42:56 -07001022
Eric Laurentb732cf52014-09-24 19:08:21 -07001023 sp<IOProfile> profile;
1024
1025 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001026 // and not explicitly requested
1027 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1028 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -07001029 audio_channel_count_from_out_mask(channelMask) <= 2) {
1030 goto non_direct_output;
1031 }
1032
Eric Laurente552edb2014-03-10 17:42:56 -07001033 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1034 // creating an offloaded track and tearing it down immediately after start when audioflinger
1035 // detects there is an active non offloadable effect.
1036 // FIXME: We should check the audio session here but we do not have it in this context.
1037 // This may prevent offloading in rare situations where effects are left active by apps
1038 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001039
Eric Laurente552edb2014-03-10 17:42:56 -07001040 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1041 !isNonOffloadableEffectEnabled()) {
1042 profile = getProfileForDirectOutput(device,
1043 samplingRate,
1044 format,
1045 channelMask,
1046 (audio_output_flags_t)flags);
1047 }
1048
Eric Laurent1c333e22014-05-20 10:48:17 -07001049 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001050 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -07001051
1052 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001053 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001054 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1055 outputDesc = desc;
1056 // reuse direct output if currently open and configured with same parameters
1057 if ((samplingRate == outputDesc->mSamplingRate) &&
1058 (format == outputDesc->mFormat) &&
1059 (channelMask == outputDesc->mChannelMask)) {
1060 outputDesc->mDirectOpenCount++;
1061 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1062 return mOutputs.keyAt(i);
1063 }
1064 }
1065 }
1066 // close direct output if currently open and configured with different parameters
1067 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001068 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001069 }
1070 outputDesc = new AudioOutputDescriptor(profile);
1071 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001072 outputDesc->mLatency = 0;
1073 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001074 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1075 config.sample_rate = samplingRate;
1076 config.channel_mask = channelMask;
1077 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001078 if (offloadInfo != NULL) {
1079 config.offload_info = *offloadInfo;
1080 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001081 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1082 &output,
1083 &config,
1084 &outputDesc->mDevice,
1085 String8(""),
1086 &outputDesc->mLatency,
1087 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001088
1089 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001090 if (status != NO_ERROR ||
1091 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1092 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1093 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001094 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1095 "format %d %d, channelMask %04x %04x", output, samplingRate,
1096 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1097 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001098 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001099 mpClientInterface->closeOutput(output);
1100 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001101 // fall back to mixer output if possible when the direct output could not be open
1102 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
1103 goto non_direct_output;
1104 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001105 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001106 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001107 outputDesc->mSamplingRate = config.sample_rate;
1108 outputDesc->mChannelMask = config.channel_mask;
1109 outputDesc->mFormat = config.format;
1110 outputDesc->mRefCount[stream] = 0;
1111 outputDesc->mStopTime[stream] = 0;
1112 outputDesc->mDirectOpenCount = 1;
1113
Eric Laurente552edb2014-03-10 17:42:56 -07001114 audio_io_handle_t srcOutput = getOutputForEffect();
1115 addOutput(output, outputDesc);
1116 audio_io_handle_t dstOutput = getOutputForEffect();
1117 if (dstOutput == output) {
1118 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1119 }
1120 mPreviousOutputs = mOutputs;
1121 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001122 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001123 return output;
1124 }
1125
Eric Laurentb732cf52014-09-24 19:08:21 -07001126non_direct_output:
1127
Eric Laurente552edb2014-03-10 17:42:56 -07001128 // ignoring channel mask due to downmix capability in mixer
1129
1130 // open a non direct output
1131
1132 // for non direct outputs, only PCM is supported
1133 if (audio_is_linear_pcm(format)) {
1134 // get which output is suitable for the specified stream. The actual
1135 // routing change will happen when startOutput() will be called
1136 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1137
Eric Laurent8838a382014-09-08 16:44:28 -07001138 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1139 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1140 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001141 }
1142 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1143 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1144
1145 ALOGV("getOutput() returns output %d", output);
1146
1147 return output;
1148}
1149
Eric Laurente0720872014-03-11 09:30:41 -07001150audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001151 audio_output_flags_t flags,
1152 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001153{
1154 // select one output among several that provide a path to a particular device or set of
1155 // devices (the list was previously build by getOutputsForDevice()).
1156 // The priority is as follows:
1157 // 1: the output with the highest number of requested policy flags
1158 // 2: the primary output
1159 // 3: the first output in the list
1160
1161 if (outputs.size() == 0) {
1162 return 0;
1163 }
1164 if (outputs.size() == 1) {
1165 return outputs[0];
1166 }
1167
1168 int maxCommonFlags = 0;
1169 audio_io_handle_t outputFlags = 0;
1170 audio_io_handle_t outputPrimary = 0;
1171
1172 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001173 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001174 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001175 // if a valid format is specified, skip output if not compatible
1176 if (format != AUDIO_FORMAT_INVALID) {
1177 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1178 if (format != outputDesc->mFormat) {
1179 continue;
1180 }
1181 } else if (!audio_is_linear_pcm(format)) {
1182 continue;
1183 }
1184 }
1185
Eric Laurent3b73df72014-03-11 09:06:29 -07001186 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001187 if (commonFlags > maxCommonFlags) {
1188 outputFlags = outputs[i];
1189 maxCommonFlags = commonFlags;
1190 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1191 }
1192 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1193 outputPrimary = outputs[i];
1194 }
1195 }
1196 }
1197
1198 if (outputFlags != 0) {
1199 return outputFlags;
1200 }
1201 if (outputPrimary != 0) {
1202 return outputPrimary;
1203 }
1204
1205 return outputs[0];
1206}
1207
Eric Laurente0720872014-03-11 09:30:41 -07001208status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001209 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001210 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001211{
1212 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1213 ssize_t index = mOutputs.indexOfKey(output);
1214 if (index < 0) {
1215 ALOGW("startOutput() unknown output %d", output);
1216 return BAD_VALUE;
1217 }
1218
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001219 // cannot start playback of STREAM_TTS if any other output is being used
1220 uint32_t beaconMuteLatency = 0;
1221 if (stream == AUDIO_STREAM_TTS) {
1222 ALOGV("\t found BEACON stream");
1223 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1224 return INVALID_OPERATION;
1225 } else {
1226 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1227 }
1228 } else {
1229 // some playback other than beacon starts
1230 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1231 }
1232
Eric Laurent1f2f2232014-06-02 12:01:23 -07001233 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001234
1235 // increment usage count for this stream on the requested output:
1236 // NOTE that the usage count is the same for duplicated output and hardware output which is
1237 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1238 outputDesc->changeRefCount(stream, 1);
1239
1240 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001241 // starting an output being rerouted?
1242 audio_devices_t newDevice;
Eric Laurentc722f302014-12-10 11:21:49 -08001243 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001244 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1245 } else {
1246 newDevice = getNewOutputDevice(output, false /*fromCache*/);
1247 }
Eric Laurente552edb2014-03-10 17:42:56 -07001248 routing_strategy strategy = getStrategy(stream);
1249 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001250 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1251 (beaconMuteLatency > 0);
1252 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001253 bool force = false;
1254 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001255 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001256 if (desc != outputDesc) {
1257 // force a device change if any other output is managed by the same hw
1258 // module and has a current device selection that differs from selected device.
1259 // In this case, the audio HAL must receive the new device selection so that it can
1260 // change the device currently selected by the other active output.
1261 if (outputDesc->sharesHwModuleWith(desc) &&
1262 desc->device() != newDevice) {
1263 force = true;
1264 }
1265 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001266 // a notification so that audio focus effect can propagate, or that a mute/unmute
1267 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001268 uint32_t latency = desc->latency();
1269 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1270 waitMs = latency;
1271 }
1272 }
1273 }
1274 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1275
1276 // handle special case for sonification while in call
1277 if (isInCall()) {
1278 handleIncallSonification(stream, true, false);
1279 }
1280
1281 // apply volume rules for current stream and device if necessary
1282 checkAndSetVolume(stream,
1283 mStreams[stream].getVolumeIndex(newDevice),
1284 output,
1285 newDevice);
1286
1287 // update the outputs if starting an output with a stream that can affect notification
1288 // routing
1289 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001290
1291 // Automatically enable the remote submix input when output is started on a re routing mix
1292 // of type MIX_TYPE_RECORDERS
1293 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1294 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001295 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001296 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1297 outputDesc->mPolicyMix->mRegistrationId);
1298 }
1299
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001300 // force reevaluating accessibility routing when ringtone or alarm starts
1301 if (strategy == STRATEGY_SONIFICATION) {
1302 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1303 }
1304
Eric Laurente552edb2014-03-10 17:42:56 -07001305 if (waitMs > muteWaitMs) {
1306 usleep((waitMs - muteWaitMs) * 2 * 1000);
1307 }
1308 }
1309 return NO_ERROR;
1310}
1311
1312
Eric Laurente0720872014-03-11 09:30:41 -07001313status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001314 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001315 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001316{
1317 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1318 ssize_t index = mOutputs.indexOfKey(output);
1319 if (index < 0) {
1320 ALOGW("stopOutput() unknown output %d", output);
1321 return BAD_VALUE;
1322 }
1323
Eric Laurent1f2f2232014-06-02 12:01:23 -07001324 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001325
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001326 // always handle stream stop, check which stream type is stopping
1327 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1328
Eric Laurente552edb2014-03-10 17:42:56 -07001329 // handle special case for sonification while in call
1330 if (isInCall()) {
1331 handleIncallSonification(stream, false, false);
1332 }
1333
1334 if (outputDesc->mRefCount[stream] > 0) {
1335 // decrement usage count of this stream on the output
1336 outputDesc->changeRefCount(stream, -1);
1337 // store time at which the stream was stopped - see isStreamActive()
1338 if (outputDesc->mRefCount[stream] == 0) {
Eric Laurentc722f302014-12-10 11:21:49 -08001339 // Automatically disable the remote submix input when output is stopped on a
1340 // re routing mix of type MIX_TYPE_RECORDERS
1341 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1342 outputDesc->mPolicyMix != NULL &&
1343 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001344 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001345 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1346 outputDesc->mPolicyMix->mRegistrationId);
1347 }
1348
Eric Laurente552edb2014-03-10 17:42:56 -07001349 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001350 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001351 // delay the device switch by twice the latency because stopOutput() is executed when
1352 // the track stop() command is received and at that time the audio track buffer can
1353 // still contain data that needs to be drained. The latency only covers the audio HAL
1354 // and kernel buffers. Also the latency does not always include additional delay in the
1355 // audio path (audio DSP, CODEC ...)
1356 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1357
1358 // force restoring the device selection on other active outputs if it differs from the
1359 // one being selected for this output
1360 for (size_t i = 0; i < mOutputs.size(); i++) {
1361 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001362 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001363 if (curOutput != output &&
1364 desc->isActive() &&
1365 outputDesc->sharesHwModuleWith(desc) &&
1366 (newDevice != desc->device())) {
1367 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001368 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001369 true,
1370 outputDesc->mLatency*2);
1371 }
1372 }
1373 // update the outputs if stopping one with a stream that can affect notification routing
1374 handleNotificationRoutingForStream(stream);
1375 }
1376 return NO_ERROR;
1377 } else {
1378 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1379 return INVALID_OPERATION;
1380 }
1381}
1382
Eric Laurente83b55d2014-11-14 10:06:21 -08001383void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001384 audio_stream_type_t stream __unused,
1385 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001386{
1387 ALOGV("releaseOutput() %d", output);
1388 ssize_t index = mOutputs.indexOfKey(output);
1389 if (index < 0) {
1390 ALOGW("releaseOutput() releasing unknown output %d", output);
1391 return;
1392 }
1393
1394#ifdef AUDIO_POLICY_TEST
1395 int testIndex = testOutputIndex(output);
1396 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001397 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001398 if (outputDesc->isActive()) {
1399 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001400 mOutputs.removeItem(output);
1401 mTestOutputs[testIndex] = 0;
1402 }
1403 return;
1404 }
1405#endif //AUDIO_POLICY_TEST
1406
Eric Laurent1f2f2232014-06-02 12:01:23 -07001407 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001408 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001409 if (desc->mDirectOpenCount <= 0) {
1410 ALOGW("releaseOutput() invalid open count %d for output %d",
1411 desc->mDirectOpenCount, output);
1412 return;
1413 }
1414 if (--desc->mDirectOpenCount == 0) {
1415 closeOutput(output);
1416 // If effects where present on the output, audioflinger moved them to the primary
1417 // output by default: move them back to the appropriate output.
1418 audio_io_handle_t dstOutput = getOutputForEffect();
1419 if (dstOutput != mPrimaryOutput) {
1420 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1421 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001422 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001423 }
1424 }
1425}
1426
1427
Eric Laurentcaf7f482014-11-25 17:50:47 -08001428status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1429 audio_io_handle_t *input,
1430 audio_session_t session,
1431 uint32_t samplingRate,
1432 audio_format_t format,
1433 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001434 audio_input_flags_t flags,
1435 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001436{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001437 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1438 "session %d, flags %#x",
1439 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001440
Eric Laurentcaf7f482014-11-25 17:50:47 -08001441 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001442 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001443 audio_devices_t device;
1444 // handle legacy remote submix case where the address was not always specified
1445 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001446 bool isSoundTrigger = false;
Eric Laurentc447ded2015-01-06 08:47:05 -08001447 audio_source_t inputSource = attr->source;
1448 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001449 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001450
Eric Laurentc447ded2015-01-06 08:47:05 -08001451 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1452 inputSource = AUDIO_SOURCE_MIC;
1453 }
1454 halInputSource = inputSource;
1455
1456 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001457 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1458 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1459 address = String8(attr->tags + strlen("addr="));
1460 ssize_t index = mPolicyMixes.indexOfKey(address);
1461 if (index < 0) {
1462 ALOGW("getInputForAttr() no policy for address %s", address.string());
1463 return BAD_VALUE;
1464 }
Eric Laurentc722f302014-12-10 11:21:49 -08001465 if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) {
1466 ALOGW("getInputForAttr() bad policy mix type for address %s", address.string());
1467 return BAD_VALUE;
1468 }
1469 policyMix = &mPolicyMixes[index]->mMix;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001470 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001471 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001472 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001473 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001474 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001475 return BAD_VALUE;
1476 }
Eric Laurentc722f302014-12-10 11:21:49 -08001477 if (policyMix != NULL) {
1478 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001479 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1480 // there is an external policy, but this input is attached to a mix of recorders,
1481 // meaning it receives audio injected into the framework, so the recorder doesn't
1482 // know about it and is therefore considered "legacy"
1483 *inputType = API_INPUT_LEGACY;
1484 } else {
1485 // recording a mix of players defined by an external policy, we're rerouting for
1486 // an external policy
1487 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1488 }
Eric Laurentc722f302014-12-10 11:21:49 -08001489 } else if (audio_is_remote_submix_device(device)) {
1490 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001491 *inputType = API_INPUT_MIX_CAPTURE;
1492 } else {
1493 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001494 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001495 // adapt channel selection to input source
Eric Laurentc447ded2015-01-06 08:47:05 -08001496 switch (inputSource) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001497 case AUDIO_SOURCE_VOICE_UPLINK:
1498 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1499 break;
1500 case AUDIO_SOURCE_VOICE_DOWNLINK:
1501 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1502 break;
1503 case AUDIO_SOURCE_VOICE_CALL:
1504 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1505 break;
1506 default:
1507 break;
1508 }
Eric Laurentc447ded2015-01-06 08:47:05 -08001509 if (inputSource == AUDIO_SOURCE_HOTWORD) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001510 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1511 if (index >= 0) {
1512 *input = mSoundTriggerSessions.valueFor(session);
1513 isSoundTrigger = true;
1514 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1515 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1516 } else {
1517 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1518 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001519 }
1520 }
1521
Eric Laurent275e8e92014-11-30 15:14:47 -08001522 sp<IOProfile> profile = getInputProfile(device, address,
1523 samplingRate, format, channelMask,
1524 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001525 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001526 //retry without flags
1527 audio_input_flags_t log_flags = flags;
1528 flags = AUDIO_INPUT_FLAG_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001529 profile = getInputProfile(device, address,
1530 samplingRate, format, channelMask,
1531 flags);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001532 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001533 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1534 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001535 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001536 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001537 }
Eric Laurente552edb2014-03-10 17:42:56 -07001538 }
1539
1540 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001541 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1542 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001543 }
1544
1545 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1546 config.sample_rate = samplingRate;
1547 config.channel_mask = channelMask;
1548 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001549
Eric Laurentcf2c0212014-07-25 16:20:43 -07001550 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001551 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001552 &config,
1553 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001554 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001555 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001556 flags);
1557
1558 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001559 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001560 (samplingRate != config.sample_rate) ||
1561 (format != config.format) ||
1562 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001563 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001564 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001565 if (*input != AUDIO_IO_HANDLE_NONE) {
1566 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001567 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001568 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001569 }
1570
Eric Laurent1f2f2232014-06-02 12:01:23 -07001571 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentc447ded2015-01-06 08:47:05 -08001572 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001573 inputDesc->mRefCount = 0;
1574 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001575 inputDesc->mSamplingRate = samplingRate;
1576 inputDesc->mFormat = format;
1577 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001578 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001579 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001580 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001581 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001582
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001583 ALOGV("getInputForAttr() returns input type = %d", inputType);
1584
Eric Laurentcaf7f482014-11-25 17:50:47 -08001585 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001586 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001587 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001588}
1589
Eric Laurent4dc68062014-07-28 17:26:49 -07001590status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1591 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001592{
1593 ALOGV("startInput() input %d", input);
1594 ssize_t index = mInputs.indexOfKey(input);
1595 if (index < 0) {
1596 ALOGW("startInput() unknown input %d", input);
1597 return BAD_VALUE;
1598 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001599 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001600
Eric Laurentc722f302014-12-10 11:21:49 -08001601 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001602 if (index < 0) {
1603 ALOGW("startInput() unknown session %d on input %d", session, input);
1604 return BAD_VALUE;
1605 }
1606
Glenn Kasten74a8e252014-07-24 14:09:55 -07001607 // virtual input devices are compatible with other input devices
1608 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1609
1610 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001611 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001612 if (activeInput != 0 && activeInput != input) {
1613
1614 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1615 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001616 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001617 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001618 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurentc722f302014-12-10 11:21:49 -08001619 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1620 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001621 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001622 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001623 return INVALID_OPERATION;
1624 }
1625 }
1626 }
1627
Glenn Kasten74a8e252014-07-24 14:09:55 -07001628 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001629 if (activeInputsCount() == 0) {
1630 SoundTrigger::setCaptureState(true);
1631 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001632 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001633
Eric Laurentc722f302014-12-10 11:21:49 -08001634 // automatically enable the remote submix output when input is started if not
1635 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001636 // For remote submix (a virtual device), we open only one input per capture request.
1637 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001638 String8 address = String8("");
1639 if (inputDesc->mPolicyMix == NULL) {
1640 address = String8("0");
1641 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1642 address = inputDesc->mPolicyMix->mRegistrationId;
1643 }
1644 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001645 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001646 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1647 address);
1648 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001649 }
Eric Laurente552edb2014-03-10 17:42:56 -07001650 }
1651
Eric Laurente552edb2014-03-10 17:42:56 -07001652 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1653
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001654 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001655 return NO_ERROR;
1656}
1657
Eric Laurent4dc68062014-07-28 17:26:49 -07001658status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1659 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001660{
1661 ALOGV("stopInput() input %d", input);
1662 ssize_t index = mInputs.indexOfKey(input);
1663 if (index < 0) {
1664 ALOGW("stopInput() unknown input %d", input);
1665 return BAD_VALUE;
1666 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001667 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001668
Eric Laurentc722f302014-12-10 11:21:49 -08001669 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001670 if (index < 0) {
1671 ALOGW("stopInput() unknown session %d on input %d", session, input);
1672 return BAD_VALUE;
1673 }
1674
Eric Laurente552edb2014-03-10 17:42:56 -07001675 if (inputDesc->mRefCount == 0) {
1676 ALOGW("stopInput() input %d already stopped", input);
1677 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001678 }
1679
1680 inputDesc->mRefCount--;
1681 if (inputDesc->mRefCount == 0) {
1682
Eric Laurentc722f302014-12-10 11:21:49 -08001683 // automatically disable the remote submix output when input is stopped if not
1684 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001685 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001686 String8 address = String8("");
1687 if (inputDesc->mPolicyMix == NULL) {
1688 address = String8("0");
1689 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1690 address = inputDesc->mPolicyMix->mRegistrationId;
1691 }
1692 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001693 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001694 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1695 address);
1696 }
Eric Laurente552edb2014-03-10 17:42:56 -07001697 }
1698
Eric Laurent1c333e22014-05-20 10:48:17 -07001699 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001700
1701 if (activeInputsCount() == 0) {
1702 SoundTrigger::setCaptureState(false);
1703 }
Eric Laurente552edb2014-03-10 17:42:56 -07001704 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001705 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001706}
1707
Eric Laurent4dc68062014-07-28 17:26:49 -07001708void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1709 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001710{
1711 ALOGV("releaseInput() %d", input);
1712 ssize_t index = mInputs.indexOfKey(input);
1713 if (index < 0) {
1714 ALOGW("releaseInput() releasing unknown input %d", input);
1715 return;
1716 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001717 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1718 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001719
Eric Laurentc722f302014-12-10 11:21:49 -08001720 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001721 if (index < 0) {
1722 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1723 return;
1724 }
Eric Laurentc722f302014-12-10 11:21:49 -08001725 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001726 if (inputDesc->mOpenRefCount == 0) {
1727 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1728 return;
1729 }
1730 inputDesc->mOpenRefCount--;
1731 if (inputDesc->mOpenRefCount > 0) {
1732 ALOGV("releaseInput() exit > 0");
1733 return;
1734 }
1735
Eric Laurent05b90f82014-08-27 15:32:29 -07001736 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001737 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001738 ALOGV("releaseInput() exit");
1739}
1740
Eric Laurentd4692962014-05-05 18:13:44 -07001741void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001742 bool patchRemoved = false;
1743
Eric Laurentd4692962014-05-05 18:13:44 -07001744 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001745 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1746 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1747 if (patch_index >= 0) {
1748 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1749 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1750 mAudioPatches.removeItemsAt(patch_index);
1751 patchRemoved = true;
1752 }
Eric Laurentd4692962014-05-05 18:13:44 -07001753 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1754 }
1755 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001756 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001757
1758 if (patchRemoved) {
1759 mpClientInterface->onAudioPatchListUpdate();
1760 }
Eric Laurentd4692962014-05-05 18:13:44 -07001761}
1762
Eric Laurente0720872014-03-11 09:30:41 -07001763void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001764 int indexMin,
1765 int indexMax)
1766{
1767 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1768 if (indexMin < 0 || indexMin >= indexMax) {
1769 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1770 return;
1771 }
1772 mStreams[stream].mIndexMin = indexMin;
1773 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001774 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1775 if (stream == AUDIO_STREAM_MUSIC) {
1776 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1777 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1778 }
Eric Laurente552edb2014-03-10 17:42:56 -07001779}
1780
Eric Laurente0720872014-03-11 09:30:41 -07001781status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001782 int index,
1783 audio_devices_t device)
1784{
1785
1786 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1787 return BAD_VALUE;
1788 }
1789 if (!audio_is_output_device(device)) {
1790 return BAD_VALUE;
1791 }
1792
1793 // Force max volume if stream cannot be muted
1794 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1795
1796 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1797 stream, device, index);
1798
1799 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1800 // clear all device specific values
1801 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1802 mStreams[stream].mIndexCur.clear();
1803 }
1804 mStreams[stream].mIndexCur.add(device, index);
1805
Eric Laurent31551f82014-10-10 18:21:56 -07001806 // update volume on all outputs whose current device is also selected by the same
1807 // strategy as the device specified by the caller
1808 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001809
1810
1811 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1812 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1813 if (stream == AUDIO_STREAM_MUSIC) {
1814 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1815 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1816 }
1817 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1818 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001819 return NO_ERROR;
1820 }
Eric Laurente552edb2014-03-10 17:42:56 -07001821 status_t status = NO_ERROR;
1822 for (size_t i = 0; i < mOutputs.size(); i++) {
1823 audio_devices_t curDevice =
1824 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001825 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001826 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1827 if (volStatus != NO_ERROR) {
1828 status = volStatus;
1829 }
1830 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001831 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1832 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1833 index, mOutputs.keyAt(i), curDevice);
1834 }
Eric Laurente552edb2014-03-10 17:42:56 -07001835 }
1836 return status;
1837}
1838
Eric Laurente0720872014-03-11 09:30:41 -07001839status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001840 int *index,
1841 audio_devices_t device)
1842{
1843 if (index == NULL) {
1844 return BAD_VALUE;
1845 }
1846 if (!audio_is_output_device(device)) {
1847 return BAD_VALUE;
1848 }
1849 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1850 // the strategy the stream belongs to.
1851 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1852 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1853 }
1854 device = getDeviceForVolume(device);
1855
1856 *index = mStreams[stream].getVolumeIndex(device);
1857 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1858 return NO_ERROR;
1859}
1860
Eric Laurente0720872014-03-11 09:30:41 -07001861audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001862 const SortedVector<audio_io_handle_t>& outputs)
1863{
1864 // select one output among several suitable for global effects.
1865 // The priority is as follows:
1866 // 1: An offloaded output. If the effect ends up not being offloadable,
1867 // AudioFlinger will invalidate the track and the offloaded output
1868 // will be closed causing the effect to be moved to a PCM output.
1869 // 2: A deep buffer output
1870 // 3: the first output in the list
1871
1872 if (outputs.size() == 0) {
1873 return 0;
1874 }
1875
1876 audio_io_handle_t outputOffloaded = 0;
1877 audio_io_handle_t outputDeepBuffer = 0;
1878
1879 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001880 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001881 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001882 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1883 outputOffloaded = outputs[i];
1884 }
1885 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1886 outputDeepBuffer = outputs[i];
1887 }
1888 }
1889
1890 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1891 outputOffloaded, outputDeepBuffer);
1892 if (outputOffloaded != 0) {
1893 return outputOffloaded;
1894 }
1895 if (outputDeepBuffer != 0) {
1896 return outputDeepBuffer;
1897 }
1898
1899 return outputs[0];
1900}
1901
Eric Laurente0720872014-03-11 09:30:41 -07001902audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001903{
1904 // apply simple rule where global effects are attached to the same output as MUSIC streams
1905
Eric Laurent3b73df72014-03-11 09:06:29 -07001906 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001907 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1908 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1909
1910 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1911 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1912 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1913
1914 return output;
1915}
1916
Eric Laurente0720872014-03-11 09:30:41 -07001917status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001918 audio_io_handle_t io,
1919 uint32_t strategy,
1920 int session,
1921 int id)
1922{
1923 ssize_t index = mOutputs.indexOfKey(io);
1924 if (index < 0) {
1925 index = mInputs.indexOfKey(io);
1926 if (index < 0) {
1927 ALOGW("registerEffect() unknown io %d", io);
1928 return INVALID_OPERATION;
1929 }
1930 }
1931
1932 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1933 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1934 desc->name, desc->memoryUsage);
1935 return INVALID_OPERATION;
1936 }
1937 mTotalEffectsMemory += desc->memoryUsage;
1938 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1939 desc->name, io, strategy, session, id);
1940 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1941
Eric Laurent1f2f2232014-06-02 12:01:23 -07001942 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1943 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1944 effectDesc->mIo = io;
1945 effectDesc->mStrategy = (routing_strategy)strategy;
1946 effectDesc->mSession = session;
1947 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001948
Eric Laurent1f2f2232014-06-02 12:01:23 -07001949 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001950
1951 return NO_ERROR;
1952}
1953
Eric Laurente0720872014-03-11 09:30:41 -07001954status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001955{
1956 ssize_t index = mEffects.indexOfKey(id);
1957 if (index < 0) {
1958 ALOGW("unregisterEffect() unknown effect ID %d", id);
1959 return INVALID_OPERATION;
1960 }
1961
Eric Laurent1f2f2232014-06-02 12:01:23 -07001962 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001963
Eric Laurent1f2f2232014-06-02 12:01:23 -07001964 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001965
Eric Laurent1f2f2232014-06-02 12:01:23 -07001966 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001967 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001968 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1969 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001970 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001971 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001972 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001973 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001974
1975 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001976
1977 return NO_ERROR;
1978}
1979
Eric Laurente0720872014-03-11 09:30:41 -07001980status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001981{
1982 ssize_t index = mEffects.indexOfKey(id);
1983 if (index < 0) {
1984 ALOGW("unregisterEffect() unknown effect ID %d", id);
1985 return INVALID_OPERATION;
1986 }
1987
1988 return setEffectEnabled(mEffects.valueAt(index), enabled);
1989}
1990
Eric Laurent1f2f2232014-06-02 12:01:23 -07001991status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001992{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001993 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001994 ALOGV("setEffectEnabled(%s) effect already %s",
1995 enabled?"true":"false", enabled?"enabled":"disabled");
1996 return INVALID_OPERATION;
1997 }
1998
1999 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002000 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002001 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002002 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07002003 return INVALID_OPERATION;
2004 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002005 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002006 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
2007 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002008 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07002009 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002010 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
2011 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002012 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002013 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002014 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
2015 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002016 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07002017 return NO_ERROR;
2018}
2019
Eric Laurente0720872014-03-11 09:30:41 -07002020bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07002021{
2022 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002023 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
2024 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
2025 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002026 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002027 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07002028 return true;
2029 }
2030 }
2031 return false;
2032}
2033
Eric Laurente0720872014-03-11 09:30:41 -07002034bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002035{
2036 nsecs_t sysTime = systemTime();
2037 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002038 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07002039 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002040 return true;
2041 }
2042 }
2043 return false;
2044}
2045
Eric Laurente0720872014-03-11 09:30:41 -07002046bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07002047 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002048{
2049 nsecs_t sysTime = systemTime();
2050 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002051 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002052 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002053 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurentc722f302014-12-10 11:21:49 -08002054 // do not consider re routing (when the output is going to a dynamic policy)
2055 // as "remote playback"
2056 if (outputDesc->mPolicyMix == NULL) {
Jean-Michel Trivi1767df72014-12-09 18:11:49 -08002057 return true;
2058 }
Eric Laurente552edb2014-03-10 17:42:56 -07002059 }
2060 }
2061 return false;
2062}
2063
Eric Laurente0720872014-03-11 09:30:41 -07002064bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002065{
2066 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002067 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002068 if (inputDescriptor->mRefCount == 0) {
2069 continue;
2070 }
2071 if (inputDescriptor->mInputSource == (int)source) {
Eric Laurente552edb2014-03-10 17:42:56 -07002072 return true;
2073 }
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002074 // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it
2075 // corresponds to an active capture triggered by a hardware hotword recognition
2076 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) &&
2077 (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) {
2078 // FIXME: we should not assume that the first session is the active one and keep
2079 // activity count per session. Same in startInput().
2080 ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0));
2081 if (index >= 0) {
2082 return true;
2083 }
2084 }
Eric Laurente552edb2014-03-10 17:42:56 -07002085 }
2086 return false;
2087}
2088
Eric Laurent275e8e92014-11-30 15:14:47 -08002089// Register a list of custom mixes with their attributes and format.
2090// When a mix is registered, corresponding input and output profiles are
2091// added to the remote submix hw module. The profile contains only the
2092// parameters (sampling rate, format...) specified by the mix.
2093// The corresponding input remote submix device is also connected.
2094//
2095// When a remote submix device is connected, the address is checked to select the
2096// appropriate profile and the corresponding input or output stream is opened.
2097//
2098// When capture starts, getInputForAttr() will:
2099// - 1 look for a mix matching the address passed in attribtutes tags if any
2100// - 2 if none found, getDeviceForInputSource() will:
2101// - 2.1 look for a mix matching the attributes source
2102// - 2.2 if none found, default to device selection by policy rules
2103// At this time, the corresponding output remote submix device is also connected
2104// and active playback use cases can be transferred to this mix if needed when reconnecting
2105// after AudioTracks are invalidated
2106//
2107// When playback starts, getOutputForAttr() will:
2108// - 1 look for a mix matching the address passed in attribtutes tags if any
2109// - 2 if none found, look for a mix matching the attributes usage
2110// - 3 if none found, default to device and output selection by policy rules.
2111
2112status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2113{
2114 sp<HwModule> module;
2115 for (size_t i = 0; i < mHwModules.size(); i++) {
2116 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2117 mHwModules[i]->mHandle != 0) {
2118 module = mHwModules[i];
2119 break;
2120 }
2121 }
2122
2123 if (module == 0) {
2124 return INVALID_OPERATION;
2125 }
2126
2127 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2128
2129 for (size_t i = 0; i < mixes.size(); i++) {
2130 String8 address = mixes[i].mRegistrationId;
2131 ssize_t index = mPolicyMixes.indexOfKey(address);
2132 if (index >= 0) {
2133 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2134 continue;
2135 }
2136 audio_config_t outputConfig = mixes[i].mFormat;
2137 audio_config_t inputConfig = mixes[i].mFormat;
2138 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2139 // stereo and let audio flinger do the channel conversion if needed.
2140 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2141 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2142 module->addOutputProfile(address, &outputConfig,
2143 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2144 module->addInputProfile(address, &inputConfig,
2145 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2146 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2147 policyMix->mMix = mixes[i];
2148 mPolicyMixes.add(address, policyMix);
Eric Laurentc722f302014-12-10 11:21:49 -08002149 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002150 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002151 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2152 address.string());
2153 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002154 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002155 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2156 address.string());
2157 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002158 }
2159 return NO_ERROR;
2160}
2161
2162status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2163{
2164 sp<HwModule> module;
2165 for (size_t i = 0; i < mHwModules.size(); i++) {
2166 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2167 mHwModules[i]->mHandle != 0) {
2168 module = mHwModules[i];
2169 break;
2170 }
2171 }
2172
2173 if (module == 0) {
2174 return INVALID_OPERATION;
2175 }
2176
2177 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2178
2179 for (size_t i = 0; i < mixes.size(); i++) {
2180 String8 address = mixes[i].mRegistrationId;
2181 ssize_t index = mPolicyMixes.indexOfKey(address);
2182 if (index < 0) {
2183 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2184 continue;
2185 }
2186
2187 mPolicyMixes.removeItemsAt(index);
2188
Eric Laurentc722f302014-12-10 11:21:49 -08002189 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2190 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2191 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002192 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002193 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2194 address.string());
2195 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002196
2197 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2198 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2199 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002200 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002201 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2202 address.string());
2203 }
2204 module->removeOutputProfile(address);
2205 module->removeInputProfile(address);
2206 }
2207 return NO_ERROR;
2208}
2209
Eric Laurente552edb2014-03-10 17:42:56 -07002210
Eric Laurente0720872014-03-11 09:30:41 -07002211status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002212{
2213 const size_t SIZE = 256;
2214 char buffer[SIZE];
2215 String8 result;
2216
2217 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2218 result.append(buffer);
2219
2220 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2221 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002222 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2223 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002224 snprintf(buffer, SIZE, " Force use for communications %d\n",
2225 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002226 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002227 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002228 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002229 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07002230 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002231 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07002232 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002233 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002234 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002235 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2236 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2237 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002238
Eric Laurent3a4311c2014-03-17 12:00:47 -07002239 snprintf(buffer, SIZE, " Available output devices:\n");
2240 result.append(buffer);
2241 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002242 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002243 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002244 }
2245 snprintf(buffer, SIZE, "\n Available input devices:\n");
2246 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002247 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002248 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002249 }
Eric Laurente552edb2014-03-10 17:42:56 -07002250
2251 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2252 write(fd, buffer, strlen(buffer));
2253 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002254 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002255 write(fd, buffer, strlen(buffer));
2256 mHwModules[i]->dump(fd);
2257 }
2258
2259 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2260 write(fd, buffer, strlen(buffer));
2261 for (size_t i = 0; i < mOutputs.size(); i++) {
2262 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2263 write(fd, buffer, strlen(buffer));
2264 mOutputs.valueAt(i)->dump(fd);
2265 }
2266
2267 snprintf(buffer, SIZE, "\nInputs dump:\n");
2268 write(fd, buffer, strlen(buffer));
2269 for (size_t i = 0; i < mInputs.size(); i++) {
2270 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2271 write(fd, buffer, strlen(buffer));
2272 mInputs.valueAt(i)->dump(fd);
2273 }
2274
2275 snprintf(buffer, SIZE, "\nStreams dump:\n");
2276 write(fd, buffer, strlen(buffer));
2277 snprintf(buffer, SIZE,
2278 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2279 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002280 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002281 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002282 write(fd, buffer, strlen(buffer));
2283 mStreams[i].dump(fd);
2284 }
2285
2286 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2287 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2288 write(fd, buffer, strlen(buffer));
2289
2290 snprintf(buffer, SIZE, "Registered effects:\n");
2291 write(fd, buffer, strlen(buffer));
2292 for (size_t i = 0; i < mEffects.size(); i++) {
2293 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2294 write(fd, buffer, strlen(buffer));
2295 mEffects.valueAt(i)->dump(fd);
2296 }
2297
Eric Laurent4d416952014-08-10 14:07:09 -07002298 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2299 write(fd, buffer, strlen(buffer));
2300 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2301 mAudioPatches[i]->dump(fd, 2, i);
2302 }
Eric Laurente552edb2014-03-10 17:42:56 -07002303
2304 return NO_ERROR;
2305}
2306
2307// This function checks for the parameters which can be offloaded.
2308// This can be enhanced depending on the capability of the DSP and policy
2309// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002310bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002311{
2312 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002313 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002314 offloadInfo.sample_rate, offloadInfo.channel_mask,
2315 offloadInfo.format,
2316 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2317 offloadInfo.has_video);
2318
2319 // Check if offload has been disabled
2320 char propValue[PROPERTY_VALUE_MAX];
2321 if (property_get("audio.offload.disable", propValue, "0")) {
2322 if (atoi(propValue) != 0) {
2323 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2324 return false;
2325 }
2326 }
2327
2328 // Check if stream type is music, then only allow offload as of now.
2329 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2330 {
2331 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2332 return false;
2333 }
2334
2335 //TODO: enable audio offloading with video when ready
2336 if (offloadInfo.has_video)
2337 {
2338 ALOGV("isOffloadSupported: has_video == true, returning false");
2339 return false;
2340 }
2341
2342 //If duration is less than minimum value defined in property, return false
2343 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2344 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2345 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2346 return false;
2347 }
2348 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2349 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2350 return false;
2351 }
2352
2353 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2354 // creating an offloaded track and tearing it down immediately after start when audioflinger
2355 // detects there is an active non offloadable effect.
2356 // FIXME: We should check the audio session here but we do not have it in this context.
2357 // This may prevent offloading in rare situations where effects are left active by apps
2358 // in the background.
2359 if (isNonOffloadableEffectEnabled()) {
2360 return false;
2361 }
2362
2363 // See if there is a profile to support this.
2364 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002365 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002366 offloadInfo.sample_rate,
2367 offloadInfo.format,
2368 offloadInfo.channel_mask,
2369 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002370 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2371 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002372}
2373
Eric Laurent6a94d692014-05-20 11:18:06 -07002374status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2375 audio_port_type_t type,
2376 unsigned int *num_ports,
2377 struct audio_port *ports,
2378 unsigned int *generation)
2379{
2380 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2381 generation == NULL) {
2382 return BAD_VALUE;
2383 }
2384 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2385 if (ports == NULL) {
2386 *num_ports = 0;
2387 }
2388
2389 size_t portsWritten = 0;
2390 size_t portsMax = *num_ports;
2391 *num_ports = 0;
2392 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2393 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2394 for (size_t i = 0;
2395 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2396 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2397 }
2398 *num_ports += mAvailableOutputDevices.size();
2399 }
2400 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2401 for (size_t i = 0;
2402 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2403 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2404 }
2405 *num_ports += mAvailableInputDevices.size();
2406 }
2407 }
2408 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2409 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2410 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2411 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2412 }
2413 *num_ports += mInputs.size();
2414 }
2415 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002416 size_t numOutputs = 0;
2417 for (size_t i = 0; i < mOutputs.size(); i++) {
2418 if (!mOutputs[i]->isDuplicated()) {
2419 numOutputs++;
2420 if (portsWritten < portsMax) {
2421 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2422 }
2423 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002424 }
Eric Laurent84c70242014-06-23 08:46:27 -07002425 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002426 }
2427 }
2428 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002429 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002430 return NO_ERROR;
2431}
2432
2433status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2434{
2435 return NO_ERROR;
2436}
2437
Eric Laurent1f2f2232014-06-02 12:01:23 -07002438sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002439 audio_port_handle_t id) const
2440{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002441 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002442 for (size_t i = 0; i < mOutputs.size(); i++) {
2443 outputDesc = mOutputs.valueAt(i);
2444 if (outputDesc->mId == id) {
2445 break;
2446 }
2447 }
2448 return outputDesc;
2449}
2450
Eric Laurent1f2f2232014-06-02 12:01:23 -07002451sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002452 audio_port_handle_t id) const
2453{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002454 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002455 for (size_t i = 0; i < mInputs.size(); i++) {
2456 inputDesc = mInputs.valueAt(i);
2457 if (inputDesc->mId == id) {
2458 break;
2459 }
2460 }
2461 return inputDesc;
2462}
2463
Eric Laurent1f2f2232014-06-02 12:01:23 -07002464sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2465 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002466{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002467 sp <HwModule> module;
2468
Eric Laurent6a94d692014-05-20 11:18:06 -07002469 for (size_t i = 0; i < mHwModules.size(); i++) {
2470 if (mHwModules[i]->mHandle == 0) {
2471 continue;
2472 }
2473 if (audio_is_output_device(device)) {
2474 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2475 {
2476 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2477 return mHwModules[i];
2478 }
2479 }
2480 } else {
2481 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2482 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2483 device & ~AUDIO_DEVICE_BIT_IN) {
2484 return mHwModules[i];
2485 }
2486 }
2487 }
2488 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002489 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002490}
2491
Eric Laurent1f2f2232014-06-02 12:01:23 -07002492sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002493{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002494 sp <HwModule> module;
2495
Eric Laurent1afeecb2014-05-14 08:52:28 -07002496 for (size_t i = 0; i < mHwModules.size(); i++)
2497 {
2498 if (strcmp(mHwModules[i]->mName, name) == 0) {
2499 return mHwModules[i];
2500 }
2501 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002502 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002503}
2504
Eric Laurentc2730ba2014-07-20 15:47:07 -07002505audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2506{
2507 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2508 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2509 return devices & mAvailableOutputDevices.types();
2510}
2511
2512audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2513{
2514 audio_module_handle_t primaryHandle =
2515 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2516 audio_devices_t devices = AUDIO_DEVICE_NONE;
2517 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2518 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2519 devices |= mAvailableInputDevices[i]->mDeviceType;
2520 }
2521 }
2522 return devices;
2523}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002524
Eric Laurent6a94d692014-05-20 11:18:06 -07002525status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2526 audio_patch_handle_t *handle,
2527 uid_t uid)
2528{
2529 ALOGV("createAudioPatch()");
2530
2531 if (handle == NULL || patch == NULL) {
2532 return BAD_VALUE;
2533 }
2534 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2535
Eric Laurent874c42872014-08-08 15:13:39 -07002536 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2537 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2538 return BAD_VALUE;
2539 }
2540 // only one source per audio patch supported for now
2541 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002542 return INVALID_OPERATION;
2543 }
Eric Laurent874c42872014-08-08 15:13:39 -07002544
2545 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002546 return INVALID_OPERATION;
2547 }
Eric Laurent874c42872014-08-08 15:13:39 -07002548 for (size_t i = 0; i < patch->num_sinks; i++) {
2549 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2550 return INVALID_OPERATION;
2551 }
2552 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002553
2554 sp<AudioPatch> patchDesc;
2555 ssize_t index = mAudioPatches.indexOfKey(*handle);
2556
Eric Laurent6a94d692014-05-20 11:18:06 -07002557 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2558 patch->sources[0].role,
2559 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002560#if LOG_NDEBUG == 0
2561 for (size_t i = 0; i < patch->num_sinks; i++) {
2562 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2563 patch->sinks[i].role,
2564 patch->sinks[i].type);
2565 }
2566#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002567
2568 if (index >= 0) {
2569 patchDesc = mAudioPatches.valueAt(index);
2570 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2571 mUidCached, patchDesc->mUid, uid);
2572 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2573 return INVALID_OPERATION;
2574 }
2575 } else {
2576 *handle = 0;
2577 }
2578
2579 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002580 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002581 if (outputDesc == NULL) {
2582 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2583 return BAD_VALUE;
2584 }
Eric Laurent84c70242014-06-23 08:46:27 -07002585 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2586 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002587 if (patchDesc != 0) {
2588 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2589 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2590 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2591 return BAD_VALUE;
2592 }
2593 }
Eric Laurent874c42872014-08-08 15:13:39 -07002594 DeviceVector devices;
2595 for (size_t i = 0; i < patch->num_sinks; i++) {
2596 // Only support mix to devices connection
2597 // TODO add support for mix to mix connection
2598 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2599 ALOGV("createAudioPatch() source mix but sink is not a device");
2600 return INVALID_OPERATION;
2601 }
2602 sp<DeviceDescriptor> devDesc =
2603 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2604 if (devDesc == 0) {
2605 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2606 return BAD_VALUE;
2607 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002608
Eric Laurent874c42872014-08-08 15:13:39 -07002609 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002610 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002611 patch->sources[0].sample_rate,
2612 NULL, // updatedSamplingRate
2613 patch->sources[0].format,
2614 patch->sources[0].channel_mask,
2615 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2616 ALOGV("createAudioPatch() profile not supported for device %08x",
2617 devDesc->mDeviceType);
2618 return INVALID_OPERATION;
2619 }
2620 devices.add(devDesc);
2621 }
2622 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002623 return INVALID_OPERATION;
2624 }
Eric Laurent874c42872014-08-08 15:13:39 -07002625
Eric Laurent6a94d692014-05-20 11:18:06 -07002626 // TODO: reconfigure output format and channels here
2627 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002628 devices.types(), outputDesc->mIoHandle);
2629 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002630 index = mAudioPatches.indexOfKey(*handle);
2631 if (index >= 0) {
2632 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2633 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2634 }
2635 patchDesc = mAudioPatches.valueAt(index);
2636 patchDesc->mUid = uid;
2637 ALOGV("createAudioPatch() success");
2638 } else {
2639 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2640 return INVALID_OPERATION;
2641 }
2642 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2643 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2644 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002645 // only one sink supported when connecting an input device to a mix
2646 if (patch->num_sinks > 1) {
2647 return INVALID_OPERATION;
2648 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002649 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002650 if (inputDesc == NULL) {
2651 return BAD_VALUE;
2652 }
2653 if (patchDesc != 0) {
2654 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2655 return BAD_VALUE;
2656 }
2657 }
2658 sp<DeviceDescriptor> devDesc =
2659 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2660 if (devDesc == 0) {
2661 return BAD_VALUE;
2662 }
2663
Eric Laurent84c70242014-06-23 08:46:27 -07002664 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002665 devDesc->mAddress,
2666 patch->sinks[0].sample_rate,
2667 NULL, /*updatedSampleRate*/
2668 patch->sinks[0].format,
2669 patch->sinks[0].channel_mask,
2670 // FIXME for the parameter type,
2671 // and the NONE
2672 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002673 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002674 return INVALID_OPERATION;
2675 }
2676 // TODO: reconfigure output format and channels here
2677 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002678 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002679 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002680 index = mAudioPatches.indexOfKey(*handle);
2681 if (index >= 0) {
2682 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2683 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2684 }
2685 patchDesc = mAudioPatches.valueAt(index);
2686 patchDesc->mUid = uid;
2687 ALOGV("createAudioPatch() success");
2688 } else {
2689 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2690 return INVALID_OPERATION;
2691 }
2692 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2693 // device to device connection
2694 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002695 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002696 return BAD_VALUE;
2697 }
2698 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002699 sp<DeviceDescriptor> srcDeviceDesc =
2700 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002701 if (srcDeviceDesc == 0) {
2702 return BAD_VALUE;
2703 }
Eric Laurent874c42872014-08-08 15:13:39 -07002704
Eric Laurent6a94d692014-05-20 11:18:06 -07002705 //update source and sink with our own data as the data passed in the patch may
2706 // be incomplete.
2707 struct audio_patch newPatch = *patch;
2708 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002709
Eric Laurent874c42872014-08-08 15:13:39 -07002710 for (size_t i = 0; i < patch->num_sinks; i++) {
2711 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2712 ALOGV("createAudioPatch() source device but one sink is not a device");
2713 return INVALID_OPERATION;
2714 }
2715
2716 sp<DeviceDescriptor> sinkDeviceDesc =
2717 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2718 if (sinkDeviceDesc == 0) {
2719 return BAD_VALUE;
2720 }
2721 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2722
2723 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2724 // only one sink supported when connected devices across HW modules
2725 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002726 return INVALID_OPERATION;
2727 }
Eric Laurent874c42872014-08-08 15:13:39 -07002728 SortedVector<audio_io_handle_t> outputs =
2729 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2730 mOutputs);
2731 // if the sink device is reachable via an opened output stream, request to go via
2732 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002733 audio_io_handle_t output = selectOutput(outputs,
2734 AUDIO_OUTPUT_FLAG_NONE,
2735 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002736 if (output != AUDIO_IO_HANDLE_NONE) {
2737 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2738 if (outputDesc->isDuplicated()) {
2739 return INVALID_OPERATION;
2740 }
2741 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2742 newPatch.num_sources = 2;
2743 }
Eric Laurent83b88082014-06-20 18:31:16 -07002744 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002745 }
2746 // TODO: check from routing capabilities in config file and other conflicting patches
2747
2748 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2749 if (index >= 0) {
2750 afPatchHandle = patchDesc->mAfPatchHandle;
2751 }
2752
2753 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2754 &afPatchHandle,
2755 0);
2756 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2757 status, afPatchHandle);
2758 if (status == NO_ERROR) {
2759 if (index < 0) {
2760 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2761 &newPatch, uid);
2762 addAudioPatch(patchDesc->mHandle, patchDesc);
2763 } else {
2764 patchDesc->mPatch = newPatch;
2765 }
2766 patchDesc->mAfPatchHandle = afPatchHandle;
2767 *handle = patchDesc->mHandle;
2768 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002769 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002770 } else {
2771 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2772 status);
2773 return INVALID_OPERATION;
2774 }
2775 } else {
2776 return BAD_VALUE;
2777 }
2778 } else {
2779 return BAD_VALUE;
2780 }
2781 return NO_ERROR;
2782}
2783
2784status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2785 uid_t uid)
2786{
2787 ALOGV("releaseAudioPatch() patch %d", handle);
2788
2789 ssize_t index = mAudioPatches.indexOfKey(handle);
2790
2791 if (index < 0) {
2792 return BAD_VALUE;
2793 }
2794 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2795 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2796 mUidCached, patchDesc->mUid, uid);
2797 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2798 return INVALID_OPERATION;
2799 }
2800
2801 struct audio_patch *patch = &patchDesc->mPatch;
2802 patchDesc->mUid = mUidCached;
2803 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002804 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002805 if (outputDesc == NULL) {
2806 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2807 return BAD_VALUE;
2808 }
2809
2810 setOutputDevice(outputDesc->mIoHandle,
2811 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2812 true,
2813 0,
2814 NULL);
2815 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2816 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002817 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002818 if (inputDesc == NULL) {
2819 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2820 return BAD_VALUE;
2821 }
2822 setInputDevice(inputDesc->mIoHandle,
2823 getNewInputDevice(inputDesc->mIoHandle),
2824 true,
2825 NULL);
2826 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2827 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2828 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2829 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2830 status, patchDesc->mAfPatchHandle);
2831 removeAudioPatch(patchDesc->mHandle);
2832 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002833 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002834 } else {
2835 return BAD_VALUE;
2836 }
2837 } else {
2838 return BAD_VALUE;
2839 }
2840 return NO_ERROR;
2841}
2842
2843status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2844 struct audio_patch *patches,
2845 unsigned int *generation)
2846{
2847 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2848 generation == NULL) {
2849 return BAD_VALUE;
2850 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002851 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002852 *num_patches, patches, mAudioPatches.size());
2853 if (patches == NULL) {
2854 *num_patches = 0;
2855 }
2856
2857 size_t patchesWritten = 0;
2858 size_t patchesMax = *num_patches;
2859 for (size_t i = 0;
2860 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2861 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2862 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002863 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002864 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2865 }
2866 *num_patches = mAudioPatches.size();
2867
2868 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002869 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002870 return NO_ERROR;
2871}
2872
Eric Laurente1715a42014-05-20 11:30:42 -07002873status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002874{
Eric Laurente1715a42014-05-20 11:30:42 -07002875 ALOGV("setAudioPortConfig()");
2876
2877 if (config == NULL) {
2878 return BAD_VALUE;
2879 }
2880 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2881 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002882 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2883 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002884 }
2885
Eric Laurenta121f902014-06-03 13:32:54 -07002886 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002887 if (config->type == AUDIO_PORT_TYPE_MIX) {
2888 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002889 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002890 if (outputDesc == NULL) {
2891 return BAD_VALUE;
2892 }
Eric Laurent84c70242014-06-23 08:46:27 -07002893 ALOG_ASSERT(!outputDesc->isDuplicated(),
2894 "setAudioPortConfig() called on duplicated output %d",
2895 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002896 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002897 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002898 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002899 if (inputDesc == NULL) {
2900 return BAD_VALUE;
2901 }
Eric Laurenta121f902014-06-03 13:32:54 -07002902 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002903 } else {
2904 return BAD_VALUE;
2905 }
2906 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2907 sp<DeviceDescriptor> deviceDesc;
2908 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2909 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2910 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2911 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2912 } else {
2913 return BAD_VALUE;
2914 }
2915 if (deviceDesc == NULL) {
2916 return BAD_VALUE;
2917 }
Eric Laurenta121f902014-06-03 13:32:54 -07002918 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002919 } else {
2920 return BAD_VALUE;
2921 }
2922
Eric Laurenta121f902014-06-03 13:32:54 -07002923 struct audio_port_config backupConfig;
2924 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2925 if (status == NO_ERROR) {
2926 struct audio_port_config newConfig;
2927 audioPortConfig->toAudioPortConfig(&newConfig, config);
2928 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002929 }
Eric Laurenta121f902014-06-03 13:32:54 -07002930 if (status != NO_ERROR) {
2931 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002932 }
Eric Laurente1715a42014-05-20 11:30:42 -07002933
2934 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002935}
2936
2937void AudioPolicyManager::clearAudioPatches(uid_t uid)
2938{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002939 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002940 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2941 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002942 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002943 }
2944 }
2945}
2946
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002947status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2948 audio_io_handle_t *ioHandle,
2949 audio_devices_t *device)
2950{
2951 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2952 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002953 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002954
2955 mSoundTriggerSessions.add(*session, *ioHandle);
2956
2957 return NO_ERROR;
2958}
2959
2960status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2961{
2962 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2963 if (index < 0) {
2964 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2965 return BAD_VALUE;
2966 }
2967
2968 mSoundTriggerSessions.removeItem(session);
2969 return NO_ERROR;
2970}
2971
Eric Laurent6a94d692014-05-20 11:18:06 -07002972status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2973 const sp<AudioPatch>& patch)
2974{
2975 ssize_t index = mAudioPatches.indexOfKey(handle);
2976
2977 if (index >= 0) {
2978 ALOGW("addAudioPatch() patch %d already in", handle);
2979 return ALREADY_EXISTS;
2980 }
2981 mAudioPatches.add(handle, patch);
2982 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2983 "sink handle %d",
2984 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2985 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2986 return NO_ERROR;
2987}
2988
2989status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2990{
2991 ssize_t index = mAudioPatches.indexOfKey(handle);
2992
2993 if (index < 0) {
2994 ALOGW("removeAudioPatch() patch %d not in", handle);
2995 return ALREADY_EXISTS;
2996 }
2997 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2998 mAudioPatches.valueAt(index)->mAfPatchHandle);
2999 mAudioPatches.removeItemsAt(index);
3000 return NO_ERROR;
3001}
3002
Eric Laurente552edb2014-03-10 17:42:56 -07003003// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003004// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003005// ----------------------------------------------------------------------------
3006
Eric Laurent3a4311c2014-03-17 12:00:47 -07003007uint32_t AudioPolicyManager::nextUniqueId()
3008{
3009 return android_atomic_inc(&mNextUniqueId);
3010}
3011
Eric Laurent6a94d692014-05-20 11:18:06 -07003012uint32_t AudioPolicyManager::nextAudioPortGeneration()
3013{
3014 return android_atomic_inc(&mAudioPortGeneration);
3015}
3016
Eric Laurente0720872014-03-11 09:30:41 -07003017AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003018 :
3019#ifdef AUDIO_POLICY_TEST
3020 Thread(false),
3021#endif //AUDIO_POLICY_TEST
3022 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07003023 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07003024 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
3025 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003026 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07003027 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003028 mAudioPortGeneration(1),
3029 mBeaconMuteRefCount(0),
3030 mBeaconPlayingRefCount(0),
3031 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003032{
Eric Laurent6a94d692014-05-20 11:18:06 -07003033 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07003034 mpClientInterface = clientInterface;
3035
Eric Laurent3b73df72014-03-11 09:06:29 -07003036 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
3037 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003038 }
3039
Eric Laurent1afeecb2014-05-14 08:52:28 -07003040 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07003041 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
3042 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
3043 ALOGE("could not load audio policy configuration file, setting defaults");
3044 defaultAudioPolicyConfig();
3045 }
3046 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003047 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003048
3049 // must be done after reading the policy
3050 initializeVolumeCurves();
3051
3052 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003053 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3054 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003055 for (size_t i = 0; i < mHwModules.size(); i++) {
3056 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3057 if (mHwModules[i]->mHandle == 0) {
3058 ALOGW("could not open HW module %s", mHwModules[i]->mName);
3059 continue;
3060 }
3061 // open all output streams needed to access attached devices
3062 // except for direct output streams that are only opened when they are actually
3063 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003064 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003065 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3066 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003067 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003068
Eric Laurent3a4311c2014-03-17 12:00:47 -07003069 if (outProfile->mSupportedDevices.isEmpty()) {
3070 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3071 continue;
3072 }
3073
Eric Laurentd78f1532014-09-16 16:38:20 -07003074 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3075 continue;
3076 }
Eric Laurent83b88082014-06-20 18:31:16 -07003077 audio_devices_t profileType = outProfile->mSupportedDevices.types();
3078 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3079 profileType = mDefaultOutputDevice->mDeviceType;
3080 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07003081 // chose first device present in mSupportedDevices also part of
3082 // outputDeviceTypes
3083 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3084 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3085 if ((profileType & outputDeviceTypes) != 0) {
3086 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003087 }
Eric Laurente552edb2014-03-10 17:42:56 -07003088 }
3089 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003090 if ((profileType & outputDeviceTypes) == 0) {
3091 continue;
3092 }
3093 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3094
3095 outputDesc->mDevice = profileType;
3096 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3097 config.sample_rate = outputDesc->mSamplingRate;
3098 config.channel_mask = outputDesc->mChannelMask;
3099 config.format = outputDesc->mFormat;
3100 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3101 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3102 &output,
3103 &config,
3104 &outputDesc->mDevice,
3105 String8(""),
3106 &outputDesc->mLatency,
3107 outputDesc->mFlags);
3108
3109 if (status != NO_ERROR) {
3110 ALOGW("Cannot open output stream for device %08x on hw module %s",
3111 outputDesc->mDevice,
3112 mHwModules[i]->mName);
3113 } else {
3114 outputDesc->mSamplingRate = config.sample_rate;
3115 outputDesc->mChannelMask = config.channel_mask;
3116 outputDesc->mFormat = config.format;
3117
3118 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3119 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3120 ssize_t index =
3121 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3122 // give a valid ID to an attached device once confirmed it is reachable
3123 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3124 mAvailableOutputDevices[index]->mId = nextUniqueId();
3125 mAvailableOutputDevices[index]->mModule = mHwModules[i];
3126 }
3127 }
3128 if (mPrimaryOutput == 0 &&
3129 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3130 mPrimaryOutput = output;
3131 }
3132 addOutput(output, outputDesc);
3133 setOutputDevice(output,
3134 outputDesc->mDevice,
3135 true);
3136 }
Eric Laurente552edb2014-03-10 17:42:56 -07003137 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003138 // open input streams needed to access attached devices to validate
3139 // mAvailableInputDevices list
3140 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3141 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003142 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003143
Eric Laurent3a4311c2014-03-17 12:00:47 -07003144 if (inProfile->mSupportedDevices.isEmpty()) {
3145 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3146 continue;
3147 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003148 // chose first device present in mSupportedDevices also part of
3149 // inputDeviceTypes
3150 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3151 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3152 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3153 if (profileType & inputDeviceTypes) {
3154 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003155 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003156 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003157 if ((profileType & inputDeviceTypes) == 0) {
3158 continue;
3159 }
3160 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3161
3162 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3163 inputDesc->mDevice = profileType;
3164
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003165 // find the address
3166 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3167 // the inputs vector must be of size 1, but we don't want to crash here
3168 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3169 : String8("");
3170 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3171 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3172
Eric Laurentd78f1532014-09-16 16:38:20 -07003173 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3174 config.sample_rate = inputDesc->mSamplingRate;
3175 config.channel_mask = inputDesc->mChannelMask;
3176 config.format = inputDesc->mFormat;
3177 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3178 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3179 &input,
3180 &config,
3181 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003182 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003183 AUDIO_SOURCE_MIC,
3184 AUDIO_INPUT_FLAG_NONE);
3185
3186 if (status == NO_ERROR) {
3187 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3188 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3189 ssize_t index =
3190 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3191 // give a valid ID to an attached device once confirmed it is reachable
3192 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3193 mAvailableInputDevices[index]->mId = nextUniqueId();
3194 mAvailableInputDevices[index]->mModule = mHwModules[i];
3195 }
3196 }
3197 mpClientInterface->closeInput(input);
3198 } else {
3199 ALOGW("Cannot open input stream for device %08x on hw module %s",
3200 inputDesc->mDevice,
3201 mHwModules[i]->mName);
3202 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003203 }
3204 }
3205 // make sure all attached devices have been allocated a unique ID
3206 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3207 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003208 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003209 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3210 continue;
3211 }
3212 i++;
3213 }
3214 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3215 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003216 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003217 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3218 continue;
3219 }
3220 i++;
3221 }
3222 // make sure default device is reachable
3223 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003224 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003225 }
Eric Laurente552edb2014-03-10 17:42:56 -07003226
3227 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3228
3229 updateDevicesAndOutputs();
3230
3231#ifdef AUDIO_POLICY_TEST
3232 if (mPrimaryOutput != 0) {
3233 AudioParameter outputCmd = AudioParameter();
3234 outputCmd.addInt(String8("set_id"), 0);
3235 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3236
3237 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3238 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003239 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3240 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003241 mTestLatencyMs = 0;
3242 mCurOutput = 0;
3243 mDirectOutput = false;
3244 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3245 mTestOutputs[i] = 0;
3246 }
3247
3248 const size_t SIZE = 256;
3249 char buffer[SIZE];
3250 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3251 run(buffer, ANDROID_PRIORITY_AUDIO);
3252 }
3253#endif //AUDIO_POLICY_TEST
3254}
3255
Eric Laurente0720872014-03-11 09:30:41 -07003256AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003257{
3258#ifdef AUDIO_POLICY_TEST
3259 exit();
3260#endif //AUDIO_POLICY_TEST
3261 for (size_t i = 0; i < mOutputs.size(); i++) {
3262 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003263 }
3264 for (size_t i = 0; i < mInputs.size(); i++) {
3265 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003266 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003267 mAvailableOutputDevices.clear();
3268 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003269 mOutputs.clear();
3270 mInputs.clear();
3271 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003272}
3273
Eric Laurente0720872014-03-11 09:30:41 -07003274status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003275{
3276 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3277}
3278
3279#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003280bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003281{
3282 ALOGV("entering threadLoop()");
3283 while (!exitPending())
3284 {
3285 String8 command;
3286 int valueInt;
3287 String8 value;
3288
3289 Mutex::Autolock _l(mLock);
3290 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3291
3292 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3293 AudioParameter param = AudioParameter(command);
3294
3295 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3296 valueInt != 0) {
3297 ALOGV("Test command %s received", command.string());
3298 String8 target;
3299 if (param.get(String8("target"), target) != NO_ERROR) {
3300 target = "Manager";
3301 }
3302 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3303 param.remove(String8("test_cmd_policy_output"));
3304 mCurOutput = valueInt;
3305 }
3306 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3307 param.remove(String8("test_cmd_policy_direct"));
3308 if (value == "false") {
3309 mDirectOutput = false;
3310 } else if (value == "true") {
3311 mDirectOutput = true;
3312 }
3313 }
3314 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3315 param.remove(String8("test_cmd_policy_input"));
3316 mTestInput = valueInt;
3317 }
3318
3319 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3320 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003321 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003322 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003323 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003324 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003325 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003326 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003327 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003328 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003329 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003330 if (target == "Manager") {
3331 mTestFormat = format;
3332 } else if (mTestOutputs[mCurOutput] != 0) {
3333 AudioParameter outputParam = AudioParameter();
3334 outputParam.addInt(String8("format"), format);
3335 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3336 }
3337 }
3338 }
3339 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3340 param.remove(String8("test_cmd_policy_channels"));
3341 int channels = 0;
3342
3343 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003344 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003345 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003346 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003347 }
3348 if (channels != 0) {
3349 if (target == "Manager") {
3350 mTestChannels = channels;
3351 } else if (mTestOutputs[mCurOutput] != 0) {
3352 AudioParameter outputParam = AudioParameter();
3353 outputParam.addInt(String8("channels"), channels);
3354 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3355 }
3356 }
3357 }
3358 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3359 param.remove(String8("test_cmd_policy_sampleRate"));
3360 if (valueInt >= 0 && valueInt <= 96000) {
3361 int samplingRate = valueInt;
3362 if (target == "Manager") {
3363 mTestSamplingRate = samplingRate;
3364 } else if (mTestOutputs[mCurOutput] != 0) {
3365 AudioParameter outputParam = AudioParameter();
3366 outputParam.addInt(String8("sampling_rate"), samplingRate);
3367 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3368 }
3369 }
3370 }
3371
3372 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3373 param.remove(String8("test_cmd_policy_reopen"));
3374
Eric Laurent1f2f2232014-06-02 12:01:23 -07003375 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003376 mpClientInterface->closeOutput(mPrimaryOutput);
3377
3378 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3379
Eric Laurente552edb2014-03-10 17:42:56 -07003380 mOutputs.removeItem(mPrimaryOutput);
3381
Eric Laurent1f2f2232014-06-02 12:01:23 -07003382 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003383 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003384 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3385 config.sample_rate = outputDesc->mSamplingRate;
3386 config.channel_mask = outputDesc->mChannelMask;
3387 config.format = outputDesc->mFormat;
3388 status_t status = mpClientInterface->openOutput(moduleHandle,
3389 &mPrimaryOutput,
3390 &config,
3391 &outputDesc->mDevice,
3392 String8(""),
3393 &outputDesc->mLatency,
3394 outputDesc->mFlags);
3395 if (status != NO_ERROR) {
3396 ALOGE("Failed to reopen hardware output stream, "
3397 "samplingRate: %d, format %d, channels %d",
3398 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003399 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003400 outputDesc->mSamplingRate = config.sample_rate;
3401 outputDesc->mChannelMask = config.channel_mask;
3402 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003403 AudioParameter outputCmd = AudioParameter();
3404 outputCmd.addInt(String8("set_id"), 0);
3405 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3406 addOutput(mPrimaryOutput, outputDesc);
3407 }
3408 }
3409
3410
3411 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3412 }
3413 }
3414 return false;
3415}
3416
Eric Laurente0720872014-03-11 09:30:41 -07003417void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003418{
3419 {
3420 AutoMutex _l(mLock);
3421 requestExit();
3422 mWaitWorkCV.signal();
3423 }
3424 requestExitAndWait();
3425}
3426
Eric Laurente0720872014-03-11 09:30:41 -07003427int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003428{
3429 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3430 if (output == mTestOutputs[i]) return i;
3431 }
3432 return 0;
3433}
3434#endif //AUDIO_POLICY_TEST
3435
3436// ---
3437
Eric Laurent1f2f2232014-06-02 12:01:23 -07003438void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003439{
Eric Laurent1c333e22014-05-20 10:48:17 -07003440 outputDesc->mIoHandle = output;
3441 outputDesc->mId = nextUniqueId();
3442 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003443 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003444}
3445
Eric Laurent1f2f2232014-06-02 12:01:23 -07003446void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003447{
Eric Laurent1c333e22014-05-20 10:48:17 -07003448 inputDesc->mIoHandle = input;
3449 inputDesc->mId = nextUniqueId();
3450 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003451 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003452}
Eric Laurente552edb2014-03-10 17:42:56 -07003453
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003454void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003455 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003456 const String8 address /*in*/,
3457 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003458 sp<DeviceDescriptor> devDesc =
3459 desc->mProfile->mSupportedDevices.getDevice(device, address);
3460 if (devDesc != 0) {
3461 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3462 desc->mIoHandle, address.string());
3463 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003464 }
3465}
3466
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003467status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003468 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003469 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003470 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003471{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003472 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003473 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003474 // erase all current sample rates, formats and channel masks
3475 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003476
Eric Laurent3b73df72014-03-11 09:06:29 -07003477 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003478 // first list already open outputs that can be routed to this device
3479 for (size_t i = 0; i < mOutputs.size(); i++) {
3480 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003481 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003482 if (!deviceDistinguishesOnAddress(device)) {
3483 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3484 outputs.add(mOutputs.keyAt(i));
3485 } else {
3486 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003487 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003488 }
Eric Laurente552edb2014-03-10 17:42:56 -07003489 }
3490 }
3491 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003492 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003493 for (size_t i = 0; i < mHwModules.size(); i++)
3494 {
3495 if (mHwModules[i]->mHandle == 0) {
3496 continue;
3497 }
3498 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3499 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003500 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3501 if (profile->mSupportedDevices.types() & device) {
3502 if (!deviceDistinguishesOnAddress(device) ||
3503 address == profile->mSupportedDevices[0]->mAddress) {
3504 profiles.add(profile);
3505 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3506 }
Eric Laurente552edb2014-03-10 17:42:56 -07003507 }
3508 }
3509 }
3510
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003511 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3512
Eric Laurente552edb2014-03-10 17:42:56 -07003513 if (profiles.isEmpty() && outputs.isEmpty()) {
3514 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3515 return BAD_VALUE;
3516 }
3517
3518 // open outputs for matching profiles if needed. Direct outputs are also opened to
3519 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3520 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003521 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003522
3523 // nothing to do if one output is already opened for this profile
3524 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003525 for (j = 0; j < outputs.size(); j++) {
3526 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003527 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003528 // matching profile: save the sample rates, format and channel masks supported
3529 // by the profile in our device descriptor
3530 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003531 break;
3532 }
3533 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003534 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003535 continue;
3536 }
3537
Eric Laurent83b88082014-06-20 18:31:16 -07003538 ALOGV("opening output for device %08x with params %s profile %p",
3539 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003540 desc = new AudioOutputDescriptor(profile);
3541 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003542 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3543 config.sample_rate = desc->mSamplingRate;
3544 config.channel_mask = desc->mChannelMask;
3545 config.format = desc->mFormat;
3546 config.offload_info.sample_rate = desc->mSamplingRate;
3547 config.offload_info.channel_mask = desc->mChannelMask;
3548 config.offload_info.format = desc->mFormat;
3549 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3550 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3551 &output,
3552 &config,
3553 &desc->mDevice,
3554 address,
3555 &desc->mLatency,
3556 desc->mFlags);
3557 if (status == NO_ERROR) {
3558 desc->mSamplingRate = config.sample_rate;
3559 desc->mChannelMask = config.channel_mask;
3560 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003561
Eric Laurentd4692962014-05-05 18:13:44 -07003562 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003563 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003564 char *param = audio_device_address_to_parameter(device, address);
3565 mpClientInterface->setParameters(output, String8(param));
3566 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003567 }
3568
Eric Laurentd4692962014-05-05 18:13:44 -07003569 // Here is where we step through and resolve any "dynamic" fields
3570 String8 reply;
3571 char *value;
3572 if (profile->mSamplingRates[0] == 0) {
3573 reply = mpClientInterface->getParameters(output,
3574 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003575 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003576 reply.string());
3577 value = strpbrk((char *)reply.string(), "=");
3578 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003579 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003580 }
Eric Laurentd4692962014-05-05 18:13:44 -07003581 }
3582 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3583 reply = mpClientInterface->getParameters(output,
3584 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003585 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003586 reply.string());
3587 value = strpbrk((char *)reply.string(), "=");
3588 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003589 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003590 }
Eric Laurentd4692962014-05-05 18:13:44 -07003591 }
3592 if (profile->mChannelMasks[0] == 0) {
3593 reply = mpClientInterface->getParameters(output,
3594 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003595 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003596 reply.string());
3597 value = strpbrk((char *)reply.string(), "=");
3598 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003599 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003600 }
Eric Laurentd4692962014-05-05 18:13:44 -07003601 }
3602 if (((profile->mSamplingRates[0] == 0) &&
3603 (profile->mSamplingRates.size() < 2)) ||
3604 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3605 (profile->mFormats.size() < 2)) ||
3606 ((profile->mChannelMasks[0] == 0) &&
3607 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003608 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003609 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003610 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003611 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3612 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003613 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003614 config.sample_rate = profile->pickSamplingRate();
3615 config.channel_mask = profile->pickChannelMask();
3616 config.format = profile->pickFormat();
3617 config.offload_info.sample_rate = config.sample_rate;
3618 config.offload_info.channel_mask = config.channel_mask;
3619 config.offload_info.format = config.format;
3620 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3621 &output,
3622 &config,
3623 &desc->mDevice,
3624 address,
3625 &desc->mLatency,
3626 desc->mFlags);
3627 if (status == NO_ERROR) {
3628 desc->mSamplingRate = config.sample_rate;
3629 desc->mChannelMask = config.channel_mask;
3630 desc->mFormat = config.format;
3631 } else {
3632 output = AUDIO_IO_HANDLE_NONE;
3633 }
Eric Laurentd4692962014-05-05 18:13:44 -07003634 }
3635
Eric Laurentcf2c0212014-07-25 16:20:43 -07003636 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003637 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003638 if (deviceDistinguishesOnAddress(device) && address != "0") {
3639 ssize_t index = mPolicyMixes.indexOfKey(address);
3640 if (index >= 0) {
3641 mPolicyMixes[index]->mOutput = desc;
Eric Laurentc722f302014-12-10 11:21:49 -08003642 desc->mPolicyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08003643 } else {
3644 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3645 address.string());
3646 }
Eric Laurentc722f302014-12-10 11:21:49 -08003647 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3648 // no duplicated output for direct outputs and
3649 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003650 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003651
Eric Laurentd4692962014-05-05 18:13:44 -07003652 // set initial stream volume for device
3653 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003654
Eric Laurentd4692962014-05-05 18:13:44 -07003655 //TODO: configure audio effect output stage here
3656
3657 // open a duplicating output thread for the new output and the primary output
3658 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3659 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003660 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003661 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003662 sp<AudioOutputDescriptor> dupOutputDesc =
3663 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003664 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3665 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3666 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3667 dupOutputDesc->mFormat = desc->mFormat;
3668 dupOutputDesc->mChannelMask = desc->mChannelMask;
3669 dupOutputDesc->mLatency = desc->mLatency;
3670 addOutput(duplicatedOutput, dupOutputDesc);
3671 applyStreamVolumes(duplicatedOutput, device, 0, true);
3672 } else {
3673 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3674 mPrimaryOutput, output);
3675 mpClientInterface->closeOutput(output);
3676 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003677 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003678 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003679 }
Eric Laurente552edb2014-03-10 17:42:56 -07003680 }
3681 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003682 } else {
3683 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003684 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003685 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003686 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003687 profiles.removeAt(profile_index);
3688 profile_index--;
3689 } else {
3690 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003691 devDesc->importAudioPort(profile);
3692
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003693 if (deviceDistinguishesOnAddress(device)) {
3694 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3695 device, address.string());
3696 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3697 NULL/*patch handle*/, address.string());
3698 }
Eric Laurente552edb2014-03-10 17:42:56 -07003699 ALOGV("checkOutputsForDevice(): adding output %d", output);
3700 }
3701 }
3702
3703 if (profiles.isEmpty()) {
3704 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3705 return BAD_VALUE;
3706 }
Eric Laurentd4692962014-05-05 18:13:44 -07003707 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003708 // check if one opened output is not needed any more after disconnecting one device
3709 for (size_t i = 0; i < mOutputs.size(); i++) {
3710 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003711 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003712 // exact match on device
3713 if (deviceDistinguishesOnAddress(device) &&
3714 (desc->mProfile->mSupportedDevices.types() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003715 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08003716 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003717 & mAvailableOutputDevices.types())) {
3718 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3719 mOutputs.keyAt(i));
3720 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003721 }
Eric Laurente552edb2014-03-10 17:42:56 -07003722 }
3723 }
Eric Laurentd4692962014-05-05 18:13:44 -07003724 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003725 for (size_t i = 0; i < mHwModules.size(); i++)
3726 {
3727 if (mHwModules[i]->mHandle == 0) {
3728 continue;
3729 }
3730 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3731 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003732 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003733 if (profile->mSupportedDevices.types() & device) {
3734 ALOGV("checkOutputsForDevice(): "
3735 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003736 if (profile->mSamplingRates[0] == 0) {
3737 profile->mSamplingRates.clear();
3738 profile->mSamplingRates.add(0);
3739 }
3740 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3741 profile->mFormats.clear();
3742 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3743 }
3744 if (profile->mChannelMasks[0] == 0) {
3745 profile->mChannelMasks.clear();
3746 profile->mChannelMasks.add(0);
3747 }
3748 }
3749 }
3750 }
3751 }
3752 return NO_ERROR;
3753}
3754
Eric Laurentd4692962014-05-05 18:13:44 -07003755status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3756 audio_policy_dev_state_t state,
3757 SortedVector<audio_io_handle_t>& inputs,
3758 const String8 address)
3759{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003760 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003761 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3762 // first list already open inputs that can be routed to this device
3763 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3764 desc = mInputs.valueAt(input_index);
3765 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3766 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3767 inputs.add(mInputs.keyAt(input_index));
3768 }
3769 }
3770
3771 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003772 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003773 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3774 {
3775 if (mHwModules[module_idx]->mHandle == 0) {
3776 continue;
3777 }
3778 for (size_t profile_index = 0;
3779 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3780 profile_index++)
3781 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003782 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3783
3784 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3785 if (!deviceDistinguishesOnAddress(device) ||
3786 address == profile->mSupportedDevices[0]->mAddress) {
3787 profiles.add(profile);
3788 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3789 profile_index, module_idx);
3790 }
Eric Laurentd4692962014-05-05 18:13:44 -07003791 }
3792 }
3793 }
3794
3795 if (profiles.isEmpty() && inputs.isEmpty()) {
3796 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3797 return BAD_VALUE;
3798 }
3799
3800 // open inputs for matching profiles if needed. Direct inputs are also opened to
3801 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3802 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3803
Eric Laurent1c333e22014-05-20 10:48:17 -07003804 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003805 // nothing to do if one input is already opened for this profile
3806 size_t input_index;
3807 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3808 desc = mInputs.valueAt(input_index);
3809 if (desc->mProfile == profile) {
3810 break;
3811 }
3812 }
3813 if (input_index != mInputs.size()) {
3814 continue;
3815 }
3816
3817 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3818 desc = new AudioInputDescriptor(profile);
3819 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003820 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3821 config.sample_rate = desc->mSamplingRate;
3822 config.channel_mask = desc->mChannelMask;
3823 config.format = desc->mFormat;
3824 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3825 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3826 &input,
3827 &config,
3828 &desc->mDevice,
3829 address,
3830 AUDIO_SOURCE_MIC,
3831 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003832
Eric Laurentcf2c0212014-07-25 16:20:43 -07003833 if (status == NO_ERROR) {
3834 desc->mSamplingRate = config.sample_rate;
3835 desc->mChannelMask = config.channel_mask;
3836 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003837
Eric Laurentd4692962014-05-05 18:13:44 -07003838 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003839 char *param = audio_device_address_to_parameter(device, address);
3840 mpClientInterface->setParameters(input, String8(param));
3841 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003842 }
3843
3844 // Here is where we step through and resolve any "dynamic" fields
3845 String8 reply;
3846 char *value;
3847 if (profile->mSamplingRates[0] == 0) {
3848 reply = mpClientInterface->getParameters(input,
3849 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3850 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3851 reply.string());
3852 value = strpbrk((char *)reply.string(), "=");
3853 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003854 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003855 }
3856 }
3857 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3858 reply = mpClientInterface->getParameters(input,
3859 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3860 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3861 value = strpbrk((char *)reply.string(), "=");
3862 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003863 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003864 }
3865 }
3866 if (profile->mChannelMasks[0] == 0) {
3867 reply = mpClientInterface->getParameters(input,
3868 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3869 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3870 reply.string());
3871 value = strpbrk((char *)reply.string(), "=");
3872 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003873 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003874 }
3875 }
3876 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3877 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3878 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3879 ALOGW("checkInputsForDevice() direct input missing param");
3880 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003881 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003882 }
3883
3884 if (input != 0) {
3885 addInput(input, desc);
3886 }
3887 } // endif input != 0
3888
Eric Laurentcf2c0212014-07-25 16:20:43 -07003889 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003890 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003891 profiles.removeAt(profile_index);
3892 profile_index--;
3893 } else {
3894 inputs.add(input);
3895 ALOGV("checkInputsForDevice(): adding input %d", input);
3896 }
3897 } // end scan profiles
3898
3899 if (profiles.isEmpty()) {
3900 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3901 return BAD_VALUE;
3902 }
3903 } else {
3904 // Disconnect
3905 // check if one opened input is not needed any more after disconnecting one device
3906 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3907 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003908 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3909 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003910 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3911 mInputs.keyAt(input_index));
3912 inputs.add(mInputs.keyAt(input_index));
3913 }
3914 }
3915 // Clear any profiles associated with the disconnected device.
3916 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3917 if (mHwModules[module_index]->mHandle == 0) {
3918 continue;
3919 }
3920 for (size_t profile_index = 0;
3921 profile_index < mHwModules[module_index]->mInputProfiles.size();
3922 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003923 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003924 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003925 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003926 profile_index, module_index);
3927 if (profile->mSamplingRates[0] == 0) {
3928 profile->mSamplingRates.clear();
3929 profile->mSamplingRates.add(0);
3930 }
3931 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3932 profile->mFormats.clear();
3933 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3934 }
3935 if (profile->mChannelMasks[0] == 0) {
3936 profile->mChannelMasks.clear();
3937 profile->mChannelMasks.add(0);
3938 }
3939 }
3940 }
3941 }
3942 } // end disconnect
3943
3944 return NO_ERROR;
3945}
3946
3947
Eric Laurente0720872014-03-11 09:30:41 -07003948void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003949{
3950 ALOGV("closeOutput(%d)", output);
3951
Eric Laurent1f2f2232014-06-02 12:01:23 -07003952 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003953 if (outputDesc == NULL) {
3954 ALOGW("closeOutput() unknown output %d", output);
3955 return;
3956 }
3957
Eric Laurent275e8e92014-11-30 15:14:47 -08003958 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3959 if (mPolicyMixes[i]->mOutput == outputDesc) {
3960 mPolicyMixes[i]->mOutput.clear();
3961 }
3962 }
3963
Eric Laurente552edb2014-03-10 17:42:56 -07003964 // look for duplicated outputs connected to the output being removed.
3965 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003966 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003967 if (dupOutputDesc->isDuplicated() &&
3968 (dupOutputDesc->mOutput1 == outputDesc ||
3969 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003970 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003971 if (dupOutputDesc->mOutput1 == outputDesc) {
3972 outputDesc2 = dupOutputDesc->mOutput2;
3973 } else {
3974 outputDesc2 = dupOutputDesc->mOutput1;
3975 }
3976 // As all active tracks on duplicated output will be deleted,
3977 // and as they were also referenced on the other output, the reference
3978 // count for their stream type must be adjusted accordingly on
3979 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003980 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003981 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003982 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003983 }
3984 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3985 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3986
3987 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003988 mOutputs.removeItem(duplicatedOutput);
3989 }
3990 }
3991
Eric Laurent05b90f82014-08-27 15:32:29 -07003992 nextAudioPortGeneration();
3993
3994 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3995 if (index >= 0) {
3996 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3997 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3998 mAudioPatches.removeItemsAt(index);
3999 mpClientInterface->onAudioPatchListUpdate();
4000 }
4001
Eric Laurente552edb2014-03-10 17:42:56 -07004002 AudioParameter param;
4003 param.add(String8("closing"), String8("true"));
4004 mpClientInterface->setParameters(output, param.toString());
4005
4006 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004007 mOutputs.removeItem(output);
4008 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004009}
4010
4011void AudioPolicyManager::closeInput(audio_io_handle_t input)
4012{
4013 ALOGV("closeInput(%d)", input);
4014
4015 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4016 if (inputDesc == NULL) {
4017 ALOGW("closeInput() unknown input %d", input);
4018 return;
4019 }
4020
Eric Laurent6a94d692014-05-20 11:18:06 -07004021 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004022
4023 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4024 if (index >= 0) {
4025 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4026 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4027 mAudioPatches.removeItemsAt(index);
4028 mpClientInterface->onAudioPatchListUpdate();
4029 }
4030
4031 mpClientInterface->closeInput(input);
4032 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004033}
4034
Eric Laurente0720872014-03-11 09:30:41 -07004035SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07004036 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004037{
4038 SortedVector<audio_io_handle_t> outputs;
4039
4040 ALOGVV("getOutputsForDevice() device %04x", device);
4041 for (size_t i = 0; i < openOutputs.size(); i++) {
4042 ALOGVV("output %d isDuplicated=%d device=%04x",
4043 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4044 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4045 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4046 outputs.add(openOutputs.keyAt(i));
4047 }
4048 }
4049 return outputs;
4050}
4051
Eric Laurente0720872014-03-11 09:30:41 -07004052bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07004053 SortedVector<audio_io_handle_t>& outputs2)
4054{
4055 if (outputs1.size() != outputs2.size()) {
4056 return false;
4057 }
4058 for (size_t i = 0; i < outputs1.size(); i++) {
4059 if (outputs1[i] != outputs2[i]) {
4060 return false;
4061 }
4062 }
4063 return true;
4064}
4065
Eric Laurente0720872014-03-11 09:30:41 -07004066void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004067{
4068 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4069 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4070 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4071 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4072
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004073 // also take into account external policy-related changes: add all outputs which are
4074 // associated with policies in the "before" and "after" output vectors
4075 ALOGVV("checkOutputForStrategy(): policy related outputs");
4076 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
4077 const sp<AudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
4078 if (desc != 0 && desc->mPolicyMix != NULL) {
4079 srcOutputs.add(desc->mIoHandle);
4080 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4081 }
4082 }
4083 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
4084 const sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4085 if (desc != 0 && desc->mPolicyMix != NULL) {
4086 dstOutputs.add(desc->mIoHandle);
4087 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4088 }
4089 }
4090
Eric Laurente552edb2014-03-10 17:42:56 -07004091 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4092 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4093 strategy, srcOutputs[0], dstOutputs[0]);
4094 // mute strategy while moving tracks from one output to another
4095 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004096 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004097 if (desc->isStrategyActive(strategy)) {
4098 setStrategyMute(strategy, true, srcOutputs[i]);
4099 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4100 }
4101 }
4102
4103 // Move effects associated to this strategy from previous output to new output
4104 if (strategy == STRATEGY_MEDIA) {
4105 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4106 SortedVector<audio_io_handle_t> moved;
4107 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004108 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4109 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4110 effectDesc->mIo != fxOutput) {
4111 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004112 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4113 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004114 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004115 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004116 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004117 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004118 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004119 }
4120 }
4121 }
4122 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004123 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004124 if (i == AUDIO_STREAM_PATCH) {
4125 continue;
4126 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004127 if (getStrategy((audio_stream_type_t)i) == strategy) {
4128 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004129 }
4130 }
4131 }
4132}
4133
Eric Laurente0720872014-03-11 09:30:41 -07004134void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004135{
Jon Eklund966095e2014-09-09 15:39:49 -05004136 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4137 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004138 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004139 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4140 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004141 checkOutputForStrategy(STRATEGY_SONIFICATION);
4142 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004143 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004144 checkOutputForStrategy(STRATEGY_MEDIA);
4145 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004146 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004147}
4148
Eric Laurente0720872014-03-11 09:30:41 -07004149audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004150{
Eric Laurente552edb2014-03-10 17:42:56 -07004151 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004152 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004153 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4154 return mOutputs.keyAt(i);
4155 }
4156 }
4157
4158 return 0;
4159}
4160
Eric Laurente0720872014-03-11 09:30:41 -07004161void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004162{
Eric Laurente552edb2014-03-10 17:42:56 -07004163 audio_io_handle_t a2dpOutput = getA2dpOutput();
4164 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004165 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004166 return;
4167 }
4168
Eric Laurent3a4311c2014-03-17 12:00:47 -07004169 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004170 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4171 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4172 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004173 // suspend A2DP output if:
4174 // (NOT already suspended) &&
4175 // ((SCO device is connected &&
4176 // (forced usage for communication || for record is SCO))) ||
4177 // (phone state is ringing || in call)
4178 //
4179 // restore A2DP output if:
4180 // (Already suspended) &&
4181 // ((SCO device is NOT connected ||
4182 // (forced usage NOT for communication && NOT for record is SCO))) &&
4183 // (phone state is NOT ringing && NOT in call)
4184 //
4185 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004186 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004187 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4188 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4189 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4190 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004191
4192 mpClientInterface->restoreOutput(a2dpOutput);
4193 mA2dpSuspended = false;
4194 }
4195 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004196 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004197 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4198 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4199 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4200 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004201
4202 mpClientInterface->suspendOutput(a2dpOutput);
4203 mA2dpSuspended = true;
4204 }
4205 }
4206}
4207
Eric Laurent1c333e22014-05-20 10:48:17 -07004208audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004209{
4210 audio_devices_t device = AUDIO_DEVICE_NONE;
4211
Eric Laurent1f2f2232014-06-02 12:01:23 -07004212 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004213
4214 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4215 if (index >= 0) {
4216 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4217 if (patchDesc->mUid != mUidCached) {
4218 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4219 outputDesc->device(), outputDesc->mPatchHandle);
4220 return outputDesc->device();
4221 }
4222 }
4223
Eric Laurente552edb2014-03-10 17:42:56 -07004224 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004225 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004226 // use device for strategy enforced audible
4227 // 2: we are in call or the strategy phone is active on the output:
4228 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004229 // 3: the strategy for enforced audible is active but not enforced on the output:
4230 // use the device for strategy enforced audible
4231 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004232 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004233 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004234 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004235 // 6: the strategy accessibility is active on the output:
4236 // use device for strategy accessibility
4237 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004238 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004239 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004240 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004241 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004242 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004243 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4244 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004245 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4246 } else if (isInCall() ||
4247 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4248 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004249 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4250 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004251 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4252 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4253 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4254 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004255 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4256 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004257 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4258 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4259 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4260 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004261 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4262 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004263 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4264 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004265 }
4266
Eric Laurent1c333e22014-05-20 10:48:17 -07004267 ALOGV("getNewOutputDevice() selected device %x", device);
4268 return device;
4269}
4270
4271audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4272{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004273 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004274
4275 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4276 if (index >= 0) {
4277 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4278 if (patchDesc->mUid != mUidCached) {
4279 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4280 inputDesc->mDevice, inputDesc->mPatchHandle);
4281 return inputDesc->mDevice;
4282 }
4283 }
4284
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004285 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07004286
4287 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004288 return device;
4289}
4290
Eric Laurente0720872014-03-11 09:30:41 -07004291uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004292 return (uint32_t)getStrategy(stream);
4293}
4294
Eric Laurente0720872014-03-11 09:30:41 -07004295audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004296 // By checking the range of stream before calling getStrategy, we avoid
4297 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4298 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004299 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004300 return AUDIO_DEVICE_NONE;
4301 }
4302 audio_devices_t devices;
4303 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4304 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4305 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4306 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004307 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004308 if (outputDesc->isStrategyActive(strategy)) {
4309 devices = outputDesc->device();
4310 break;
4311 }
Eric Laurente552edb2014-03-10 17:42:56 -07004312 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004313
4314 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4315 and doesn't really need to.*/
4316 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4317 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4318 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4319 }
4320
Eric Laurente552edb2014-03-10 17:42:56 -07004321 return devices;
4322}
4323
Eric Laurente0720872014-03-11 09:30:41 -07004324AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004325 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004326
4327 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4328
Eric Laurente552edb2014-03-10 17:42:56 -07004329 // stream to strategy mapping
4330 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004331 case AUDIO_STREAM_VOICE_CALL:
4332 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004333 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004334 case AUDIO_STREAM_RING:
4335 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004336 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004337 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004338 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004339 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004340 return STRATEGY_DTMF;
4341 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004342 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004343 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004344 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4345 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004346 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004347 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004348 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004349 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004350 case AUDIO_STREAM_TTS:
4351 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004352 case AUDIO_STREAM_ACCESSIBILITY:
4353 return STRATEGY_ACCESSIBILITY;
4354 case AUDIO_STREAM_REROUTING:
4355 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004356 }
4357}
4358
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004359uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4360 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004361 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4362 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4363 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004364 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4365 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4366 }
4367
4368 // usage to strategy mapping
4369 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004370 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4371 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4372 return (uint32_t) STRATEGY_SONIFICATION;
4373 }
4374 if (isInCall()) {
4375 return (uint32_t) STRATEGY_PHONE;
4376 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004377 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004378
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004379 case AUDIO_USAGE_MEDIA:
4380 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004381 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4382 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4383 return (uint32_t) STRATEGY_MEDIA;
4384
4385 case AUDIO_USAGE_VOICE_COMMUNICATION:
4386 return (uint32_t) STRATEGY_PHONE;
4387
4388 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4389 return (uint32_t) STRATEGY_DTMF;
4390
4391 case AUDIO_USAGE_ALARM:
4392 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4393 return (uint32_t) STRATEGY_SONIFICATION;
4394
4395 case AUDIO_USAGE_NOTIFICATION:
4396 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4397 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4398 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4399 case AUDIO_USAGE_NOTIFICATION_EVENT:
4400 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4401
4402 case AUDIO_USAGE_UNKNOWN:
4403 default:
4404 return (uint32_t) STRATEGY_MEDIA;
4405 }
4406}
4407
Eric Laurente0720872014-03-11 09:30:41 -07004408void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004409 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004410 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004411 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4412 updateDevicesAndOutputs();
4413 break;
4414 default:
4415 break;
4416 }
4417}
4418
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004419bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4420 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4421 if (s == (size_t) streamToIgnore) {
4422 continue;
4423 }
4424 for (size_t i = 0; i < mOutputs.size(); i++) {
4425 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4426 if (outputDesc->mRefCount[s] != 0) {
4427 return true;
4428 }
4429 }
4430 }
4431 return false;
4432}
4433
4434uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4435 switch(event) {
4436 case STARTING_OUTPUT:
4437 mBeaconMuteRefCount++;
4438 break;
4439 case STOPPING_OUTPUT:
4440 if (mBeaconMuteRefCount > 0) {
4441 mBeaconMuteRefCount--;
4442 }
4443 break;
4444 case STARTING_BEACON:
4445 mBeaconPlayingRefCount++;
4446 break;
4447 case STOPPING_BEACON:
4448 if (mBeaconPlayingRefCount > 0) {
4449 mBeaconPlayingRefCount--;
4450 }
4451 break;
4452 }
4453
4454 if (mBeaconMuteRefCount > 0) {
4455 // any playback causes beacon to be muted
4456 return setBeaconMute(true);
4457 } else {
4458 // no other playback: unmute when beacon starts playing, mute when it stops
4459 return setBeaconMute(mBeaconPlayingRefCount == 0);
4460 }
4461}
4462
4463uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4464 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4465 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4466 // keep track of muted state to avoid repeating mute/unmute operations
4467 if (mBeaconMuted != mute) {
4468 // mute/unmute AUDIO_STREAM_TTS on all outputs
4469 ALOGV("\t muting %d", mute);
4470 uint32_t maxLatency = 0;
4471 for (size_t i = 0; i < mOutputs.size(); i++) {
4472 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4473 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4474 desc->mIoHandle,
4475 0 /*delay*/, AUDIO_DEVICE_NONE);
4476 const uint32_t latency = desc->latency() * 2;
4477 if (latency > maxLatency) {
4478 maxLatency = latency;
4479 }
4480 }
4481 mBeaconMuted = mute;
4482 return maxLatency;
4483 }
4484 return 0;
4485}
4486
Eric Laurente0720872014-03-11 09:30:41 -07004487audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004488 bool fromCache)
4489{
4490 uint32_t device = AUDIO_DEVICE_NONE;
4491
4492 if (fromCache) {
4493 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4494 strategy, mDeviceForStrategy[strategy]);
4495 return mDeviceForStrategy[strategy];
4496 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004497 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004498 switch (strategy) {
4499
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004500 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4501 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4502 if (!device) {
4503 ALOGE("getDeviceForStrategy() no device found for "\
4504 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4505 }
4506 break;
4507
Eric Laurente552edb2014-03-10 17:42:56 -07004508 case STRATEGY_SONIFICATION_RESPECTFUL:
4509 if (isInCall()) {
4510 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004511 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004512 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4513 // while media is playing on a remote device, use the the sonification behavior.
4514 // Note that we test this usecase before testing if media is playing because
4515 // the isStreamActive() method only informs about the activity of a stream, not
4516 // if it's for local playback. Note also that we use the same delay between both tests
4517 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004518 //user "safe" speaker if available instead of normal speaker to avoid triggering
4519 //other acoustic safety mechanisms for notification
4520 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4521 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004522 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004523 // while media is playing (or has recently played), use the same device
4524 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4525 } else {
4526 // when media is not playing anymore, fall back on the sonification behavior
4527 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004528 //user "safe" speaker if available instead of normal speaker to avoid triggering
4529 //other acoustic safety mechanisms for notification
4530 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4531 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004532 }
4533
4534 break;
4535
4536 case STRATEGY_DTMF:
4537 if (!isInCall()) {
4538 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4539 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4540 break;
4541 }
4542 // when in call, DTMF and PHONE strategies follow the same rules
4543 // FALL THROUGH
4544
4545 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004546 // Force use of only devices on primary output if:
4547 // - in call AND
4548 // - cannot route from voice call RX OR
4549 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4550 if (mPhoneState == AUDIO_MODE_IN_CALL) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004551 audio_devices_t txDevice =
4552 getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -07004553 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4554 if (((mAvailableInputDevices.types() &
4555 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4556 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004557 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004558 AUDIO_DEVICE_API_VERSION_3_0))) {
4559 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4560 }
4561 }
Eric Laurente552edb2014-03-10 17:42:56 -07004562 // for phone strategy, we first consider the forced use and then the available devices by order
4563 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004564 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4565 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004566 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004567 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004568 if (device) break;
4569 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004570 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004571 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004572 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004573 if (device) break;
4574 // if SCO device is requested but no SCO device is available, fall back to default case
4575 // FALL THROUGH
4576
4577 default: // FORCE_NONE
4578 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004579 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004580 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004581 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004582 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004583 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004584 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004585 if (device) break;
4586 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004587 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004588 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004589 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004590 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004591 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4592 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004593 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004594 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004595 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004596 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004597 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004598 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004599 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004600 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004601 if (device) break;
4602 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004603 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004604 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004605 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004606 if (device == AUDIO_DEVICE_NONE) {
4607 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4608 }
4609 break;
4610
Eric Laurent3b73df72014-03-11 09:06:29 -07004611 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004612 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4613 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004614 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004615 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004616 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004617 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004618 if (device) break;
4619 }
Eric Laurentcd71a692014-12-16 12:01:12 -08004620 if (!isInCall()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004621 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004622 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004623 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004624 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004625 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004626 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004627 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004628 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004629 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004630 if (device) break;
4631 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004632 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4633 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004634 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004635 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004636 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004637 if (device == AUDIO_DEVICE_NONE) {
4638 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4639 }
4640 break;
4641 }
4642 break;
4643
4644 case STRATEGY_SONIFICATION:
4645
4646 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4647 // handleIncallSonification().
4648 if (isInCall()) {
4649 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4650 break;
4651 }
4652 // FALL THROUGH
4653
4654 case STRATEGY_ENFORCED_AUDIBLE:
4655 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4656 // except:
4657 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4658 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4659
4660 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004661 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004662 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004663 if (device == AUDIO_DEVICE_NONE) {
4664 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4665 }
4666 }
4667 // The second device used for sonification is the same as the device used by media strategy
4668 // FALL THROUGH
4669
Eric Laurent223fd5c2014-11-11 13:43:36 -08004670 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4671 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004672 if (strategy == STRATEGY_ACCESSIBILITY) {
4673 // do not route accessibility prompts to a digital output currently configured with a
4674 // compressed format as they would likely not be mixed and dropped.
4675 for (size_t i = 0; i < mOutputs.size(); i++) {
4676 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4677 audio_devices_t devices = desc->device() &
4678 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4679 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4680 devices != AUDIO_DEVICE_NONE) {
4681 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4682 }
4683 }
4684 }
4685 // FALL THROUGH
4686
Eric Laurent223fd5c2014-11-11 13:43:36 -08004687 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004688 case STRATEGY_MEDIA: {
4689 uint32_t device2 = AUDIO_DEVICE_NONE;
4690 if (strategy != STRATEGY_SONIFICATION) {
4691 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004692 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4693 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4694 }
Eric Laurente552edb2014-03-10 17:42:56 -07004695 }
4696 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004697 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004698 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004699 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004700 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004701 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004702 }
4703 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004704 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004705 }
4706 }
Hochi Huang327cb702014-09-21 09:47:31 +08004707 if ((device2 == AUDIO_DEVICE_NONE) &&
4708 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4709 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4710 }
Eric Laurente552edb2014-03-10 17:42:56 -07004711 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004712 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004713 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004714 if ((device2 == AUDIO_DEVICE_NONE)) {
4715 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4716 }
Eric Laurente552edb2014-03-10 17:42:56 -07004717 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004718 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004719 }
4720 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004721 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004722 }
4723 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004724 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004725 }
4726 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004727 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004728 }
4729 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4730 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004731 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004732 }
4733 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004734 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004735 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004736 }
4737 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004738 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004739 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004740 int device3 = AUDIO_DEVICE_NONE;
4741 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004742 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004743 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4744 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004745 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004746 }
Eric Laurente552edb2014-03-10 17:42:56 -07004747
Jungshik Jang839e4f32014-06-26 17:23:40 +09004748 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004749 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4750 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4751 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004752
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004753 // If hdmi system audio mode is on, remove speaker out of output list.
4754 if ((strategy == STRATEGY_MEDIA) &&
4755 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4756 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4757 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4758 }
4759
Eric Laurente552edb2014-03-10 17:42:56 -07004760 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004761 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004762 if (device == AUDIO_DEVICE_NONE) {
4763 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4764 }
4765 } break;
4766
4767 default:
4768 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4769 break;
4770 }
4771
4772 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4773 return device;
4774}
4775
Eric Laurente0720872014-03-11 09:30:41 -07004776void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004777{
4778 for (int i = 0; i < NUM_STRATEGIES; i++) {
4779 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4780 }
4781 mPreviousOutputs = mOutputs;
4782}
4783
Eric Laurent1f2f2232014-06-02 12:01:23 -07004784uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004785 audio_devices_t prevDevice,
4786 uint32_t delayMs)
4787{
4788 // mute/unmute strategies using an incompatible device combination
4789 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4790 // if unmuting, unmute only after the specified delay
4791 if (outputDesc->isDuplicated()) {
4792 return 0;
4793 }
4794
4795 uint32_t muteWaitMs = 0;
4796 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004797 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004798
4799 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4800 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004801 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004802 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4803 bool doMute = false;
4804
4805 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4806 doMute = true;
4807 outputDesc->mStrategyMutedByDevice[i] = true;
4808 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4809 doMute = true;
4810 outputDesc->mStrategyMutedByDevice[i] = false;
4811 }
Eric Laurent99401132014-05-07 19:48:15 -07004812 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004813 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004814 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004815 // skip output if it does not share any device with current output
4816 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4817 == AUDIO_DEVICE_NONE) {
4818 continue;
4819 }
4820 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4821 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4822 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4823 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4824 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004825 if (mute) {
4826 // FIXME: should not need to double latency if volume could be applied
4827 // immediately by the audioflinger mixer. We must account for the delay
4828 // between now and the next time the audioflinger thread for this output
4829 // will process a buffer (which corresponds to one buffer size,
4830 // usually 1/2 or 1/4 of the latency).
4831 if (muteWaitMs < desc->latency() * 2) {
4832 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004833 }
4834 }
4835 }
4836 }
4837 }
4838 }
4839
Eric Laurent99401132014-05-07 19:48:15 -07004840 // temporary mute output if device selection changes to avoid volume bursts due to
4841 // different per device volumes
4842 if (outputDesc->isActive() && (device != prevDevice)) {
4843 if (muteWaitMs < outputDesc->latency() * 2) {
4844 muteWaitMs = outputDesc->latency() * 2;
4845 }
4846 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4847 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004848 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004849 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004850 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004851 muteWaitMs *2, device);
4852 }
4853 }
4854 }
4855
Eric Laurente552edb2014-03-10 17:42:56 -07004856 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4857 if (muteWaitMs > delayMs) {
4858 muteWaitMs -= delayMs;
4859 usleep(muteWaitMs * 1000);
4860 return muteWaitMs;
4861 }
4862 return 0;
4863}
4864
Eric Laurente0720872014-03-11 09:30:41 -07004865uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004866 audio_devices_t device,
4867 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004868 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004869 audio_patch_handle_t *patchHandle,
4870 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004871{
4872 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004873 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004874 AudioParameter param;
4875 uint32_t muteWaitMs;
4876
4877 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004878 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4879 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004880 return muteWaitMs;
4881 }
4882 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4883 // output profile
4884 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004885 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004886 return 0;
4887 }
4888
4889 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004890 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004891
4892 audio_devices_t prevDevice = outputDesc->mDevice;
4893
4894 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4895
4896 if (device != AUDIO_DEVICE_NONE) {
4897 outputDesc->mDevice = device;
4898 }
4899 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4900
4901 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004902 // the requested device is AUDIO_DEVICE_NONE
4903 // OR the requested device is the same as current device
4904 // AND force is not specified
4905 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004906 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004907 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4908 outputDesc->mPatchHandle != 0) {
4909 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4910 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004911 return muteWaitMs;
4912 }
4913
4914 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004915
Eric Laurente552edb2014-03-10 17:42:56 -07004916 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004917 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004918 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004919 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004920 DeviceVector deviceList = (address == NULL) ?
4921 mAvailableOutputDevices.getDevicesFromType(device)
4922 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004923 if (!deviceList.isEmpty()) {
4924 struct audio_patch patch;
4925 outputDesc->toAudioPortConfig(&patch.sources[0]);
4926 patch.num_sources = 1;
4927 patch.num_sinks = 0;
4928 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4929 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004930 patch.num_sinks++;
4931 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004932 ssize_t index;
4933 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4934 index = mAudioPatches.indexOfKey(*patchHandle);
4935 } else {
4936 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4937 }
4938 sp< AudioPatch> patchDesc;
4939 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4940 if (index >= 0) {
4941 patchDesc = mAudioPatches.valueAt(index);
4942 afPatchHandle = patchDesc->mAfPatchHandle;
4943 }
4944
Eric Laurent1c333e22014-05-20 10:48:17 -07004945 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004946 &afPatchHandle,
4947 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004948 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4949 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004951 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004952 if (index < 0) {
4953 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4954 &patch, mUidCached);
4955 addAudioPatch(patchDesc->mHandle, patchDesc);
4956 } else {
4957 patchDesc->mPatch = patch;
4958 }
4959 patchDesc->mAfPatchHandle = afPatchHandle;
4960 patchDesc->mUid = mUidCached;
4961 if (patchHandle) {
4962 *patchHandle = patchDesc->mHandle;
4963 }
4964 outputDesc->mPatchHandle = patchDesc->mHandle;
4965 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004966 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004967 }
4968 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004969
4970 // inform all input as well
4971 for (size_t i = 0; i < mInputs.size(); i++) {
4972 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4973 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4974 AudioParameter inputCmd = AudioParameter();
4975 ALOGV("%s: inform input %d of device:%d", __func__,
4976 inputDescriptor->mIoHandle, device);
4977 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4978 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4979 inputCmd.toString(),
4980 delayMs);
4981 }
4982 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004983 }
Eric Laurente552edb2014-03-10 17:42:56 -07004984
4985 // update stream volumes according to new device
4986 applyStreamVolumes(output, device, delayMs);
4987
4988 return muteWaitMs;
4989}
4990
Eric Laurent1c333e22014-05-20 10:48:17 -07004991status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 int delayMs,
4993 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004994{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004995 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004996 ssize_t index;
4997 if (patchHandle) {
4998 index = mAudioPatches.indexOfKey(*patchHandle);
4999 } else {
5000 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
5001 }
5002 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005003 return INVALID_OPERATION;
5004 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005005 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5006 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005007 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
5008 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005009 removeAudioPatch(patchDesc->mHandle);
5010 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005011 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005012 return status;
5013}
5014
5015status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5016 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005017 bool force,
5018 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005019{
5020 status_t status = NO_ERROR;
5021
Eric Laurent1f2f2232014-06-02 12:01:23 -07005022 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005023 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5024 inputDesc->mDevice = device;
5025
5026 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5027 if (!deviceList.isEmpty()) {
5028 struct audio_patch patch;
5029 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005030 // AUDIO_SOURCE_HOTWORD is for internal use only:
5031 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005032 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
5033 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005034 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5035 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005036 patch.num_sinks = 1;
5037 //only one input device for now
5038 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005039 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 ssize_t index;
5041 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5042 index = mAudioPatches.indexOfKey(*patchHandle);
5043 } else {
5044 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5045 }
5046 sp< AudioPatch> patchDesc;
5047 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5048 if (index >= 0) {
5049 patchDesc = mAudioPatches.valueAt(index);
5050 afPatchHandle = patchDesc->mAfPatchHandle;
5051 }
5052
Eric Laurent1c333e22014-05-20 10:48:17 -07005053 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005054 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005055 0);
5056 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005057 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005058 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005059 if (index < 0) {
5060 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5061 &patch, mUidCached);
5062 addAudioPatch(patchDesc->mHandle, patchDesc);
5063 } else {
5064 patchDesc->mPatch = patch;
5065 }
5066 patchDesc->mAfPatchHandle = afPatchHandle;
5067 patchDesc->mUid = mUidCached;
5068 if (patchHandle) {
5069 *patchHandle = patchDesc->mHandle;
5070 }
5071 inputDesc->mPatchHandle = patchDesc->mHandle;
5072 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005073 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005074 }
5075 }
5076 }
5077 return status;
5078}
5079
Eric Laurent6a94d692014-05-20 11:18:06 -07005080status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5081 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005082{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005083 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005084 ssize_t index;
5085 if (patchHandle) {
5086 index = mAudioPatches.indexOfKey(*patchHandle);
5087 } else {
5088 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5089 }
5090 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005091 return INVALID_OPERATION;
5092 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005093 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5094 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005095 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5096 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005097 removeAudioPatch(patchDesc->mHandle);
5098 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005099 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005100 return status;
5101}
5102
5103sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08005104 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07005105 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005106 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005107 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07005108 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005109{
5110 // Choose an input profile based on the requested capture parameters: select the first available
5111 // profile supporting all requested parameters.
5112
5113 for (size_t i = 0; i < mHwModules.size(); i++)
5114 {
5115 if (mHwModules[i]->mHandle == 0) {
5116 continue;
5117 }
5118 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5119 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005120 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005121 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005122 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005123 &samplingRate /*updatedSamplingRate*/,
5124 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005125
Eric Laurente552edb2014-03-10 17:42:56 -07005126 return profile;
5127 }
5128 }
5129 }
5130 return NULL;
5131}
5132
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005133
5134audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
Eric Laurentc722f302014-12-10 11:21:49 -08005135 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005136{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005137 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5138 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005139
5140 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5141 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5142 continue;
5143 }
5144 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5145 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5146 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5147 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5148 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5149 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurentc722f302014-12-10 11:21:49 -08005150 if (policyMix != NULL) {
5151 *policyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005152 }
5153 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5154 }
5155 break;
5156 }
5157 }
5158 }
5159
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005160 return getDeviceForInputSource(inputSource);
5161}
5162
5163audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5164{
5165 uint32_t device = AUDIO_DEVICE_NONE;
5166 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5167 ~AUDIO_DEVICE_BIT_IN;
5168
Eric Laurente552edb2014-03-10 17:42:56 -07005169 switch (inputSource) {
5170 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005171 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005172 device = AUDIO_DEVICE_IN_VOICE_CALL;
5173 break;
5174 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005175 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005176
5177 case AUDIO_SOURCE_DEFAULT:
5178 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005179 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5180 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentdc136ff2014-12-16 12:24:18 -08005181 } else if ((mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO) &&
5182 (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET)) {
5183 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005184 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5185 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5186 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5187 device = AUDIO_DEVICE_IN_USB_DEVICE;
5188 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5189 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005190 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005191 break;
5192
5193 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5194 // Allow only use of devices on primary input if in call and HAL does not support routing
5195 // to voice call path.
5196 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5197 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5198 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5199 }
5200
5201 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5202 case AUDIO_POLICY_FORCE_BT_SCO:
5203 // if SCO device is requested but no SCO device is available, fall back to default case
5204 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5205 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5206 break;
5207 }
5208 // FALL THROUGH
5209
5210 default: // FORCE_NONE
5211 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5212 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5213 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5214 device = AUDIO_DEVICE_IN_USB_DEVICE;
5215 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5216 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5217 }
5218 break;
5219
5220 case AUDIO_POLICY_FORCE_SPEAKER:
5221 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5222 device = AUDIO_DEVICE_IN_BACK_MIC;
5223 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5224 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5225 }
5226 break;
5227 }
5228 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005229
Eric Laurente552edb2014-03-10 17:42:56 -07005230 case AUDIO_SOURCE_VOICE_RECOGNITION:
5231 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005232 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005233 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005234 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005235 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005236 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005237 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5238 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005239 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005240 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5241 }
5242 break;
5243 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005244 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005245 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005246 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005247 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5248 }
5249 break;
5250 case AUDIO_SOURCE_VOICE_DOWNLINK:
5251 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005252 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005253 device = AUDIO_DEVICE_IN_VOICE_CALL;
5254 }
5255 break;
5256 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005257 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005258 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5259 }
5260 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005261 case AUDIO_SOURCE_FM_TUNER:
5262 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5263 device = AUDIO_DEVICE_IN_FM_TUNER;
5264 }
5265 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005266 default:
5267 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5268 break;
5269 }
5270 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5271 return device;
5272}
5273
Eric Laurente0720872014-03-11 09:30:41 -07005274bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005275{
5276 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5277 device &= ~AUDIO_DEVICE_BIT_IN;
5278 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5279 return true;
5280 }
5281 return false;
5282}
5283
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005284bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005285 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005286}
5287
Eric Laurente0720872014-03-11 09:30:41 -07005288audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005289{
5290 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005291 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005292 if ((input_descriptor->mRefCount > 0)
5293 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5294 return mInputs.keyAt(i);
5295 }
5296 }
5297 return 0;
5298}
5299
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005300uint32_t AudioPolicyManager::activeInputsCount() const
5301{
5302 uint32_t count = 0;
5303 for (size_t i = 0; i < mInputs.size(); i++) {
5304 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5305 if (desc->mRefCount > 0) {
Eric Laurenta34c9ce2014-12-19 11:16:32 -08005306 count++;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005307 }
5308 }
5309 return count;
5310}
5311
Eric Laurente552edb2014-03-10 17:42:56 -07005312
Eric Laurente0720872014-03-11 09:30:41 -07005313audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005314{
5315 if (device == AUDIO_DEVICE_NONE) {
5316 // this happens when forcing a route update and no track is active on an output.
5317 // In this case the returned category is not important.
5318 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005319 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005320 // Multiple device selection is either:
5321 // - speaker + one other device: give priority to speaker in this case.
5322 // - one A2DP device + another device: happens with duplicated output. In this case
5323 // retain the device on the A2DP output as the other must not correspond to an active
5324 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005325 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005326 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5327 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005328 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5329 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5330 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5331 device = AUDIO_DEVICE_OUT_AUX_LINE;
5332 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5333 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005334 } else {
5335 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5336 }
5337 }
5338
Jon Eklund11c9fb12014-06-23 14:47:03 -05005339 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5340 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5341 device = AUDIO_DEVICE_OUT_SPEAKER;
5342
Eric Laurent3b73df72014-03-11 09:06:29 -07005343 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005344 "getDeviceForVolume() invalid device combination: %08x",
5345 device);
5346
5347 return device;
5348}
5349
Eric Laurente0720872014-03-11 09:30:41 -07005350AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005351{
5352 switch(getDeviceForVolume(device)) {
5353 case AUDIO_DEVICE_OUT_EARPIECE:
5354 return DEVICE_CATEGORY_EARPIECE;
5355 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5356 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5357 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5358 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5359 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5360 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5361 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005362 case AUDIO_DEVICE_OUT_LINE:
5363 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5364 /*USB? Remote submix?*/
5365 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005366 case AUDIO_DEVICE_OUT_SPEAKER:
5367 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5368 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005369 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5370 case AUDIO_DEVICE_OUT_USB_DEVICE:
5371 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5372 default:
5373 return DEVICE_CATEGORY_SPEAKER;
5374 }
5375}
5376
Eric Laurent223fd5c2014-11-11 13:43:36 -08005377/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005378float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005379 int indexInUi)
5380{
5381 device_category deviceCategory = getDeviceCategory(device);
5382 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5383
5384 // the volume index in the UI is relative to the min and max volume indices for this stream type
5385 int nbSteps = 1 + curve[VOLMAX].mIndex -
5386 curve[VOLMIN].mIndex;
5387 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5388 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5389
5390 // find what part of the curve this index volume belongs to, or if it's out of bounds
5391 int segment = 0;
5392 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5393 return 0.0f;
5394 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5395 segment = 0;
5396 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5397 segment = 1;
5398 } else if (volIdx <= curve[VOLMAX].mIndex) {
5399 segment = 2;
5400 } else { // out of bounds
5401 return 1.0f;
5402 }
5403
5404 // linear interpolation in the attenuation table in dB
5405 float decibels = curve[segment].mDBAttenuation +
5406 ((float)(volIdx - curve[segment].mIndex)) *
5407 ( (curve[segment+1].mDBAttenuation -
5408 curve[segment].mDBAttenuation) /
5409 ((float)(curve[segment+1].mIndex -
5410 curve[segment].mIndex)) );
5411
5412 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5413
5414 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5415 curve[segment].mIndex, volIdx,
5416 curve[segment+1].mIndex,
5417 curve[segment].mDBAttenuation,
5418 decibels,
5419 curve[segment+1].mDBAttenuation,
5420 amplification);
5421
5422 return amplification;
5423}
5424
Eric Laurente0720872014-03-11 09:30:41 -07005425const AudioPolicyManager::VolumeCurvePoint
5426 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005427 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5428};
5429
Eric Laurente0720872014-03-11 09:30:41 -07005430const AudioPolicyManager::VolumeCurvePoint
5431 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005432 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5433};
5434
Eric Laurente0720872014-03-11 09:30:41 -07005435const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005436 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5437 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5438};
5439
5440const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005441 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005442 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5443};
5444
Eric Laurente0720872014-03-11 09:30:41 -07005445const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005446 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005447 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005448};
5449
5450const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005451 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005452 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5453};
5454
Eric Laurente0720872014-03-11 09:30:41 -07005455const AudioPolicyManager::VolumeCurvePoint
5456 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005457 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5458};
5459
5460// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5461// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5462// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5463// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5464
Eric Laurente0720872014-03-11 09:30:41 -07005465const AudioPolicyManager::VolumeCurvePoint
5466 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005467 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5468};
5469
Eric Laurente0720872014-03-11 09:30:41 -07005470const AudioPolicyManager::VolumeCurvePoint
5471 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005472 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5473};
5474
Eric Laurente0720872014-03-11 09:30:41 -07005475const AudioPolicyManager::VolumeCurvePoint
5476 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005477 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5478};
5479
Eric Laurente0720872014-03-11 09:30:41 -07005480const AudioPolicyManager::VolumeCurvePoint
5481 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005482 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5483};
5484
Eric Laurente0720872014-03-11 09:30:41 -07005485const AudioPolicyManager::VolumeCurvePoint
5486 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005487 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5488};
5489
Eric Laurente0720872014-03-11 09:30:41 -07005490const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005491 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5492 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5493};
5494
5495const AudioPolicyManager::VolumeCurvePoint
5496 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5497 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5498};
5499
5500const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005501 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5502 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5503};
5504
5505const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005506 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5507 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005508 { // AUDIO_STREAM_VOICE_CALL
5509 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5510 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005511 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5512 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005513 },
5514 { // AUDIO_STREAM_SYSTEM
5515 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5516 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005517 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5518 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005519 },
5520 { // AUDIO_STREAM_RING
5521 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5522 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005523 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5524 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005525 },
5526 { // AUDIO_STREAM_MUSIC
5527 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5528 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005529 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5530 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005531 },
5532 { // AUDIO_STREAM_ALARM
5533 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5534 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005535 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5536 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005537 },
5538 { // AUDIO_STREAM_NOTIFICATION
5539 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5540 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005541 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5542 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005543 },
5544 { // AUDIO_STREAM_BLUETOOTH_SCO
5545 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5546 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005547 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5548 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005549 },
5550 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5551 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5552 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005553 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5554 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005555 },
5556 { // AUDIO_STREAM_DTMF
5557 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5558 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005559 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5560 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005561 },
5562 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005563 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5564 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5565 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5566 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5567 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005568 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005569 { // AUDIO_STREAM_ACCESSIBILITY
5570 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5571 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5572 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5573 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5574 },
5575 { // AUDIO_STREAM_REROUTING
5576 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5577 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5578 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5579 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5580 },
5581 { // AUDIO_STREAM_PATCH
5582 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5583 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5584 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5585 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5586 },
Eric Laurente552edb2014-03-10 17:42:56 -07005587};
5588
Eric Laurente0720872014-03-11 09:30:41 -07005589void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005590{
5591 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5592 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5593 mStreams[i].mVolumeCurve[j] =
5594 sVolumeProfiles[i][j];
5595 }
5596 }
5597
5598 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5599 if (mSpeakerDrcEnabled) {
5600 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5601 sDefaultSystemVolumeCurveDrc;
5602 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5603 sSpeakerSonificationVolumeCurveDrc;
5604 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5605 sSpeakerSonificationVolumeCurveDrc;
5606 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5607 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005608 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5609 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005610 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5611 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005612 }
5613}
5614
Eric Laurente0720872014-03-11 09:30:41 -07005615float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005616 int index,
5617 audio_io_handle_t output,
5618 audio_devices_t device)
5619{
5620 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005621 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005622 StreamDescriptor &streamDesc = mStreams[stream];
5623
5624 if (device == AUDIO_DEVICE_NONE) {
5625 device = outputDesc->device();
5626 }
5627
Eric Laurente552edb2014-03-10 17:42:56 -07005628 volume = volIndexToAmpl(device, streamDesc, index);
5629
5630 // if a headset is connected, apply the following rules to ring tones and notifications
5631 // to avoid sound level bursts in user's ears:
5632 // - always attenuate ring tones and notifications volume by 6dB
5633 // - if music is playing, always limit the volume to current music volume,
5634 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005635 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005636 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5637 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5638 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5639 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5640 ((stream_strategy == STRATEGY_SONIFICATION)
5641 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005642 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005643 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005644 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005645 streamDesc.mCanBeMuted) {
5646 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5647 // when the phone is ringing we must consider that music could have been paused just before
5648 // by the music application and behave as if music was active if the last music track was
5649 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005650 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005651 mLimitRingtoneVolume) {
5652 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005653 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5654 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005655 output,
5656 musicDevice);
5657 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5658 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5659 if (volume > minVol) {
5660 volume = minVol;
5661 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5662 }
5663 }
5664 }
5665
5666 return volume;
5667}
5668
Eric Laurente0720872014-03-11 09:30:41 -07005669status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005670 int index,
5671 audio_io_handle_t output,
5672 audio_devices_t device,
5673 int delayMs,
5674 bool force)
5675{
5676
5677 // do not change actual stream volume if the stream is muted
5678 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5679 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5680 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5681 return NO_ERROR;
5682 }
5683
5684 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005685 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5686 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5687 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5688 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005689 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005690 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005691 return INVALID_OPERATION;
5692 }
5693
5694 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005695 // unit gain if rerouting to external policy
5696 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5697 ssize_t index = mOutputs.indexOfKey(output);
5698 if (index >= 0) {
5699 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurentc722f302014-12-10 11:21:49 -08005700 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005701 ALOGV("max gain when rerouting for output=%d", output);
5702 volume = 1.0f;
5703 }
5704 }
5705
5706 }
Eric Laurente552edb2014-03-10 17:42:56 -07005707 // We actually change the volume if:
5708 // - the float value returned by computeVolume() changed
5709 // - the force flag is set
5710 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5711 force) {
5712 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5713 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5714 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5715 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005716 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5717 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005718 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005719 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005720 }
5721
Eric Laurent3b73df72014-03-11 09:06:29 -07005722 if (stream == AUDIO_STREAM_VOICE_CALL ||
5723 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005724 float voiceVolume;
5725 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005726 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005727 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5728 } else {
5729 voiceVolume = 1.0;
5730 }
5731
5732 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5733 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5734 mLastVoiceVolume = voiceVolume;
5735 }
5736 }
5737
5738 return NO_ERROR;
5739}
5740
Eric Laurente0720872014-03-11 09:30:41 -07005741void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005742 audio_devices_t device,
5743 int delayMs,
5744 bool force)
5745{
5746 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5747
Eric Laurent3b73df72014-03-11 09:06:29 -07005748 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005749 if (stream == AUDIO_STREAM_PATCH) {
5750 continue;
5751 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005752 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005753 mStreams[stream].getVolumeIndex(device),
5754 output,
5755 device,
5756 delayMs,
5757 force);
5758 }
5759}
5760
Eric Laurente0720872014-03-11 09:30:41 -07005761void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005762 bool on,
5763 audio_io_handle_t output,
5764 int delayMs,
5765 audio_devices_t device)
5766{
5767 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005768 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005769 if (stream == AUDIO_STREAM_PATCH) {
5770 continue;
5771 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005772 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5773 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005774 }
5775 }
5776}
5777
Eric Laurente0720872014-03-11 09:30:41 -07005778void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005779 bool on,
5780 audio_io_handle_t output,
5781 int delayMs,
5782 audio_devices_t device)
5783{
5784 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005785 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005786 if (device == AUDIO_DEVICE_NONE) {
5787 device = outputDesc->device();
5788 }
5789
5790 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5791 stream, on, output, outputDesc->mMuteCount[stream], device);
5792
5793 if (on) {
5794 if (outputDesc->mMuteCount[stream] == 0) {
5795 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005796 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5797 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005798 checkAndSetVolume(stream, 0, output, device, delayMs);
5799 }
5800 }
5801 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5802 outputDesc->mMuteCount[stream]++;
5803 } else {
5804 if (outputDesc->mMuteCount[stream] == 0) {
5805 ALOGV("setStreamMute() unmuting non muted stream!");
5806 return;
5807 }
5808 if (--outputDesc->mMuteCount[stream] == 0) {
5809 checkAndSetVolume(stream,
5810 streamDesc.getVolumeIndex(device),
5811 output,
5812 device,
5813 delayMs);
5814 }
5815 }
5816}
5817
Eric Laurente0720872014-03-11 09:30:41 -07005818void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005819 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005820{
5821 // if the stream pertains to sonification strategy and we are in call we must
5822 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5823 // in the device used for phone strategy and play the tone if the selected device does not
5824 // interfere with the device used for phone strategy
5825 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5826 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005827 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005828 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5829 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005830 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005831 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5832 stream, starting, outputDesc->mDevice, stateChange);
5833 if (outputDesc->mRefCount[stream]) {
5834 int muteCount = 1;
5835 if (stateChange) {
5836 muteCount = outputDesc->mRefCount[stream];
5837 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005838 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005839 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5840 for (int i = 0; i < muteCount; i++) {
5841 setStreamMute(stream, starting, mPrimaryOutput);
5842 }
5843 } else {
5844 ALOGV("handleIncallSonification() high visibility");
5845 if (outputDesc->device() &
5846 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5847 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5848 for (int i = 0; i < muteCount; i++) {
5849 setStreamMute(stream, starting, mPrimaryOutput);
5850 }
5851 }
5852 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005853 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5854 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005855 } else {
5856 mpClientInterface->stopTone();
5857 }
5858 }
5859 }
5860 }
5861}
5862
Eric Laurente0720872014-03-11 09:30:41 -07005863bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005864{
5865 return isStateInCall(mPhoneState);
5866}
5867
Eric Laurente0720872014-03-11 09:30:41 -07005868bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005869 return ((state == AUDIO_MODE_IN_CALL) ||
5870 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005871}
5872
Eric Laurente0720872014-03-11 09:30:41 -07005873uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005874{
5875 return MAX_EFFECTS_CPU_LOAD;
5876}
5877
Eric Laurente0720872014-03-11 09:30:41 -07005878uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005879{
5880 return MAX_EFFECTS_MEMORY;
5881}
5882
Eric Laurent6a94d692014-05-20 11:18:06 -07005883
Eric Laurente552edb2014-03-10 17:42:56 -07005884// --- AudioOutputDescriptor class implementation
5885
Eric Laurente0720872014-03-11 09:30:41 -07005886AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005887 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005888 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurentc722f302014-12-10 11:21:49 -08005889 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
Eric Laurent275e8e92014-11-30 15:14:47 -08005890 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005891 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5892{
5893 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005894 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005895 mRefCount[i] = 0;
5896 mCurVolume[i] = -1.0;
5897 mMuteCount[i] = 0;
5898 mStopTime[i] = 0;
5899 }
5900 for (int i = 0; i < NUM_STRATEGIES; i++) {
5901 mStrategyMutedByDevice[i] = false;
5902 }
5903 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005904 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005905 mSamplingRate = profile->pickSamplingRate();
5906 mFormat = profile->pickFormat();
5907 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005908 if (profile->mGains.size() > 0) {
5909 profile->mGains[0]->getDefaultConfig(&mGain);
5910 }
Eric Laurente552edb2014-03-10 17:42:56 -07005911 }
5912}
5913
Eric Laurente0720872014-03-11 09:30:41 -07005914audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005915{
5916 if (isDuplicated()) {
5917 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5918 } else {
5919 return mDevice;
5920 }
5921}
5922
Eric Laurente0720872014-03-11 09:30:41 -07005923uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005924{
5925 if (isDuplicated()) {
5926 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5927 } else {
5928 return mLatency;
5929 }
5930}
5931
Eric Laurente0720872014-03-11 09:30:41 -07005932bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005933 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005934{
5935 if (isDuplicated()) {
5936 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5937 } else if (outputDesc->isDuplicated()){
5938 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5939 } else {
5940 return (mProfile->mModule == outputDesc->mProfile->mModule);
5941 }
5942}
5943
Eric Laurente0720872014-03-11 09:30:41 -07005944void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005945 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005946{
5947 // forward usage count change to attached outputs
5948 if (isDuplicated()) {
5949 mOutput1->changeRefCount(stream, delta);
5950 mOutput2->changeRefCount(stream, delta);
5951 }
5952 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005953 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5954 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005955 mRefCount[stream] = 0;
5956 return;
5957 }
5958 mRefCount[stream] += delta;
5959 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5960}
5961
Eric Laurente0720872014-03-11 09:30:41 -07005962audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005963{
5964 if (isDuplicated()) {
5965 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5966 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005967 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005968 }
5969}
5970
Eric Laurente0720872014-03-11 09:30:41 -07005971bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005972{
5973 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5974}
5975
Eric Laurente0720872014-03-11 09:30:41 -07005976bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005977 uint32_t inPastMs,
5978 nsecs_t sysTime) const
5979{
5980 if ((sysTime == 0) && (inPastMs != 0)) {
5981 sysTime = systemTime();
5982 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005983 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005984 if (i == AUDIO_STREAM_PATCH) {
5985 continue;
5986 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005987 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005988 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005989 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005990 return true;
5991 }
5992 }
5993 return false;
5994}
5995
Eric Laurente0720872014-03-11 09:30:41 -07005996bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005997 uint32_t inPastMs,
5998 nsecs_t sysTime) const
5999{
6000 if (mRefCount[stream] != 0) {
6001 return true;
6002 }
6003 if (inPastMs == 0) {
6004 return false;
6005 }
6006 if (sysTime == 0) {
6007 sysTime = systemTime();
6008 }
6009 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
6010 return true;
6011 }
6012 return false;
6013}
6014
Eric Laurent1c333e22014-05-20 10:48:17 -07006015void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006016 struct audio_port_config *dstConfig,
6017 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006018{
Eric Laurent84c70242014-06-23 08:46:27 -07006019 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
6020
Eric Laurent1f2f2232014-06-02 12:01:23 -07006021 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6022 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6023 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006024 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006025 }
6026 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6027
Eric Laurent6a94d692014-05-20 11:18:06 -07006028 dstConfig->id = mId;
6029 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
6030 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07006031 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6032 dstConfig->ext.mix.handle = mIoHandle;
6033 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07006034}
6035
6036void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
6037 struct audio_port *port) const
6038{
Eric Laurent84c70242014-06-23 08:46:27 -07006039 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07006040 mProfile->toAudioPort(port);
6041 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006042 toAudioPortConfig(&port->active_config);
6043 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006044 port->ext.mix.handle = mIoHandle;
6045 port->ext.mix.latency_class =
6046 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
6047}
Eric Laurente552edb2014-03-10 17:42:56 -07006048
Eric Laurente0720872014-03-11 09:30:41 -07006049status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006050{
6051 const size_t SIZE = 256;
6052 char buffer[SIZE];
6053 String8 result;
6054
Eric Laurent4d416952014-08-10 14:07:09 -07006055 snprintf(buffer, SIZE, " ID: %d\n", mId);
6056 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006057 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6058 result.append(buffer);
6059 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
6060 result.append(buffer);
6061 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6062 result.append(buffer);
6063 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
6064 result.append(buffer);
6065 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
6066 result.append(buffer);
6067 snprintf(buffer, SIZE, " Devices %08x\n", device());
6068 result.append(buffer);
6069 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
6070 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07006071 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6072 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
6073 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07006074 result.append(buffer);
6075 }
6076 write(fd, result.string(), result.size());
6077
6078 return NO_ERROR;
6079}
6080
6081// --- AudioInputDescriptor class implementation
6082
Eric Laurent1c333e22014-05-20 10:48:17 -07006083AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006084 : mId(0), mIoHandle(0),
Eric Laurentc722f302014-12-10 11:21:49 -08006085 mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006086 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07006087{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006088 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006089 mSamplingRate = profile->pickSamplingRate();
6090 mFormat = profile->pickFormat();
6091 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07006092 if (profile->mGains.size() > 0) {
6093 profile->mGains[0]->getDefaultConfig(&mGain);
6094 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006095 }
Eric Laurente552edb2014-03-10 17:42:56 -07006096}
6097
Eric Laurent1c333e22014-05-20 10:48:17 -07006098void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006099 struct audio_port_config *dstConfig,
6100 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006101{
Eric Laurent84c70242014-06-23 08:46:27 -07006102 ALOG_ASSERT(mProfile != 0,
6103 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07006104 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6105 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6106 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006107 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006108 }
6109
6110 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6111
Eric Laurent6a94d692014-05-20 11:18:06 -07006112 dstConfig->id = mId;
6113 dstConfig->role = AUDIO_PORT_ROLE_SINK;
6114 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07006115 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6116 dstConfig->ext.mix.handle = mIoHandle;
6117 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07006118}
6119
6120void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6121 struct audio_port *port) const
6122{
Eric Laurent84c70242014-06-23 08:46:27 -07006123 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6124
Eric Laurent1c333e22014-05-20 10:48:17 -07006125 mProfile->toAudioPort(port);
6126 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006127 toAudioPortConfig(&port->active_config);
6128 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006129 port->ext.mix.handle = mIoHandle;
6130 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6131}
6132
Eric Laurente0720872014-03-11 09:30:41 -07006133status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006134{
6135 const size_t SIZE = 256;
6136 char buffer[SIZE];
6137 String8 result;
6138
Eric Laurent4d416952014-08-10 14:07:09 -07006139 snprintf(buffer, SIZE, " ID: %d\n", mId);
6140 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006141 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6142 result.append(buffer);
6143 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6144 result.append(buffer);
6145 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6146 result.append(buffer);
6147 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6148 result.append(buffer);
6149 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6150 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006151 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6152 result.append(buffer);
6153
Eric Laurente552edb2014-03-10 17:42:56 -07006154 write(fd, result.string(), result.size());
6155
6156 return NO_ERROR;
6157}
6158
6159// --- StreamDescriptor class implementation
6160
Eric Laurente0720872014-03-11 09:30:41 -07006161AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006162 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6163{
6164 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6165}
6166
Eric Laurente0720872014-03-11 09:30:41 -07006167int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006168{
Eric Laurente0720872014-03-11 09:30:41 -07006169 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006170 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6171 if (mIndexCur.indexOfKey(device) < 0) {
6172 device = AUDIO_DEVICE_OUT_DEFAULT;
6173 }
6174 return mIndexCur.valueFor(device);
6175}
6176
Eric Laurente0720872014-03-11 09:30:41 -07006177void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006178{
6179 const size_t SIZE = 256;
6180 char buffer[SIZE];
6181 String8 result;
6182
6183 snprintf(buffer, SIZE, "%s %02d %02d ",
6184 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6185 result.append(buffer);
6186 for (size_t i = 0; i < mIndexCur.size(); i++) {
6187 snprintf(buffer, SIZE, "%04x : %02d, ",
6188 mIndexCur.keyAt(i),
6189 mIndexCur.valueAt(i));
6190 result.append(buffer);
6191 }
6192 result.append("\n");
6193
6194 write(fd, result.string(), result.size());
6195}
6196
6197// --- EffectDescriptor class implementation
6198
Eric Laurente0720872014-03-11 09:30:41 -07006199status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006200{
6201 const size_t SIZE = 256;
6202 char buffer[SIZE];
6203 String8 result;
6204
6205 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6206 result.append(buffer);
6207 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6208 result.append(buffer);
6209 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6210 result.append(buffer);
6211 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6212 result.append(buffer);
6213 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6214 result.append(buffer);
6215 write(fd, result.string(), result.size());
6216
6217 return NO_ERROR;
6218}
6219
Eric Laurent1c333e22014-05-20 10:48:17 -07006220// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006221
Eric Laurente0720872014-03-11 09:30:41 -07006222AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006223 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6224 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006225{
6226}
6227
Eric Laurente0720872014-03-11 09:30:41 -07006228AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006229{
6230 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006231 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006232 }
6233 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006234 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006235 }
6236 free((void *)mName);
6237}
6238
Eric Laurent1afeecb2014-05-14 08:52:28 -07006239status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6240{
6241 cnode *node = root->first_child;
6242
6243 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6244
6245 while (node) {
6246 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6247 profile->loadSamplingRates((char *)node->value);
6248 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6249 profile->loadFormats((char *)node->value);
6250 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6251 profile->loadInChannels((char *)node->value);
6252 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6253 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6254 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006255 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6256 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006257 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6258 profile->loadGains(node);
6259 }
6260 node = node->next;
6261 }
6262 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6263 "loadInput() invalid supported devices");
6264 ALOGW_IF(profile->mChannelMasks.size() == 0,
6265 "loadInput() invalid supported channel masks");
6266 ALOGW_IF(profile->mSamplingRates.size() == 0,
6267 "loadInput() invalid supported sampling rates");
6268 ALOGW_IF(profile->mFormats.size() == 0,
6269 "loadInput() invalid supported formats");
6270 if (!profile->mSupportedDevices.isEmpty() &&
6271 (profile->mChannelMasks.size() != 0) &&
6272 (profile->mSamplingRates.size() != 0) &&
6273 (profile->mFormats.size() != 0)) {
6274
6275 ALOGV("loadInput() adding input Supported Devices %04x",
6276 profile->mSupportedDevices.types());
6277
6278 mInputProfiles.add(profile);
6279 return NO_ERROR;
6280 } else {
6281 return BAD_VALUE;
6282 }
6283}
6284
6285status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6286{
6287 cnode *node = root->first_child;
6288
6289 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6290
6291 while (node) {
6292 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6293 profile->loadSamplingRates((char *)node->value);
6294 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6295 profile->loadFormats((char *)node->value);
6296 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6297 profile->loadOutChannels((char *)node->value);
6298 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6299 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6300 mDeclaredDevices);
6301 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006302 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006303 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6304 profile->loadGains(node);
6305 }
6306 node = node->next;
6307 }
6308 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6309 "loadOutput() invalid supported devices");
6310 ALOGW_IF(profile->mChannelMasks.size() == 0,
6311 "loadOutput() invalid supported channel masks");
6312 ALOGW_IF(profile->mSamplingRates.size() == 0,
6313 "loadOutput() invalid supported sampling rates");
6314 ALOGW_IF(profile->mFormats.size() == 0,
6315 "loadOutput() invalid supported formats");
6316 if (!profile->mSupportedDevices.isEmpty() &&
6317 (profile->mChannelMasks.size() != 0) &&
6318 (profile->mSamplingRates.size() != 0) &&
6319 (profile->mFormats.size() != 0)) {
6320
6321 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6322 profile->mSupportedDevices.types(), profile->mFlags);
6323
6324 mOutputProfiles.add(profile);
6325 return NO_ERROR;
6326 } else {
6327 return BAD_VALUE;
6328 }
6329}
6330
6331status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6332{
6333 cnode *node = root->first_child;
6334
6335 audio_devices_t type = AUDIO_DEVICE_NONE;
6336 while (node) {
6337 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6338 type = parseDeviceNames((char *)node->value);
6339 break;
6340 }
6341 node = node->next;
6342 }
6343 if (type == AUDIO_DEVICE_NONE ||
6344 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6345 ALOGW("loadDevice() bad type %08x", type);
6346 return BAD_VALUE;
6347 }
6348 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6349 deviceDesc->mModule = this;
6350
6351 node = root->first_child;
6352 while (node) {
6353 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6354 deviceDesc->mAddress = String8((char *)node->value);
6355 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6356 if (audio_is_input_device(type)) {
6357 deviceDesc->loadInChannels((char *)node->value);
6358 } else {
6359 deviceDesc->loadOutChannels((char *)node->value);
6360 }
6361 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6362 deviceDesc->loadGains(node);
6363 }
6364 node = node->next;
6365 }
6366
6367 ALOGV("loadDevice() adding device name %s type %08x address %s",
6368 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6369
6370 mDeclaredDevices.add(deviceDesc);
6371
6372 return NO_ERROR;
6373}
6374
Eric Laurent275e8e92014-11-30 15:14:47 -08006375status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6376 audio_devices_t device, String8 address)
6377{
6378 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6379
6380 profile->mSamplingRates.add(config->sample_rate);
6381 profile->mChannelMasks.add(config->channel_mask);
6382 profile->mFormats.add(config->format);
6383
6384 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6385 devDesc->mAddress = address;
6386 profile->mSupportedDevices.add(devDesc);
6387
6388 mOutputProfiles.add(profile);
6389
6390 return NO_ERROR;
6391}
6392
6393status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6394{
6395 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6396 if (mOutputProfiles[i]->mName == name) {
6397 mOutputProfiles.removeAt(i);
6398 break;
6399 }
6400 }
6401
6402 return NO_ERROR;
6403}
6404
6405status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6406 audio_devices_t device, String8 address)
6407{
6408 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6409
6410 profile->mSamplingRates.add(config->sample_rate);
6411 profile->mChannelMasks.add(config->channel_mask);
6412 profile->mFormats.add(config->format);
6413
6414 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6415 devDesc->mAddress = address;
6416 profile->mSupportedDevices.add(devDesc);
6417
6418 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6419
6420 mInputProfiles.add(profile);
6421
6422 return NO_ERROR;
6423}
6424
6425status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6426{
6427 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6428 if (mInputProfiles[i]->mName == name) {
6429 mInputProfiles.removeAt(i);
6430 break;
6431 }
6432 }
6433
6434 return NO_ERROR;
6435}
6436
6437
Eric Laurente0720872014-03-11 09:30:41 -07006438void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006439{
6440 const size_t SIZE = 256;
6441 char buffer[SIZE];
6442 String8 result;
6443
6444 snprintf(buffer, SIZE, " - name: %s\n", mName);
6445 result.append(buffer);
6446 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6447 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006448 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6449 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006450 write(fd, result.string(), result.size());
6451 if (mOutputProfiles.size()) {
6452 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6453 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006454 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006455 write(fd, buffer, strlen(buffer));
6456 mOutputProfiles[i]->dump(fd);
6457 }
6458 }
6459 if (mInputProfiles.size()) {
6460 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6461 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006462 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006463 write(fd, buffer, strlen(buffer));
6464 mInputProfiles[i]->dump(fd);
6465 }
6466 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006467 if (mDeclaredDevices.size()) {
6468 write(fd, " - devices:\n", strlen(" - devices:\n"));
6469 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6470 mDeclaredDevices[i]->dump(fd, 4, i);
6471 }
6472 }
Eric Laurente552edb2014-03-10 17:42:56 -07006473}
6474
Eric Laurent1c333e22014-05-20 10:48:17 -07006475// --- AudioPort class implementation
6476
Eric Laurenta121f902014-06-03 13:32:54 -07006477
6478AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6479 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006480 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006481{
6482 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6483 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6484}
6485
Eric Laurent1c333e22014-05-20 10:48:17 -07006486void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6487{
6488 port->role = mRole;
6489 port->type = mType;
6490 unsigned int i;
6491 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006492 if (mSamplingRates[i] != 0) {
6493 port->sample_rates[i] = mSamplingRates[i];
6494 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006495 }
6496 port->num_sample_rates = i;
6497 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006498 if (mChannelMasks[i] != 0) {
6499 port->channel_masks[i] = mChannelMasks[i];
6500 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006501 }
6502 port->num_channel_masks = i;
6503 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006504 if (mFormats[i] != 0) {
6505 port->formats[i] = mFormats[i];
6506 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006507 }
6508 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006509
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006510 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006511
6512 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6513 port->gains[i] = mGains[i]->mGain;
6514 }
6515 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006516}
6517
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006518void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6519 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6520 const uint32_t rate = port->mSamplingRates.itemAt(k);
6521 if (rate != 0) { // skip "dynamic" rates
6522 bool hasRate = false;
6523 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6524 if (rate == mSamplingRates.itemAt(l)) {
6525 hasRate = true;
6526 break;
6527 }
6528 }
6529 if (!hasRate) { // never import a sampling rate twice
6530 mSamplingRates.add(rate);
6531 }
6532 }
6533 }
6534 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6535 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6536 if (mask != 0) { // skip "dynamic" masks
6537 bool hasMask = false;
6538 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6539 if (mask == mChannelMasks.itemAt(l)) {
6540 hasMask = true;
6541 break;
6542 }
6543 }
6544 if (!hasMask) { // never import a channel mask twice
6545 mChannelMasks.add(mask);
6546 }
6547 }
6548 }
6549 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6550 const audio_format_t format = port->mFormats.itemAt(k);
6551 if (format != 0) { // skip "dynamic" formats
6552 bool hasFormat = false;
6553 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6554 if (format == mFormats.itemAt(l)) {
6555 hasFormat = true;
6556 break;
6557 }
6558 }
6559 if (!hasFormat) { // never import a channel mask twice
6560 mFormats.add(format);
6561 }
6562 }
6563 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006564 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6565 sp<AudioGain> gain = port->mGains.itemAt(k);
6566 if (gain != 0) {
6567 bool hasGain = false;
6568 for (size_t l = 0 ; l < mGains.size() ; l++) {
6569 if (gain == mGains.itemAt(l)) {
6570 hasGain = true;
6571 break;
6572 }
6573 }
6574 if (!hasGain) { // never import a gain twice
6575 mGains.add(gain);
6576 }
6577 }
6578 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006579}
6580
6581void AudioPolicyManager::AudioPort::clearCapabilities() {
6582 mChannelMasks.clear();
6583 mFormats.clear();
6584 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006585 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006586}
Eric Laurent1c333e22014-05-20 10:48:17 -07006587
6588void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6589{
6590 char *str = strtok(name, "|");
6591
6592 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6593 // rates should be read from the output stream after it is opened for the first time
6594 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6595 mSamplingRates.add(0);
6596 return;
6597 }
6598
6599 while (str != NULL) {
6600 uint32_t rate = atoi(str);
6601 if (rate != 0) {
6602 ALOGV("loadSamplingRates() adding rate %d", rate);
6603 mSamplingRates.add(rate);
6604 }
6605 str = strtok(NULL, "|");
6606 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006607}
6608
6609void AudioPolicyManager::AudioPort::loadFormats(char *name)
6610{
6611 char *str = strtok(name, "|");
6612
6613 // by convention, "0' in the first entry in mFormats indicates the supported formats
6614 // should be read from the output stream after it is opened for the first time
6615 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6616 mFormats.add(AUDIO_FORMAT_DEFAULT);
6617 return;
6618 }
6619
6620 while (str != NULL) {
6621 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6622 ARRAY_SIZE(sFormatNameToEnumTable),
6623 str);
6624 if (format != AUDIO_FORMAT_DEFAULT) {
6625 mFormats.add(format);
6626 }
6627 str = strtok(NULL, "|");
6628 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006629}
6630
6631void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6632{
6633 const char *str = strtok(name, "|");
6634
6635 ALOGV("loadInChannels() %s", name);
6636
6637 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6638 mChannelMasks.add(0);
6639 return;
6640 }
6641
6642 while (str != NULL) {
6643 audio_channel_mask_t channelMask =
6644 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6645 ARRAY_SIZE(sInChannelsNameToEnumTable),
6646 str);
6647 if (channelMask != 0) {
6648 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6649 mChannelMasks.add(channelMask);
6650 }
6651 str = strtok(NULL, "|");
6652 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006653}
6654
6655void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6656{
6657 const char *str = strtok(name, "|");
6658
6659 ALOGV("loadOutChannels() %s", name);
6660
6661 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6662 // masks should be read from the output stream after it is opened for the first time
6663 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6664 mChannelMasks.add(0);
6665 return;
6666 }
6667
6668 while (str != NULL) {
6669 audio_channel_mask_t channelMask =
6670 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6671 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6672 str);
6673 if (channelMask != 0) {
6674 mChannelMasks.add(channelMask);
6675 }
6676 str = strtok(NULL, "|");
6677 }
6678 return;
6679}
6680
Eric Laurent1afeecb2014-05-14 08:52:28 -07006681audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6682{
6683 const char *str = strtok(name, "|");
6684
6685 ALOGV("loadGainMode() %s", name);
6686 audio_gain_mode_t mode = 0;
6687 while (str != NULL) {
6688 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6689 ARRAY_SIZE(sGainModeNameToEnumTable),
6690 str);
6691 str = strtok(NULL, "|");
6692 }
6693 return mode;
6694}
6695
Eric Laurenta121f902014-06-03 13:32:54 -07006696void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006697{
6698 cnode *node = root->first_child;
6699
Eric Laurenta121f902014-06-03 13:32:54 -07006700 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006701
6702 while (node) {
6703 if (strcmp(node->name, GAIN_MODE) == 0) {
6704 gain->mGain.mode = loadGainMode((char *)node->value);
6705 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006706 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006707 gain->mGain.channel_mask =
6708 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6709 ARRAY_SIZE(sInChannelsNameToEnumTable),
6710 (char *)node->value);
6711 } else {
6712 gain->mGain.channel_mask =
6713 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6714 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6715 (char *)node->value);
6716 }
6717 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6718 gain->mGain.min_value = atoi((char *)node->value);
6719 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6720 gain->mGain.max_value = atoi((char *)node->value);
6721 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6722 gain->mGain.default_value = atoi((char *)node->value);
6723 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6724 gain->mGain.step_value = atoi((char *)node->value);
6725 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6726 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6727 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6728 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6729 }
6730 node = node->next;
6731 }
6732
6733 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6734 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6735
6736 if (gain->mGain.mode == 0) {
6737 return;
6738 }
6739 mGains.add(gain);
6740}
6741
6742void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6743{
6744 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006745 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006746 while (node) {
6747 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006748 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006749 node = node->next;
6750 }
6751}
6752
Glenn Kastencbd48022014-07-24 13:46:44 -07006753status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006754{
Eric Laurent0daea392014-12-04 19:14:54 -08006755 if (mSamplingRates.isEmpty()) {
6756 return NO_ERROR;
6757 }
6758
Eric Laurenta121f902014-06-03 13:32:54 -07006759 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6760 if (mSamplingRates[i] == samplingRate) {
6761 return NO_ERROR;
6762 }
6763 }
6764 return BAD_VALUE;
6765}
6766
Glenn Kastencbd48022014-07-24 13:46:44 -07006767status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6768 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006769{
Eric Laurent0daea392014-12-04 19:14:54 -08006770 if (mSamplingRates.isEmpty()) {
6771 return NO_ERROR;
6772 }
6773
Glenn Kastencbd48022014-07-24 13:46:44 -07006774 // Search for the closest supported sampling rate that is above (preferred)
6775 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6776 // The sampling rates do not need to be sorted in ascending order.
6777 ssize_t maxBelow = -1;
6778 ssize_t minAbove = -1;
6779 uint32_t candidate;
6780 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6781 candidate = mSamplingRates[i];
6782 if (candidate == samplingRate) {
6783 if (updatedSamplingRate != NULL) {
6784 *updatedSamplingRate = candidate;
6785 }
6786 return NO_ERROR;
6787 }
6788 // candidate < desired
6789 if (candidate < samplingRate) {
6790 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6791 maxBelow = i;
6792 }
6793 // candidate > desired
6794 } else {
6795 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6796 minAbove = i;
6797 }
6798 }
6799 }
6800 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6801 // TODO Move these assumptions out.
6802 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6803 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6804 // due to approximation by an int32_t of the
6805 // phase increments
6806 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6807 if (minAbove >= 0) {
6808 candidate = mSamplingRates[minAbove];
6809 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6810 if (updatedSamplingRate != NULL) {
6811 *updatedSamplingRate = candidate;
6812 }
6813 return NO_ERROR;
6814 }
6815 }
6816 // But if we have to up-sample from a lower sampling rate, that's OK.
6817 if (maxBelow >= 0) {
6818 candidate = mSamplingRates[maxBelow];
6819 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6820 if (updatedSamplingRate != NULL) {
6821 *updatedSamplingRate = candidate;
6822 }
6823 return NO_ERROR;
6824 }
6825 }
6826 // leave updatedSamplingRate unmodified
6827 return BAD_VALUE;
6828}
6829
6830status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6831{
Eric Laurent0daea392014-12-04 19:14:54 -08006832 if (mChannelMasks.isEmpty()) {
6833 return NO_ERROR;
6834 }
6835
Glenn Kastencbd48022014-07-24 13:46:44 -07006836 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006837 if (mChannelMasks[i] == channelMask) {
6838 return NO_ERROR;
6839 }
6840 }
6841 return BAD_VALUE;
6842}
6843
Glenn Kastencbd48022014-07-24 13:46:44 -07006844status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6845 const
6846{
Eric Laurent0daea392014-12-04 19:14:54 -08006847 if (mChannelMasks.isEmpty()) {
6848 return NO_ERROR;
6849 }
6850
Glenn Kastencbd48022014-07-24 13:46:44 -07006851 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6852 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6853 // FIXME Does not handle multi-channel automatic conversions yet
6854 audio_channel_mask_t supported = mChannelMasks[i];
6855 if (supported == channelMask) {
6856 return NO_ERROR;
6857 }
6858 if (isRecordThread) {
6859 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6860 // FIXME Abstract this out to a table.
6861 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6862 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6863 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6864 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6865 return NO_ERROR;
6866 }
6867 }
6868 }
6869 return BAD_VALUE;
6870}
6871
Eric Laurenta121f902014-06-03 13:32:54 -07006872status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6873{
Eric Laurent0daea392014-12-04 19:14:54 -08006874 if (mFormats.isEmpty()) {
6875 return NO_ERROR;
6876 }
6877
Eric Laurenta121f902014-06-03 13:32:54 -07006878 for (size_t i = 0; i < mFormats.size(); i ++) {
6879 if (mFormats[i] == format) {
6880 return NO_ERROR;
6881 }
6882 }
6883 return BAD_VALUE;
6884}
6885
Eric Laurent1e693b52014-07-09 15:03:28 -07006886
6887uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6888{
6889 // special case for uninitialized dynamic profile
6890 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6891 return 0;
6892 }
6893
Eric Laurent828bcff2014-09-07 12:26:06 -07006894 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6895 // channel count / sampling rate combination chosen will be supported by the connected
6896 // sink
6897 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6898 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6899 uint32_t samplingRate = UINT_MAX;
6900 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6901 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6902 samplingRate = mSamplingRates[i];
6903 }
6904 }
6905 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6906 }
6907
Eric Laurent1e693b52014-07-09 15:03:28 -07006908 uint32_t samplingRate = 0;
6909 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6910
6911 // For mixed output and inputs, use max mixer sampling rates. Do not
6912 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006913 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006914 maxRate = UINT_MAX;
6915 }
6916 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6917 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6918 samplingRate = mSamplingRates[i];
6919 }
6920 }
6921 return samplingRate;
6922}
6923
6924audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6925{
6926 // special case for uninitialized dynamic profile
6927 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6928 return AUDIO_CHANNEL_NONE;
6929 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006930 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006931
6932 // For direct outputs, pick minimum channel count: this helps ensuring that the
6933 // channel count / sampling rate combination chosen will be supported by the connected
6934 // sink
6935 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6936 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6937 uint32_t channelCount = UINT_MAX;
6938 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6939 uint32_t cnlCount;
6940 if (mUseInChannelMask) {
6941 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6942 } else {
6943 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6944 }
6945 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6946 channelMask = mChannelMasks[i];
6947 channelCount = cnlCount;
6948 }
6949 }
6950 return channelMask;
6951 }
6952
Eric Laurent1e693b52014-07-09 15:03:28 -07006953 uint32_t channelCount = 0;
6954 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6955
6956 // For mixed output and inputs, use max mixer channel count. Do not
6957 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006958 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006959 maxCount = UINT_MAX;
6960 }
6961 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6962 uint32_t cnlCount;
6963 if (mUseInChannelMask) {
6964 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6965 } else {
6966 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6967 }
6968 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6969 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006970 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006971 }
6972 }
6973 return channelMask;
6974}
6975
Andy Hung9a605382014-07-28 16:16:31 -07006976/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006977const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6978 AUDIO_FORMAT_DEFAULT,
6979 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006980 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006981 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006982 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006983 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006984};
6985
6986int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6987 audio_format_t format2)
6988{
6989 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6990 // compressed format and better than any PCM format. This is by design of pickFormat()
6991 if (!audio_is_linear_pcm(format1)) {
6992 if (!audio_is_linear_pcm(format2)) {
6993 return 0;
6994 }
6995 return 1;
6996 }
6997 if (!audio_is_linear_pcm(format2)) {
6998 return -1;
6999 }
7000
7001 int index1 = -1, index2 = -1;
7002 for (size_t i = 0;
7003 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
7004 i ++) {
7005 if (sPcmFormatCompareTable[i] == format1) {
7006 index1 = i;
7007 }
7008 if (sPcmFormatCompareTable[i] == format2) {
7009 index2 = i;
7010 }
7011 }
7012 // format1 not found => index1 < 0 => format2 > format1
7013 // format2 not found => index2 < 0 => format2 < format1
7014 return index1 - index2;
7015}
7016
7017audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
7018{
7019 // special case for uninitialized dynamic profile
7020 if (mFormats.size() == 1 && mFormats[0] == 0) {
7021 return AUDIO_FORMAT_DEFAULT;
7022 }
7023
7024 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07007025 audio_format_t bestFormat =
7026 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
7027 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07007028 // For mixed output and inputs, use best mixer output format. Do not
7029 // limit format otherwise
7030 if ((mType != AUDIO_PORT_TYPE_MIX) ||
7031 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07007032 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007033 bestFormat = AUDIO_FORMAT_INVALID;
7034 }
7035
7036 for (size_t i = 0; i < mFormats.size(); i ++) {
7037 if ((compareFormats(mFormats[i], format) > 0) &&
7038 (compareFormats(mFormats[i], bestFormat) <= 0)) {
7039 format = mFormats[i];
7040 }
7041 }
7042 return format;
7043}
7044
Eric Laurenta121f902014-06-03 13:32:54 -07007045status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
7046 int index) const
7047{
7048 if (index < 0 || (size_t)index >= mGains.size()) {
7049 return BAD_VALUE;
7050 }
7051 return mGains[index]->checkConfig(gainConfig);
7052}
7053
Eric Laurent1afeecb2014-05-14 08:52:28 -07007054void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
7055{
7056 const size_t SIZE = 256;
7057 char buffer[SIZE];
7058 String8 result;
7059
7060 if (mName.size() != 0) {
7061 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
7062 result.append(buffer);
7063 }
7064
7065 if (mSamplingRates.size() != 0) {
7066 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
7067 result.append(buffer);
7068 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007069 if (i == 0 && mSamplingRates[i] == 0) {
7070 snprintf(buffer, SIZE, "Dynamic");
7071 } else {
7072 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7073 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007074 result.append(buffer);
7075 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7076 }
7077 result.append("\n");
7078 }
7079
7080 if (mChannelMasks.size() != 0) {
7081 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7082 result.append(buffer);
7083 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007084 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7085
7086 if (i == 0 && mChannelMasks[i] == 0) {
7087 snprintf(buffer, SIZE, "Dynamic");
7088 } else {
7089 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7090 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007091 result.append(buffer);
7092 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7093 }
7094 result.append("\n");
7095 }
7096
7097 if (mFormats.size() != 0) {
7098 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7099 result.append(buffer);
7100 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007101 const char *formatStr = enumToString(sFormatNameToEnumTable,
7102 ARRAY_SIZE(sFormatNameToEnumTable),
7103 mFormats[i]);
7104 if (i == 0 && strcmp(formatStr, "") == 0) {
7105 snprintf(buffer, SIZE, "Dynamic");
7106 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07007107 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07007108 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007109 result.append(buffer);
7110 result.append(i == (mFormats.size() - 1) ? "" : ", ");
7111 }
7112 result.append("\n");
7113 }
7114 write(fd, result.string(), result.size());
7115 if (mGains.size() != 0) {
7116 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7117 write(fd, buffer, strlen(buffer) + 1);
7118 result.append(buffer);
7119 for (size_t i = 0; i < mGains.size(); i++) {
7120 mGains[i]->dump(fd, spaces + 2, i);
7121 }
7122 }
7123}
7124
7125// --- AudioGain class implementation
7126
Eric Laurenta121f902014-06-03 13:32:54 -07007127AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07007128{
Eric Laurenta121f902014-06-03 13:32:54 -07007129 mIndex = index;
7130 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007131 memset(&mGain, 0, sizeof(struct audio_gain));
7132}
7133
Eric Laurenta121f902014-06-03 13:32:54 -07007134void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7135{
7136 config->index = mIndex;
7137 config->mode = mGain.mode;
7138 config->channel_mask = mGain.channel_mask;
7139 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7140 config->values[0] = mGain.default_value;
7141 } else {
7142 uint32_t numValues;
7143 if (mUseInChannelMask) {
7144 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7145 } else {
7146 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7147 }
7148 for (size_t i = 0; i < numValues; i++) {
7149 config->values[i] = mGain.default_value;
7150 }
7151 }
7152 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7153 config->ramp_duration_ms = mGain.min_ramp_ms;
7154 }
7155}
7156
7157status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7158{
7159 if ((config->mode & ~mGain.mode) != 0) {
7160 return BAD_VALUE;
7161 }
7162 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7163 if ((config->values[0] < mGain.min_value) ||
7164 (config->values[0] > mGain.max_value)) {
7165 return BAD_VALUE;
7166 }
7167 } else {
7168 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7169 return BAD_VALUE;
7170 }
7171 uint32_t numValues;
7172 if (mUseInChannelMask) {
7173 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7174 } else {
7175 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7176 }
7177 for (size_t i = 0; i < numValues; i++) {
7178 if ((config->values[i] < mGain.min_value) ||
7179 (config->values[i] > mGain.max_value)) {
7180 return BAD_VALUE;
7181 }
7182 }
7183 }
7184 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7185 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7186 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7187 return BAD_VALUE;
7188 }
7189 }
7190 return NO_ERROR;
7191}
7192
Eric Laurent1afeecb2014-05-14 08:52:28 -07007193void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7194{
7195 const size_t SIZE = 256;
7196 char buffer[SIZE];
7197 String8 result;
7198
7199 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7200 result.append(buffer);
7201 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7202 result.append(buffer);
7203 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7204 result.append(buffer);
7205 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7206 result.append(buffer);
7207 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7208 result.append(buffer);
7209 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7210 result.append(buffer);
7211 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7212 result.append(buffer);
7213 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7214 result.append(buffer);
7215 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7216 result.append(buffer);
7217
7218 write(fd, result.string(), result.size());
7219}
7220
Eric Laurent1f2f2232014-06-02 12:01:23 -07007221// --- AudioPortConfig class implementation
7222
7223AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7224{
7225 mSamplingRate = 0;
7226 mChannelMask = AUDIO_CHANNEL_NONE;
7227 mFormat = AUDIO_FORMAT_INVALID;
7228 mGain.index = -1;
7229}
7230
Eric Laurenta121f902014-06-03 13:32:54 -07007231status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7232 const struct audio_port_config *config,
7233 struct audio_port_config *backupConfig)
7234{
7235 struct audio_port_config localBackupConfig;
7236 status_t status = NO_ERROR;
7237
7238 localBackupConfig.config_mask = config->config_mask;
7239 toAudioPortConfig(&localBackupConfig);
7240
Marco Nelissen961ec212014-08-25 15:58:39 -07007241 sp<AudioPort> audioport = getAudioPort();
7242 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007243 status = NO_INIT;
7244 goto exit;
7245 }
7246 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007247 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007248 if (status != NO_ERROR) {
7249 goto exit;
7250 }
7251 mSamplingRate = config->sample_rate;
7252 }
7253 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007254 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007255 if (status != NO_ERROR) {
7256 goto exit;
7257 }
7258 mChannelMask = config->channel_mask;
7259 }
7260 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007261 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007262 if (status != NO_ERROR) {
7263 goto exit;
7264 }
7265 mFormat = config->format;
7266 }
7267 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007268 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007269 if (status != NO_ERROR) {
7270 goto exit;
7271 }
7272 mGain = config->gain;
7273 }
7274
7275exit:
7276 if (status != NO_ERROR) {
7277 applyAudioPortConfig(&localBackupConfig);
7278 }
7279 if (backupConfig != NULL) {
7280 *backupConfig = localBackupConfig;
7281 }
7282 return status;
7283}
7284
Eric Laurent1f2f2232014-06-02 12:01:23 -07007285void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7286 struct audio_port_config *dstConfig,
7287 const struct audio_port_config *srcConfig) const
7288{
7289 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7290 dstConfig->sample_rate = mSamplingRate;
7291 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7292 dstConfig->sample_rate = srcConfig->sample_rate;
7293 }
7294 } else {
7295 dstConfig->sample_rate = 0;
7296 }
7297 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7298 dstConfig->channel_mask = mChannelMask;
7299 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7300 dstConfig->channel_mask = srcConfig->channel_mask;
7301 }
7302 } else {
7303 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7304 }
7305 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7306 dstConfig->format = mFormat;
7307 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7308 dstConfig->format = srcConfig->format;
7309 }
7310 } else {
7311 dstConfig->format = AUDIO_FORMAT_INVALID;
7312 }
7313 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7314 dstConfig->gain = mGain;
7315 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7316 dstConfig->gain = srcConfig->gain;
7317 }
7318 } else {
7319 dstConfig->gain.index = -1;
7320 }
7321 if (dstConfig->gain.index != -1) {
7322 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7323 } else {
7324 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7325 }
7326}
7327
Eric Laurent1c333e22014-05-20 10:48:17 -07007328// --- IOProfile class implementation
7329
Eric Laurent1afeecb2014-05-14 08:52:28 -07007330AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007331 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007332 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007333{
7334}
7335
Eric Laurente0720872014-03-11 09:30:41 -07007336AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007337{
7338}
7339
7340// checks if the IO profile is compatible with specified parameters.
7341// Sampling rate, format and channel mask must be specified in order to
7342// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007343bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007344 String8 address,
7345 uint32_t samplingRate,
7346 uint32_t *updatedSamplingRate,
7347 audio_format_t format,
7348 audio_channel_mask_t channelMask,
7349 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007350{
Glenn Kastencbd48022014-07-24 13:46:44 -07007351 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7352 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7353 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007354
Eric Laurent275e8e92014-11-30 15:14:47 -08007355 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007356 return false;
7357 }
7358
7359 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007360 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007361 }
7362 uint32_t myUpdatedSamplingRate = samplingRate;
7363 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007364 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007365 }
7366 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7367 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007368 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007369 }
7370
7371 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7372 return false;
7373 }
7374
7375 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7376 checkExactChannelMask(channelMask) != NO_ERROR)) {
7377 return false;
7378 }
7379 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7380 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7381 return false;
7382 }
7383
7384 if (isPlaybackThread && (mFlags & flags) != flags) {
7385 return false;
7386 }
7387 // The only input flag that is allowed to be different is the fast flag.
7388 // An existing fast stream is compatible with a normal track request.
7389 // An existing normal stream is compatible with a fast track request,
7390 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007391 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007392 ~AUDIO_INPUT_FLAG_FAST)) {
7393 return false;
7394 }
7395
7396 if (updatedSamplingRate != NULL) {
7397 *updatedSamplingRate = myUpdatedSamplingRate;
7398 }
7399 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007400}
7401
Eric Laurente0720872014-03-11 09:30:41 -07007402void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007403{
7404 const size_t SIZE = 256;
7405 char buffer[SIZE];
7406 String8 result;
7407
Eric Laurent1afeecb2014-05-14 08:52:28 -07007408 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007409
Eric Laurente552edb2014-03-10 17:42:56 -07007410 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7411 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007412 snprintf(buffer, SIZE, " - devices:\n");
7413 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007414 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007415 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7416 mSupportedDevices[i]->dump(fd, 6, i);
7417 }
Eric Laurente552edb2014-03-10 17:42:56 -07007418}
7419
Eric Laurentd4692962014-05-05 18:13:44 -07007420void AudioPolicyManager::IOProfile::log()
7421{
7422 const size_t SIZE = 256;
7423 char buffer[SIZE];
7424 String8 result;
7425
7426 ALOGV(" - sampling rates: ");
7427 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7428 ALOGV(" %d", mSamplingRates[i]);
7429 }
7430
7431 ALOGV(" - channel masks: ");
7432 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7433 ALOGV(" 0x%04x", mChannelMasks[i]);
7434 }
7435
7436 ALOGV(" - formats: ");
7437 for (size_t i = 0; i < mFormats.size(); i++) {
7438 ALOGV(" 0x%08x", mFormats[i]);
7439 }
7440
7441 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7442 ALOGV(" - flags: 0x%04x\n", mFlags);
7443}
7444
7445
Eric Laurent3a4311c2014-03-17 12:00:47 -07007446// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007447
Eric Laurent1f2f2232014-06-02 12:01:23 -07007448
7449AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7450 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7451 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7452 AUDIO_PORT_ROLE_SOURCE,
7453 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007454 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007455{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007456}
7457
Eric Laurent3a4311c2014-03-17 12:00:47 -07007458bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007459{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007460 // Devices are considered equal if they:
7461 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7462 // - have the same address or one device does not specify the address
7463 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007464 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007465 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007466 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007467 mChannelMask == other->mChannelMask);
7468}
7469
Eric Laurent1db89b92015-01-27 18:21:09 -08007470void AudioPolicyManager::DeviceDescriptor::loadGains(cnode *root)
7471{
7472 AudioPort::loadGains(root);
7473 if (mGains.size() > 0) {
7474 mGains[0]->getDefaultConfig(&mGain);
7475 }
7476}
7477
7478
Eric Laurent3a4311c2014-03-17 12:00:47 -07007479void AudioPolicyManager::DeviceVector::refreshTypes()
7480{
Eric Laurent1c333e22014-05-20 10:48:17 -07007481 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007482 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007483 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007484 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007485 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007486}
7487
7488ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7489{
7490 for(size_t i = 0; i < size(); i++) {
7491 if (item->equals(itemAt(i))) {
7492 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007493 }
7494 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007495 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007496}
7497
Eric Laurent3a4311c2014-03-17 12:00:47 -07007498ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007499{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007500 ssize_t ret = indexOf(item);
7501
7502 if (ret < 0) {
7503 ret = SortedVector::add(item);
7504 if (ret >= 0) {
7505 refreshTypes();
7506 }
7507 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007508 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007509 ret = -1;
7510 }
7511 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007512}
7513
Eric Laurent3a4311c2014-03-17 12:00:47 -07007514ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7515{
7516 size_t i;
7517 ssize_t ret = indexOf(item);
7518
7519 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007520 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007521 } else {
7522 ret = SortedVector::removeAt(ret);
7523 if (ret >= 0) {
7524 refreshTypes();
7525 }
7526 }
7527 return ret;
7528}
7529
7530void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7531{
7532 DeviceVector deviceList;
7533
7534 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7535 types &= ~role_bit;
7536
7537 while (types) {
7538 uint32_t i = 31 - __builtin_clz(types);
7539 uint32_t type = 1 << i;
7540 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007541 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007542 }
7543}
7544
Eric Laurent1afeecb2014-05-14 08:52:28 -07007545void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7546 const DeviceVector& declaredDevices)
7547{
7548 char *devName = strtok(name, "|");
7549 while (devName != NULL) {
7550 if (strlen(devName) != 0) {
7551 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7552 ARRAY_SIZE(sDeviceNameToEnumTable),
7553 devName);
7554 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007555 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007556 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7557 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007558 dev->mAddress = String8("0");
7559 }
7560 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007561 } else {
7562 sp<DeviceDescriptor> deviceDesc =
7563 declaredDevices.getDeviceFromName(String8(devName));
7564 if (deviceDesc != 0) {
7565 add(deviceDesc);
7566 }
7567 }
7568 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007569 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007570 }
7571}
7572
Eric Laurent1c333e22014-05-20 10:48:17 -07007573sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7574 audio_devices_t type, String8 address) const
7575{
7576 sp<DeviceDescriptor> device;
7577 for (size_t i = 0; i < size(); i++) {
7578 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007579 if (address == "" || itemAt(i)->mAddress == address) {
7580 device = itemAt(i);
7581 if (itemAt(i)->mAddress == address) {
7582 break;
7583 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007584 }
7585 }
7586 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007587 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007588 type, address.string(), device.get());
7589 return device;
7590}
7591
Eric Laurent6a94d692014-05-20 11:18:06 -07007592sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7593 audio_port_handle_t id) const
7594{
7595 sp<DeviceDescriptor> device;
7596 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007597 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007598 if (itemAt(i)->mId == id) {
7599 device = itemAt(i);
7600 break;
7601 }
7602 }
7603 return device;
7604}
7605
Eric Laurent1c333e22014-05-20 10:48:17 -07007606AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7607 audio_devices_t type) const
7608{
7609 DeviceVector devices;
7610 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7611 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7612 devices.add(itemAt(i));
7613 type &= ~itemAt(i)->mDeviceType;
7614 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7615 itemAt(i)->mDeviceType, itemAt(i).get());
7616 }
7617 }
7618 return devices;
7619}
7620
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007621AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7622 audio_devices_t type, String8 address) const
7623{
7624 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007625 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007626 if (itemAt(i)->mDeviceType == type) {
7627 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007628 devices.add(itemAt(i));
7629 }
7630 }
7631 }
7632 return devices;
7633}
7634
Eric Laurent1afeecb2014-05-14 08:52:28 -07007635sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7636 const String8& name) const
7637{
7638 sp<DeviceDescriptor> device;
7639 for (size_t i = 0; i < size(); i++) {
7640 if (itemAt(i)->mName == name) {
7641 device = itemAt(i);
7642 break;
7643 }
7644 }
7645 return device;
7646}
7647
Eric Laurent6a94d692014-05-20 11:18:06 -07007648void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7649 struct audio_port_config *dstConfig,
7650 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007651{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007652 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7653 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007654 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007655 }
7656
7657 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7658
Eric Laurent6a94d692014-05-20 11:18:06 -07007659 dstConfig->id = mId;
7660 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007661 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007662 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007663 dstConfig->ext.device.type = mDeviceType;
7664 dstConfig->ext.device.hw_module = mModule->mHandle;
7665 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007666}
7667
7668void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7669{
Eric Laurent83b88082014-06-20 18:31:16 -07007670 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007671 AudioPort::toAudioPort(port);
7672 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007673 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007674 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007675 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007676 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7677}
7678
Eric Laurent1afeecb2014-05-14 08:52:28 -07007679status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007680{
7681 const size_t SIZE = 256;
7682 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007683 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007684
Eric Laurent1afeecb2014-05-14 08:52:28 -07007685 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7686 result.append(buffer);
7687 if (mId != 0) {
7688 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7689 result.append(buffer);
7690 }
7691 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7692 enumToString(sDeviceNameToEnumTable,
7693 ARRAY_SIZE(sDeviceNameToEnumTable),
7694 mDeviceType));
7695 result.append(buffer);
7696 if (mAddress.size() != 0) {
7697 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7698 result.append(buffer);
7699 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007700 write(fd, result.string(), result.size());
7701 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007702
7703 return NO_ERROR;
7704}
7705
Eric Laurent4d416952014-08-10 14:07:09 -07007706status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7707{
7708 const size_t SIZE = 256;
7709 char buffer[SIZE];
7710 String8 result;
7711
7712
7713 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7714 result.append(buffer);
7715 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7716 result.append(buffer);
7717 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7718 result.append(buffer);
7719 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7720 result.append(buffer);
7721 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7722 result.append(buffer);
7723 for (size_t i = 0; i < mPatch.num_sources; i++) {
7724 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7725 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7726 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7727 ARRAY_SIZE(sDeviceNameToEnumTable),
7728 mPatch.sources[i].ext.device.type));
7729 } else {
7730 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7731 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7732 }
7733 result.append(buffer);
7734 }
7735 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7736 result.append(buffer);
7737 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7738 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7739 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7740 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7741 ARRAY_SIZE(sDeviceNameToEnumTable),
7742 mPatch.sinks[i].ext.device.type));
7743 } else {
7744 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7745 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7746 }
7747 result.append(buffer);
7748 }
7749
7750 write(fd, result.string(), result.size());
7751 return NO_ERROR;
7752}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007753
7754// --- audio_policy.conf file parsing
7755
Eric Laurent5dbe4712014-09-19 19:04:57 -07007756uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007757{
7758 uint32_t flag = 0;
7759
7760 // it is OK to cast name to non const here as we are not going to use it after
7761 // strtok() modifies it
7762 char *flagName = strtok(name, "|");
7763 while (flagName != NULL) {
7764 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007765 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7766 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007767 flagName);
7768 }
7769 flagName = strtok(NULL, "|");
7770 }
7771 //force direct flag if offload flag is set: offloading implies a direct output stream
7772 // and all common behaviors are driven by checking only the direct flag
7773 // this should normally be set appropriately in the policy configuration file
7774 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7775 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7776 }
7777
Eric Laurent5dbe4712014-09-19 19:04:57 -07007778 return flag;
7779}
7780
7781uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7782{
7783 uint32_t flag = 0;
7784
7785 // it is OK to cast name to non const here as we are not going to use it after
7786 // strtok() modifies it
7787 char *flagName = strtok(name, "|");
7788 while (flagName != NULL) {
7789 if (strlen(flagName) != 0) {
7790 flag |= stringToEnum(sInputFlagNameToEnumTable,
7791 ARRAY_SIZE(sInputFlagNameToEnumTable),
7792 flagName);
7793 }
7794 flagName = strtok(NULL, "|");
7795 }
7796 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007797}
7798
Eric Laurente0720872014-03-11 09:30:41 -07007799audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007800{
7801 uint32_t device = 0;
7802
7803 char *devName = strtok(name, "|");
7804 while (devName != NULL) {
7805 if (strlen(devName) != 0) {
7806 device |= stringToEnum(sDeviceNameToEnumTable,
7807 ARRAY_SIZE(sDeviceNameToEnumTable),
7808 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007809 }
Eric Laurente552edb2014-03-10 17:42:56 -07007810 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007811 }
Eric Laurente552edb2014-03-10 17:42:56 -07007812 return device;
7813}
7814
Eric Laurente0720872014-03-11 09:30:41 -07007815void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007816{
Eric Laurente552edb2014-03-10 17:42:56 -07007817 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007818 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007819 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007820
Eric Laurent1afeecb2014-05-14 08:52:28 -07007821 node = config_find(root, DEVICES_TAG);
7822 if (node != NULL) {
7823 node = node->first_child;
7824 while (node) {
7825 ALOGV("loadHwModule() loading device %s", node->name);
7826 status_t tmpStatus = module->loadDevice(node);
7827 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7828 status = tmpStatus;
7829 }
7830 node = node->next;
7831 }
7832 }
7833 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007834 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007835 node = node->first_child;
7836 while (node) {
7837 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007838 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007839 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7840 status = tmpStatus;
7841 }
7842 node = node->next;
7843 }
7844 }
7845 node = config_find(root, INPUTS_TAG);
7846 if (node != NULL) {
7847 node = node->first_child;
7848 while (node) {
7849 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007850 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007851 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7852 status = tmpStatus;
7853 }
7854 node = node->next;
7855 }
7856 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007857 loadGlobalConfig(root, module);
7858
Eric Laurente552edb2014-03-10 17:42:56 -07007859 if (status == NO_ERROR) {
7860 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007861 }
7862}
7863
Eric Laurente0720872014-03-11 09:30:41 -07007864void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007865{
7866 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7867 if (node == NULL) {
7868 return;
7869 }
7870
7871 node = node->first_child;
7872 while (node) {
7873 ALOGV("loadHwModules() loading module %s", node->name);
7874 loadHwModule(node);
7875 node = node->next;
7876 }
7877}
7878
Eric Laurent1f2f2232014-06-02 12:01:23 -07007879void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007880{
7881 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007882
Eric Laurente552edb2014-03-10 17:42:56 -07007883 if (node == NULL) {
7884 return;
7885 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007886 DeviceVector declaredDevices;
7887 if (module != NULL) {
7888 declaredDevices = module->mDeclaredDevices;
7889 }
7890
Eric Laurente552edb2014-03-10 17:42:56 -07007891 node = node->first_child;
7892 while (node) {
7893 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007894 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7895 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007896 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7897 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007898 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007899 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007900 ARRAY_SIZE(sDeviceNameToEnumTable),
7901 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007902 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007903 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007904 } else {
7905 ALOGW("loadGlobalConfig() default device not specified");
7906 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007907 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007908 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007909 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7910 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007911 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007912 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7913 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7914 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007915 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7916 uint32_t major, minor;
7917 sscanf((char *)node->value, "%u.%u", &major, &minor);
7918 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7919 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7920 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007921 }
7922 node = node->next;
7923 }
7924}
7925
Eric Laurente0720872014-03-11 09:30:41 -07007926status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007927{
7928 cnode *root;
7929 char *data;
7930
7931 data = (char *)load_file(path, NULL);
7932 if (data == NULL) {
7933 return -ENODEV;
7934 }
7935 root = config_node("", "");
7936 config_load(root, data);
7937
Eric Laurente552edb2014-03-10 17:42:56 -07007938 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007939 // legacy audio_policy.conf files have one global_configuration section
7940 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007941 config_free(root);
7942 free(root);
7943 free(data);
7944
7945 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7946
7947 return NO_ERROR;
7948}
7949
Eric Laurente0720872014-03-11 09:30:41 -07007950void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007951{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007952 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007953 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007954 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7955 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007956 mAvailableOutputDevices.add(mDefaultOutputDevice);
7957 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007958
7959 module = new HwModule("primary");
7960
Eric Laurent1afeecb2014-05-14 08:52:28 -07007961 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007962 profile->mSamplingRates.add(44100);
7963 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7964 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007965 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007966 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7967 module->mOutputProfiles.add(profile);
7968
Eric Laurent1afeecb2014-05-14 08:52:28 -07007969 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007970 profile->mSamplingRates.add(8000);
7971 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7972 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007973 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007974 module->mInputProfiles.add(profile);
7975
7976 mHwModules.add(module);
7977}
7978
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007979audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7980{
7981 // flags to stream type mapping
7982 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7983 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7984 }
7985 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7986 return AUDIO_STREAM_BLUETOOTH_SCO;
7987 }
7988
7989 // usage to stream type mapping
7990 switch (attr->usage) {
7991 case AUDIO_USAGE_MEDIA:
7992 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007993 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7994 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007995 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007996 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7997 return AUDIO_STREAM_ALARM;
7998 }
7999 if (isStreamActive(AUDIO_STREAM_RING)) {
8000 return AUDIO_STREAM_RING;
8001 }
8002 if (isInCall()) {
8003 return AUDIO_STREAM_VOICE_CALL;
8004 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08008005 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008006 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8007 return AUDIO_STREAM_SYSTEM;
8008 case AUDIO_USAGE_VOICE_COMMUNICATION:
8009 return AUDIO_STREAM_VOICE_CALL;
8010
8011 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8012 return AUDIO_STREAM_DTMF;
8013
8014 case AUDIO_USAGE_ALARM:
8015 return AUDIO_STREAM_ALARM;
8016 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8017 return AUDIO_STREAM_RING;
8018
8019 case AUDIO_USAGE_NOTIFICATION:
8020 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8021 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8022 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8023 case AUDIO_USAGE_NOTIFICATION_EVENT:
8024 return AUDIO_STREAM_NOTIFICATION;
8025
8026 case AUDIO_USAGE_UNKNOWN:
8027 default:
8028 return AUDIO_STREAM_MUSIC;
8029 }
8030}
Eric Laurente83b55d2014-11-14 10:06:21 -08008031
8032bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
8033 // has flags that map to a strategy?
8034 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8035 return true;
8036 }
8037
8038 // has known usage?
8039 switch (paa->usage) {
8040 case AUDIO_USAGE_UNKNOWN:
8041 case AUDIO_USAGE_MEDIA:
8042 case AUDIO_USAGE_VOICE_COMMUNICATION:
8043 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8044 case AUDIO_USAGE_ALARM:
8045 case AUDIO_USAGE_NOTIFICATION:
8046 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8047 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8048 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8049 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8050 case AUDIO_USAGE_NOTIFICATION_EVENT:
8051 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8052 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8053 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8054 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008055 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08008056 break;
8057 default:
8058 return false;
8059 }
8060 return true;
8061}
8062
Eric Laurente552edb2014-03-10 17:42:56 -07008063}; // namespace android