blob: 744556d7d74655095ecee258c0c86e1ebdc0ff5a [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 }
599 }
600
601 // store previous phone state for management of sonification strategy below
602 int oldState = mPhoneState;
603 mPhoneState = state;
604 bool force = false;
605
606 // are we entering or starting a call
607 if (!isStateInCall(oldState) && isStateInCall(state)) {
608 ALOGV(" Entering call in setPhoneState()");
609 // force routing command to audio hardware when starting a call
610 // even if no device change is needed
611 force = true;
612 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
613 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
614 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
615 }
616 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
617 ALOGV(" Exiting call in setPhoneState()");
618 // force routing command to audio hardware when exiting a call
619 // even if no device change is needed
620 force = true;
621 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
622 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
623 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
624 }
625 } else if (isStateInCall(state) && (state != oldState)) {
626 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
627 // force routing command to audio hardware when switching between telephony and VoIP
628 // even if no device change is needed
629 force = true;
630 }
631
632 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700633 checkA2dpSuspend();
634 checkOutputForAllStrategies();
635 updateDevicesAndOutputs();
636
Eric Laurent1f2f2232014-06-02 12:01:23 -0700637 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700638
Eric Laurente552edb2014-03-10 17:42:56 -0700639 int delayMs = 0;
640 if (isStateInCall(state)) {
641 nsecs_t sysTime = systemTime();
642 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700643 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700644 // mute media and sonification strategies and delay device switch by the largest
645 // latency of any output where either strategy is active.
646 // This avoid sending the ring tone or music tail into the earpiece or headset.
647 if ((desc->isStrategyActive(STRATEGY_MEDIA,
648 SONIFICATION_HEADSET_MUSIC_DELAY,
649 sysTime) ||
650 desc->isStrategyActive(STRATEGY_SONIFICATION,
651 SONIFICATION_HEADSET_MUSIC_DELAY,
652 sysTime)) &&
653 (delayMs < (int)desc->mLatency*2)) {
654 delayMs = desc->mLatency*2;
655 }
656 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
657 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
658 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
659 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
660 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
661 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
662 }
663 }
664
Eric Laurentc2730ba2014-07-20 15:47:07 -0700665 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
666 // the device returned is not necessarily reachable via this output
667 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
668 // force routing command to audio hardware when ending call
669 // even if no device change is needed
670 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
671 rxDevice = hwOutputDesc->device();
672 }
Eric Laurente552edb2014-03-10 17:42:56 -0700673
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674 if (state == AUDIO_MODE_IN_CALL) {
675 updateCallRouting(rxDevice, delayMs);
676 } else if (oldState == AUDIO_MODE_IN_CALL) {
677 if (mCallRxPatch != 0) {
678 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
679 mCallRxPatch.clear();
680 }
681 if (mCallTxPatch != 0) {
682 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
683 mCallTxPatch.clear();
684 }
685 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
686 } else {
687 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
688 }
Eric Laurente552edb2014-03-10 17:42:56 -0700689 // if entering in call state, handle special case of active streams
690 // pertaining to sonification strategy see handleIncallSonification()
691 if (isStateInCall(state)) {
692 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700693 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800694 if (stream == AUDIO_STREAM_PATCH) {
695 continue;
696 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700697 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700698 }
699 }
700
701 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700702 if (state == AUDIO_MODE_RINGTONE &&
703 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700704 mLimitRingtoneVolume = true;
705 } else {
706 mLimitRingtoneVolume = false;
707 }
708}
709
Eric Laurente0720872014-03-11 09:30:41 -0700710void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700711 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700712{
713 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
714
715 bool forceVolumeReeval = false;
716 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700717 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
718 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
719 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700720 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
721 return;
722 }
723 forceVolumeReeval = true;
724 mForceUse[usage] = config;
725 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700726 case AUDIO_POLICY_FORCE_FOR_MEDIA:
727 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
728 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
729 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
730 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800731 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700732 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
733 return;
734 }
735 mForceUse[usage] = config;
736 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700737 case AUDIO_POLICY_FORCE_FOR_RECORD:
738 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
739 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700740 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
741 return;
742 }
743 mForceUse[usage] = config;
744 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700745 case AUDIO_POLICY_FORCE_FOR_DOCK:
746 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
747 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
748 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
749 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
750 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700751 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
752 }
753 forceVolumeReeval = true;
754 mForceUse[usage] = config;
755 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700756 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
757 if (config != AUDIO_POLICY_FORCE_NONE &&
758 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700759 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
760 }
761 forceVolumeReeval = true;
762 mForceUse[usage] = config;
763 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900764 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
765 if (config != AUDIO_POLICY_FORCE_NONE &&
766 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
767 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
768 }
769 mForceUse[usage] = config;
770 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700771 default:
772 ALOGW("setForceUse() invalid usage %d", usage);
773 break;
774 }
775
776 // check for device and output changes triggered by new force usage
777 checkA2dpSuspend();
778 checkOutputForAllStrategies();
779 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700780 if (mPhoneState == AUDIO_MODE_IN_CALL) {
781 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
782 updateCallRouting(newDevice);
783 }
Eric Laurente552edb2014-03-10 17:42:56 -0700784 for (size_t i = 0; i < mOutputs.size(); i++) {
785 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700786 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700787 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
788 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
789 }
Eric Laurente552edb2014-03-10 17:42:56 -0700790 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
791 applyStreamVolumes(output, newDevice, 0, true);
792 }
793 }
794
795 audio_io_handle_t activeInput = getActiveInput();
796 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700797 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700798 }
799
800}
801
Eric Laurente0720872014-03-11 09:30:41 -0700802audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700803{
804 return mForceUse[usage];
805}
806
Eric Laurente0720872014-03-11 09:30:41 -0700807void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700808{
809 ALOGV("setSystemProperty() property %s, value %s", property, value);
810}
811
812// Find a direct output profile compatible with the parameters passed, even if the input flags do
813// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700814sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700815 audio_devices_t device,
816 uint32_t samplingRate,
817 audio_format_t format,
818 audio_channel_mask_t channelMask,
819 audio_output_flags_t flags)
820{
821 for (size_t i = 0; i < mHwModules.size(); i++) {
822 if (mHwModules[i]->mHandle == 0) {
823 continue;
824 }
825 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700826 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent275e8e92014-11-30 15:14:47 -0800827 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -0700828 NULL /*updatedSamplingRate*/, format, channelMask,
829 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
830 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700831 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
832 return profile;
833 }
Eric Laurente552edb2014-03-10 17:42:56 -0700834 }
835 }
836 return 0;
837}
838
Eric Laurente0720872014-03-11 09:30:41 -0700839audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700840 uint32_t samplingRate,
841 audio_format_t format,
842 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700843 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700844 const audio_offload_info_t *offloadInfo)
845{
Eric Laurent3b73df72014-03-11 09:06:29 -0700846 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700847 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
848 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
849 device, stream, samplingRate, format, channelMask, flags);
850
Eric Laurente83b55d2014-11-14 10:06:21 -0800851 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
852 stream, samplingRate,format, channelMask,
853 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700854}
855
Eric Laurente83b55d2014-11-14 10:06:21 -0800856status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
857 audio_io_handle_t *output,
858 audio_session_t session,
859 audio_stream_type_t *stream,
860 uint32_t samplingRate,
861 audio_format_t format,
862 audio_channel_mask_t channelMask,
863 audio_output_flags_t flags,
864 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700865{
Eric Laurente83b55d2014-11-14 10:06:21 -0800866 audio_attributes_t attributes;
867 if (attr != NULL) {
868 if (!isValidAttributes(attr)) {
869 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
870 attr->usage, attr->content_type, attr->flags,
871 attr->tags);
872 return BAD_VALUE;
873 }
874 attributes = *attr;
875 } else {
876 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
877 ALOGE("getOutputForAttr(): invalid stream type");
878 return BAD_VALUE;
879 }
880 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700881 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800882
Eric Laurent275e8e92014-11-30 15:14:47 -0800883 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
884 sp<AudioOutputDescriptor> desc;
885 if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) {
886 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
887 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
888 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) ||
889 (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
890 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) {
891 desc = mPolicyMixes[i]->mOutput;
892 break;
893 }
894 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
895 strncmp(attributes.tags + strlen("addr="),
896 mPolicyMixes[i]->mMix.mRegistrationId.string(),
897 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
898 desc = mPolicyMixes[i]->mOutput;
899 break;
900 }
901 }
902 } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) {
903 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE &&
904 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
905 strncmp(attributes.tags + strlen("addr="),
906 mPolicyMixes[i]->mMix.mRegistrationId.string(),
907 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
908 desc = mPolicyMixes[i]->mOutput;
Eric Laurent275e8e92014-11-30 15:14:47 -0800909 }
910 }
911 if (desc != 0) {
912 if (!audio_is_linear_pcm(format)) {
913 return BAD_VALUE;
914 }
Eric Laurentc722f302014-12-10 11:21:49 -0800915 desc->mPolicyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -0800916 *stream = streamTypefromAttributesInt(&attributes);
917 *output = desc->mIoHandle;
918 ALOGV("getOutputForAttr() returns output %d", *output);
919 return NO_ERROR;
920 }
921 }
922 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
923 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
924 return BAD_VALUE;
925 }
926
Eric Laurent93c3d412014-08-01 14:48:35 -0700927 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800928 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700929
Eric Laurente83b55d2014-11-14 10:06:21 -0800930 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700931 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700932
Eric Laurente83b55d2014-11-14 10:06:21 -0800933 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700934 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
935 }
936
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700937 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700938 device, samplingRate, format, channelMask, flags);
939
Eric Laurente83b55d2014-11-14 10:06:21 -0800940 *stream = streamTypefromAttributesInt(&attributes);
941 *output = getOutputForDevice(device, session, *stream,
942 samplingRate, format, channelMask,
943 flags, offloadInfo);
944 if (*output == AUDIO_IO_HANDLE_NONE) {
945 return INVALID_OPERATION;
946 }
947 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700948}
949
950audio_io_handle_t AudioPolicyManager::getOutputForDevice(
951 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800952 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700953 audio_stream_type_t stream,
954 uint32_t samplingRate,
955 audio_format_t format,
956 audio_channel_mask_t channelMask,
957 audio_output_flags_t flags,
958 const audio_offload_info_t *offloadInfo)
959{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700960 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700961 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700962 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700963
Eric Laurente552edb2014-03-10 17:42:56 -0700964#ifdef AUDIO_POLICY_TEST
965 if (mCurOutput != 0) {
966 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
967 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
968
969 if (mTestOutputs[mCurOutput] == 0) {
970 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700971 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700972 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700973 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700974 outputDesc->mFlags =
975 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700976 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700977 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
978 config.sample_rate = mTestSamplingRate;
979 config.channel_mask = mTestChannels;
980 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700981 if (offloadInfo != NULL) {
982 config.offload_info = *offloadInfo;
983 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700984 status = mpClientInterface->openOutput(0,
985 &mTestOutputs[mCurOutput],
986 &config,
987 &outputDesc->mDevice,
988 String8(""),
989 &outputDesc->mLatency,
990 outputDesc->mFlags);
991 if (status == NO_ERROR) {
992 outputDesc->mSamplingRate = config.sample_rate;
993 outputDesc->mFormat = config.format;
994 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700995 AudioParameter outputCmd = AudioParameter();
996 outputCmd.addInt(String8("set_id"),mCurOutput);
997 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
998 addOutput(mTestOutputs[mCurOutput], outputDesc);
999 }
1000 }
1001 return mTestOutputs[mCurOutput];
1002 }
1003#endif //AUDIO_POLICY_TEST
1004
1005 // open a direct output if required by specified parameters
1006 //force direct flag if offload flag is set: offloading implies a direct output stream
1007 // and all common behaviors are driven by checking only the direct flag
1008 // this should normally be set appropriately in the policy configuration file
1009 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001010 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001011 }
Eric Laurent93c3d412014-08-01 14:48:35 -07001012 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1013 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1014 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001015 // only allow deep buffering for music stream type
1016 if (stream != AUDIO_STREAM_MUSIC) {
1017 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1018 }
Eric Laurente552edb2014-03-10 17:42:56 -07001019
Eric Laurentb732cf52014-09-24 19:08:21 -07001020 sp<IOProfile> profile;
1021
1022 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001023 // and not explicitly requested
1024 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1025 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -07001026 audio_channel_count_from_out_mask(channelMask) <= 2) {
1027 goto non_direct_output;
1028 }
1029
Eric Laurente552edb2014-03-10 17:42:56 -07001030 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1031 // creating an offloaded track and tearing it down immediately after start when audioflinger
1032 // detects there is an active non offloadable effect.
1033 // FIXME: We should check the audio session here but we do not have it in this context.
1034 // This may prevent offloading in rare situations where effects are left active by apps
1035 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001036
Eric Laurente552edb2014-03-10 17:42:56 -07001037 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1038 !isNonOffloadableEffectEnabled()) {
1039 profile = getProfileForDirectOutput(device,
1040 samplingRate,
1041 format,
1042 channelMask,
1043 (audio_output_flags_t)flags);
1044 }
1045
Eric Laurent1c333e22014-05-20 10:48:17 -07001046 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001047 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -07001048
1049 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001050 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001051 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1052 outputDesc = desc;
1053 // reuse direct output if currently open and configured with same parameters
1054 if ((samplingRate == outputDesc->mSamplingRate) &&
1055 (format == outputDesc->mFormat) &&
1056 (channelMask == outputDesc->mChannelMask)) {
1057 outputDesc->mDirectOpenCount++;
1058 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1059 return mOutputs.keyAt(i);
1060 }
1061 }
1062 }
1063 // close direct output if currently open and configured with different parameters
1064 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001065 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001066 }
1067 outputDesc = new AudioOutputDescriptor(profile);
1068 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001069 outputDesc->mLatency = 0;
1070 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001071 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1072 config.sample_rate = samplingRate;
1073 config.channel_mask = channelMask;
1074 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001075 if (offloadInfo != NULL) {
1076 config.offload_info = *offloadInfo;
1077 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001078 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1079 &output,
1080 &config,
1081 &outputDesc->mDevice,
1082 String8(""),
1083 &outputDesc->mLatency,
1084 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001085
1086 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001087 if (status != NO_ERROR ||
1088 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1089 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1090 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001091 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1092 "format %d %d, channelMask %04x %04x", output, samplingRate,
1093 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1094 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001095 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001096 mpClientInterface->closeOutput(output);
1097 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001098 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001099 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001100 outputDesc->mSamplingRate = config.sample_rate;
1101 outputDesc->mChannelMask = config.channel_mask;
1102 outputDesc->mFormat = config.format;
1103 outputDesc->mRefCount[stream] = 0;
1104 outputDesc->mStopTime[stream] = 0;
1105 outputDesc->mDirectOpenCount = 1;
1106
Eric Laurente552edb2014-03-10 17:42:56 -07001107 audio_io_handle_t srcOutput = getOutputForEffect();
1108 addOutput(output, outputDesc);
1109 audio_io_handle_t dstOutput = getOutputForEffect();
1110 if (dstOutput == output) {
1111 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1112 }
1113 mPreviousOutputs = mOutputs;
1114 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001115 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001116 return output;
1117 }
1118
Eric Laurentb732cf52014-09-24 19:08:21 -07001119non_direct_output:
1120
Eric Laurente552edb2014-03-10 17:42:56 -07001121 // ignoring channel mask due to downmix capability in mixer
1122
1123 // open a non direct output
1124
1125 // for non direct outputs, only PCM is supported
1126 if (audio_is_linear_pcm(format)) {
1127 // get which output is suitable for the specified stream. The actual
1128 // routing change will happen when startOutput() will be called
1129 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1130
Eric Laurent8838a382014-09-08 16:44:28 -07001131 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1132 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1133 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001134 }
1135 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1136 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1137
1138 ALOGV("getOutput() returns output %d", output);
1139
1140 return output;
1141}
1142
Eric Laurente0720872014-03-11 09:30:41 -07001143audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001144 audio_output_flags_t flags,
1145 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001146{
1147 // select one output among several that provide a path to a particular device or set of
1148 // devices (the list was previously build by getOutputsForDevice()).
1149 // The priority is as follows:
1150 // 1: the output with the highest number of requested policy flags
1151 // 2: the primary output
1152 // 3: the first output in the list
1153
1154 if (outputs.size() == 0) {
1155 return 0;
1156 }
1157 if (outputs.size() == 1) {
1158 return outputs[0];
1159 }
1160
1161 int maxCommonFlags = 0;
1162 audio_io_handle_t outputFlags = 0;
1163 audio_io_handle_t outputPrimary = 0;
1164
1165 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001166 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001167 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001168 // if a valid format is specified, skip output if not compatible
1169 if (format != AUDIO_FORMAT_INVALID) {
1170 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1171 if (format != outputDesc->mFormat) {
1172 continue;
1173 }
1174 } else if (!audio_is_linear_pcm(format)) {
1175 continue;
1176 }
1177 }
1178
Eric Laurent3b73df72014-03-11 09:06:29 -07001179 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001180 if (commonFlags > maxCommonFlags) {
1181 outputFlags = outputs[i];
1182 maxCommonFlags = commonFlags;
1183 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1184 }
1185 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1186 outputPrimary = outputs[i];
1187 }
1188 }
1189 }
1190
1191 if (outputFlags != 0) {
1192 return outputFlags;
1193 }
1194 if (outputPrimary != 0) {
1195 return outputPrimary;
1196 }
1197
1198 return outputs[0];
1199}
1200
Eric Laurente0720872014-03-11 09:30:41 -07001201status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001202 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001203 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001204{
1205 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1206 ssize_t index = mOutputs.indexOfKey(output);
1207 if (index < 0) {
1208 ALOGW("startOutput() unknown output %d", output);
1209 return BAD_VALUE;
1210 }
1211
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001212 // cannot start playback of STREAM_TTS if any other output is being used
1213 uint32_t beaconMuteLatency = 0;
1214 if (stream == AUDIO_STREAM_TTS) {
1215 ALOGV("\t found BEACON stream");
1216 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1217 return INVALID_OPERATION;
1218 } else {
1219 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1220 }
1221 } else {
1222 // some playback other than beacon starts
1223 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1224 }
1225
Eric Laurent1f2f2232014-06-02 12:01:23 -07001226 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001227
1228 // increment usage count for this stream on the requested output:
1229 // NOTE that the usage count is the same for duplicated output and hardware output which is
1230 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1231 outputDesc->changeRefCount(stream, 1);
1232
1233 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001234 // starting an output being rerouted?
1235 audio_devices_t newDevice;
Eric Laurentc722f302014-12-10 11:21:49 -08001236 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001237 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1238 } else {
1239 newDevice = getNewOutputDevice(output, false /*fromCache*/);
1240 }
Eric Laurente552edb2014-03-10 17:42:56 -07001241 routing_strategy strategy = getStrategy(stream);
1242 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001243 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1244 (beaconMuteLatency > 0);
1245 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001246 bool force = false;
1247 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001248 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001249 if (desc != outputDesc) {
1250 // force a device change if any other output is managed by the same hw
1251 // module and has a current device selection that differs from selected device.
1252 // In this case, the audio HAL must receive the new device selection so that it can
1253 // change the device currently selected by the other active output.
1254 if (outputDesc->sharesHwModuleWith(desc) &&
1255 desc->device() != newDevice) {
1256 force = true;
1257 }
1258 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001259 // a notification so that audio focus effect can propagate, or that a mute/unmute
1260 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001261 uint32_t latency = desc->latency();
1262 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1263 waitMs = latency;
1264 }
1265 }
1266 }
1267 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1268
1269 // handle special case for sonification while in call
1270 if (isInCall()) {
1271 handleIncallSonification(stream, true, false);
1272 }
1273
1274 // apply volume rules for current stream and device if necessary
1275 checkAndSetVolume(stream,
1276 mStreams[stream].getVolumeIndex(newDevice),
1277 output,
1278 newDevice);
1279
1280 // update the outputs if starting an output with a stream that can affect notification
1281 // routing
1282 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001283
1284 // Automatically enable the remote submix input when output is started on a re routing mix
1285 // of type MIX_TYPE_RECORDERS
1286 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1287 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001288 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001289 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1290 outputDesc->mPolicyMix->mRegistrationId);
1291 }
1292
Eric Laurente552edb2014-03-10 17:42:56 -07001293 if (waitMs > muteWaitMs) {
1294 usleep((waitMs - muteWaitMs) * 2 * 1000);
1295 }
1296 }
1297 return NO_ERROR;
1298}
1299
1300
Eric Laurente0720872014-03-11 09:30:41 -07001301status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001302 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001303 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001304{
1305 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1306 ssize_t index = mOutputs.indexOfKey(output);
1307 if (index < 0) {
1308 ALOGW("stopOutput() unknown output %d", output);
1309 return BAD_VALUE;
1310 }
1311
Eric Laurent1f2f2232014-06-02 12:01:23 -07001312 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001313
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001314 // always handle stream stop, check which stream type is stopping
1315 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1316
Eric Laurente552edb2014-03-10 17:42:56 -07001317 // handle special case for sonification while in call
1318 if (isInCall()) {
1319 handleIncallSonification(stream, false, false);
1320 }
1321
1322 if (outputDesc->mRefCount[stream] > 0) {
1323 // decrement usage count of this stream on the output
1324 outputDesc->changeRefCount(stream, -1);
1325 // store time at which the stream was stopped - see isStreamActive()
1326 if (outputDesc->mRefCount[stream] == 0) {
Eric Laurentc722f302014-12-10 11:21:49 -08001327 // Automatically disable the remote submix input when output is stopped on a
1328 // re routing mix of type MIX_TYPE_RECORDERS
1329 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1330 outputDesc->mPolicyMix != NULL &&
1331 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001332 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001333 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1334 outputDesc->mPolicyMix->mRegistrationId);
1335 }
1336
Eric Laurente552edb2014-03-10 17:42:56 -07001337 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001338 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001339 // delay the device switch by twice the latency because stopOutput() is executed when
1340 // the track stop() command is received and at that time the audio track buffer can
1341 // still contain data that needs to be drained. The latency only covers the audio HAL
1342 // and kernel buffers. Also the latency does not always include additional delay in the
1343 // audio path (audio DSP, CODEC ...)
1344 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1345
1346 // force restoring the device selection on other active outputs if it differs from the
1347 // one being selected for this output
1348 for (size_t i = 0; i < mOutputs.size(); i++) {
1349 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001350 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001351 if (curOutput != output &&
1352 desc->isActive() &&
1353 outputDesc->sharesHwModuleWith(desc) &&
1354 (newDevice != desc->device())) {
1355 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001356 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001357 true,
1358 outputDesc->mLatency*2);
1359 }
1360 }
1361 // update the outputs if stopping one with a stream that can affect notification routing
1362 handleNotificationRoutingForStream(stream);
1363 }
1364 return NO_ERROR;
1365 } else {
1366 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1367 return INVALID_OPERATION;
1368 }
1369}
1370
Eric Laurente83b55d2014-11-14 10:06:21 -08001371void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001372 audio_stream_type_t stream __unused,
1373 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001374{
1375 ALOGV("releaseOutput() %d", output);
1376 ssize_t index = mOutputs.indexOfKey(output);
1377 if (index < 0) {
1378 ALOGW("releaseOutput() releasing unknown output %d", output);
1379 return;
1380 }
1381
1382#ifdef AUDIO_POLICY_TEST
1383 int testIndex = testOutputIndex(output);
1384 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001385 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001386 if (outputDesc->isActive()) {
1387 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001388 mOutputs.removeItem(output);
1389 mTestOutputs[testIndex] = 0;
1390 }
1391 return;
1392 }
1393#endif //AUDIO_POLICY_TEST
1394
Eric Laurent1f2f2232014-06-02 12:01:23 -07001395 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001396 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001397 if (desc->mDirectOpenCount <= 0) {
1398 ALOGW("releaseOutput() invalid open count %d for output %d",
1399 desc->mDirectOpenCount, output);
1400 return;
1401 }
1402 if (--desc->mDirectOpenCount == 0) {
1403 closeOutput(output);
1404 // If effects where present on the output, audioflinger moved them to the primary
1405 // output by default: move them back to the appropriate output.
1406 audio_io_handle_t dstOutput = getOutputForEffect();
1407 if (dstOutput != mPrimaryOutput) {
1408 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1409 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001410 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001411 }
1412 }
1413}
1414
1415
Eric Laurentcaf7f482014-11-25 17:50:47 -08001416status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1417 audio_io_handle_t *input,
1418 audio_session_t session,
1419 uint32_t samplingRate,
1420 audio_format_t format,
1421 audio_channel_mask_t channelMask,
1422 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001423{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001424 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1425 "session %d, flags %#x",
1426 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001427
Eric Laurentcaf7f482014-11-25 17:50:47 -08001428 *input = AUDIO_IO_HANDLE_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001429 audio_devices_t device;
1430 // handle legacy remote submix case where the address was not always specified
1431 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001432 bool isSoundTrigger = false;
Eric Laurentcaf7f482014-11-25 17:50:47 -08001433 audio_source_t halInputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001434 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001435
1436 if (attr->source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1437 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1438 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1439 address = String8(attr->tags + strlen("addr="));
1440 ssize_t index = mPolicyMixes.indexOfKey(address);
1441 if (index < 0) {
1442 ALOGW("getInputForAttr() no policy for address %s", address.string());
1443 return BAD_VALUE;
1444 }
Eric Laurentc722f302014-12-10 11:21:49 -08001445 if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) {
1446 ALOGW("getInputForAttr() bad policy mix type for address %s", address.string());
1447 return BAD_VALUE;
1448 }
1449 policyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08001450 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001451 device = getDeviceAndMixForInputSource(attr->source, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001452 if (device == AUDIO_DEVICE_NONE) {
1453 ALOGW("getInputForAttr() could not find device for source %d", attr->source);
1454 return BAD_VALUE;
1455 }
Eric Laurentc722f302014-12-10 11:21:49 -08001456 if (policyMix != NULL) {
1457 address = policyMix->mRegistrationId;
1458 } else if (audio_is_remote_submix_device(device)) {
1459 address = String8("0");
1460 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001461 // adapt channel selection to input source
1462 switch (attr->source) {
1463 case AUDIO_SOURCE_VOICE_UPLINK:
1464 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1465 break;
1466 case AUDIO_SOURCE_VOICE_DOWNLINK:
1467 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1468 break;
1469 case AUDIO_SOURCE_VOICE_CALL:
1470 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1471 break;
1472 default:
1473 break;
1474 }
1475 if (attr->source == AUDIO_SOURCE_HOTWORD) {
1476 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1477 if (index >= 0) {
1478 *input = mSoundTriggerSessions.valueFor(session);
1479 isSoundTrigger = true;
1480 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1481 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1482 } else {
1483 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1484 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001485 }
1486 }
1487
Eric Laurent275e8e92014-11-30 15:14:47 -08001488 sp<IOProfile> profile = getInputProfile(device, address,
1489 samplingRate, format, channelMask,
1490 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001491 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001492 //retry without flags
1493 audio_input_flags_t log_flags = flags;
1494 flags = AUDIO_INPUT_FLAG_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001495 profile = getInputProfile(device, address,
1496 samplingRate, format, channelMask,
1497 flags);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001498 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001499 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1500 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001501 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001502 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001503 }
Eric Laurente552edb2014-03-10 17:42:56 -07001504 }
1505
1506 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001507 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1508 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001509 }
1510
1511 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1512 config.sample_rate = samplingRate;
1513 config.channel_mask = channelMask;
1514 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001515
Eric Laurentcf2c0212014-07-25 16:20:43 -07001516 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001517 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001518 &config,
1519 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001520 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001521 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001522 flags);
1523
1524 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001525 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001526 (samplingRate != config.sample_rate) ||
1527 (format != config.format) ||
1528 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001529 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001530 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001531 if (*input != AUDIO_IO_HANDLE_NONE) {
1532 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001533 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001534 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001535 }
1536
Eric Laurent1f2f2232014-06-02 12:01:23 -07001537 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001538 inputDesc->mInputSource = attr->source;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001539 inputDesc->mRefCount = 0;
1540 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001541 inputDesc->mSamplingRate = samplingRate;
1542 inputDesc->mFormat = format;
1543 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001544 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001545 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001546 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001547 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001548
Eric Laurentcaf7f482014-11-25 17:50:47 -08001549 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001550 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001551 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001552}
1553
Eric Laurent4dc68062014-07-28 17:26:49 -07001554status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1555 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001556{
1557 ALOGV("startInput() input %d", input);
1558 ssize_t index = mInputs.indexOfKey(input);
1559 if (index < 0) {
1560 ALOGW("startInput() unknown input %d", input);
1561 return BAD_VALUE;
1562 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001563 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001564
Eric Laurentc722f302014-12-10 11:21:49 -08001565 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001566 if (index < 0) {
1567 ALOGW("startInput() unknown session %d on input %d", session, input);
1568 return BAD_VALUE;
1569 }
1570
Glenn Kasten74a8e252014-07-24 14:09:55 -07001571 // virtual input devices are compatible with other input devices
1572 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1573
1574 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001575 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001576 if (activeInput != 0 && activeInput != input) {
1577
1578 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1579 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001580 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001581 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001582 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurentc722f302014-12-10 11:21:49 -08001583 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1584 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001585 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001586 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001587 return INVALID_OPERATION;
1588 }
1589 }
1590 }
1591
Glenn Kasten74a8e252014-07-24 14:09:55 -07001592 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001593 if (activeInputsCount() == 0) {
1594 SoundTrigger::setCaptureState(true);
1595 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001596 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001597
Eric Laurentc722f302014-12-10 11:21:49 -08001598 // automatically enable the remote submix output when input is started if not
1599 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001600 // For remote submix (a virtual device), we open only one input per capture request.
1601 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001602 String8 address = String8("");
1603 if (inputDesc->mPolicyMix == NULL) {
1604 address = String8("0");
1605 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1606 address = inputDesc->mPolicyMix->mRegistrationId;
1607 }
1608 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001609 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001610 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1611 address);
1612 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001613 }
Eric Laurente552edb2014-03-10 17:42:56 -07001614 }
1615
Eric Laurente552edb2014-03-10 17:42:56 -07001616 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1617
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001618 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001619 return NO_ERROR;
1620}
1621
Eric Laurent4dc68062014-07-28 17:26:49 -07001622status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1623 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001624{
1625 ALOGV("stopInput() input %d", input);
1626 ssize_t index = mInputs.indexOfKey(input);
1627 if (index < 0) {
1628 ALOGW("stopInput() unknown input %d", input);
1629 return BAD_VALUE;
1630 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001631 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001632
Eric Laurentc722f302014-12-10 11:21:49 -08001633 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001634 if (index < 0) {
1635 ALOGW("stopInput() unknown session %d on input %d", session, input);
1636 return BAD_VALUE;
1637 }
1638
Eric Laurente552edb2014-03-10 17:42:56 -07001639 if (inputDesc->mRefCount == 0) {
1640 ALOGW("stopInput() input %d already stopped", input);
1641 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001642 }
1643
1644 inputDesc->mRefCount--;
1645 if (inputDesc->mRefCount == 0) {
1646
Eric Laurentc722f302014-12-10 11:21:49 -08001647 // automatically disable the remote submix output when input is stopped if not
1648 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001649 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001650 String8 address = String8("");
1651 if (inputDesc->mPolicyMix == NULL) {
1652 address = String8("0");
1653 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1654 address = inputDesc->mPolicyMix->mRegistrationId;
1655 }
1656 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001657 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001658 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1659 address);
1660 }
Eric Laurente552edb2014-03-10 17:42:56 -07001661 }
1662
Eric Laurent1c333e22014-05-20 10:48:17 -07001663 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001664
1665 if (activeInputsCount() == 0) {
1666 SoundTrigger::setCaptureState(false);
1667 }
Eric Laurente552edb2014-03-10 17:42:56 -07001668 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001669 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001670}
1671
Eric Laurent4dc68062014-07-28 17:26:49 -07001672void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1673 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001674{
1675 ALOGV("releaseInput() %d", input);
1676 ssize_t index = mInputs.indexOfKey(input);
1677 if (index < 0) {
1678 ALOGW("releaseInput() releasing unknown input %d", input);
1679 return;
1680 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001681 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1682 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001683
Eric Laurentc722f302014-12-10 11:21:49 -08001684 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001685 if (index < 0) {
1686 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1687 return;
1688 }
Eric Laurentc722f302014-12-10 11:21:49 -08001689 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001690 if (inputDesc->mOpenRefCount == 0) {
1691 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1692 return;
1693 }
1694 inputDesc->mOpenRefCount--;
1695 if (inputDesc->mOpenRefCount > 0) {
1696 ALOGV("releaseInput() exit > 0");
1697 return;
1698 }
1699
Eric Laurent05b90f82014-08-27 15:32:29 -07001700 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001701 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001702 ALOGV("releaseInput() exit");
1703}
1704
Eric Laurentd4692962014-05-05 18:13:44 -07001705void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001706 bool patchRemoved = false;
1707
Eric Laurentd4692962014-05-05 18:13:44 -07001708 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001709 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1710 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1711 if (patch_index >= 0) {
1712 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1713 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1714 mAudioPatches.removeItemsAt(patch_index);
1715 patchRemoved = true;
1716 }
Eric Laurentd4692962014-05-05 18:13:44 -07001717 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1718 }
1719 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001720 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001721
1722 if (patchRemoved) {
1723 mpClientInterface->onAudioPatchListUpdate();
1724 }
Eric Laurentd4692962014-05-05 18:13:44 -07001725}
1726
Eric Laurente0720872014-03-11 09:30:41 -07001727void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001728 int indexMin,
1729 int indexMax)
1730{
1731 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1732 if (indexMin < 0 || indexMin >= indexMax) {
1733 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1734 return;
1735 }
1736 mStreams[stream].mIndexMin = indexMin;
1737 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001738 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1739 if (stream == AUDIO_STREAM_MUSIC) {
1740 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1741 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1742 }
Eric Laurente552edb2014-03-10 17:42:56 -07001743}
1744
Eric Laurente0720872014-03-11 09:30:41 -07001745status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001746 int index,
1747 audio_devices_t device)
1748{
1749
1750 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1751 return BAD_VALUE;
1752 }
1753 if (!audio_is_output_device(device)) {
1754 return BAD_VALUE;
1755 }
1756
1757 // Force max volume if stream cannot be muted
1758 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1759
1760 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1761 stream, device, index);
1762
1763 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1764 // clear all device specific values
1765 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1766 mStreams[stream].mIndexCur.clear();
1767 }
1768 mStreams[stream].mIndexCur.add(device, index);
1769
Eric Laurent31551f82014-10-10 18:21:56 -07001770 // update volume on all outputs whose current device is also selected by the same
1771 // strategy as the device specified by the caller
1772 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001773
1774
1775 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1776 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1777 if (stream == AUDIO_STREAM_MUSIC) {
1778 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1779 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1780 }
1781 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1782 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001783 return NO_ERROR;
1784 }
Eric Laurente552edb2014-03-10 17:42:56 -07001785 status_t status = NO_ERROR;
1786 for (size_t i = 0; i < mOutputs.size(); i++) {
1787 audio_devices_t curDevice =
1788 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001789 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001790 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1791 if (volStatus != NO_ERROR) {
1792 status = volStatus;
1793 }
1794 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001795 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1796 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1797 index, mOutputs.keyAt(i), curDevice);
1798 }
Eric Laurente552edb2014-03-10 17:42:56 -07001799 }
1800 return status;
1801}
1802
Eric Laurente0720872014-03-11 09:30:41 -07001803status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001804 int *index,
1805 audio_devices_t device)
1806{
1807 if (index == NULL) {
1808 return BAD_VALUE;
1809 }
1810 if (!audio_is_output_device(device)) {
1811 return BAD_VALUE;
1812 }
1813 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1814 // the strategy the stream belongs to.
1815 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1816 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1817 }
1818 device = getDeviceForVolume(device);
1819
1820 *index = mStreams[stream].getVolumeIndex(device);
1821 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1822 return NO_ERROR;
1823}
1824
Eric Laurente0720872014-03-11 09:30:41 -07001825audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001826 const SortedVector<audio_io_handle_t>& outputs)
1827{
1828 // select one output among several suitable for global effects.
1829 // The priority is as follows:
1830 // 1: An offloaded output. If the effect ends up not being offloadable,
1831 // AudioFlinger will invalidate the track and the offloaded output
1832 // will be closed causing the effect to be moved to a PCM output.
1833 // 2: A deep buffer output
1834 // 3: the first output in the list
1835
1836 if (outputs.size() == 0) {
1837 return 0;
1838 }
1839
1840 audio_io_handle_t outputOffloaded = 0;
1841 audio_io_handle_t outputDeepBuffer = 0;
1842
1843 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001844 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001845 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001846 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1847 outputOffloaded = outputs[i];
1848 }
1849 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1850 outputDeepBuffer = outputs[i];
1851 }
1852 }
1853
1854 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1855 outputOffloaded, outputDeepBuffer);
1856 if (outputOffloaded != 0) {
1857 return outputOffloaded;
1858 }
1859 if (outputDeepBuffer != 0) {
1860 return outputDeepBuffer;
1861 }
1862
1863 return outputs[0];
1864}
1865
Eric Laurente0720872014-03-11 09:30:41 -07001866audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001867{
1868 // apply simple rule where global effects are attached to the same output as MUSIC streams
1869
Eric Laurent3b73df72014-03-11 09:06:29 -07001870 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001871 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1872 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1873
1874 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1875 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1876 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1877
1878 return output;
1879}
1880
Eric Laurente0720872014-03-11 09:30:41 -07001881status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001882 audio_io_handle_t io,
1883 uint32_t strategy,
1884 int session,
1885 int id)
1886{
1887 ssize_t index = mOutputs.indexOfKey(io);
1888 if (index < 0) {
1889 index = mInputs.indexOfKey(io);
1890 if (index < 0) {
1891 ALOGW("registerEffect() unknown io %d", io);
1892 return INVALID_OPERATION;
1893 }
1894 }
1895
1896 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1897 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1898 desc->name, desc->memoryUsage);
1899 return INVALID_OPERATION;
1900 }
1901 mTotalEffectsMemory += desc->memoryUsage;
1902 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1903 desc->name, io, strategy, session, id);
1904 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1905
Eric Laurent1f2f2232014-06-02 12:01:23 -07001906 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1907 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1908 effectDesc->mIo = io;
1909 effectDesc->mStrategy = (routing_strategy)strategy;
1910 effectDesc->mSession = session;
1911 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001912
Eric Laurent1f2f2232014-06-02 12:01:23 -07001913 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001914
1915 return NO_ERROR;
1916}
1917
Eric Laurente0720872014-03-11 09:30:41 -07001918status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001919{
1920 ssize_t index = mEffects.indexOfKey(id);
1921 if (index < 0) {
1922 ALOGW("unregisterEffect() unknown effect ID %d", id);
1923 return INVALID_OPERATION;
1924 }
1925
Eric Laurent1f2f2232014-06-02 12:01:23 -07001926 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001927
Eric Laurent1f2f2232014-06-02 12:01:23 -07001928 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001929
Eric Laurent1f2f2232014-06-02 12:01:23 -07001930 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001931 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001932 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1933 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001934 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001935 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001936 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001937 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001938
1939 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001940
1941 return NO_ERROR;
1942}
1943
Eric Laurente0720872014-03-11 09:30:41 -07001944status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001945{
1946 ssize_t index = mEffects.indexOfKey(id);
1947 if (index < 0) {
1948 ALOGW("unregisterEffect() unknown effect ID %d", id);
1949 return INVALID_OPERATION;
1950 }
1951
1952 return setEffectEnabled(mEffects.valueAt(index), enabled);
1953}
1954
Eric Laurent1f2f2232014-06-02 12:01:23 -07001955status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001956{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001957 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001958 ALOGV("setEffectEnabled(%s) effect already %s",
1959 enabled?"true":"false", enabled?"enabled":"disabled");
1960 return INVALID_OPERATION;
1961 }
1962
1963 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001964 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001965 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001966 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001967 return INVALID_OPERATION;
1968 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001969 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001970 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1971 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001972 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001973 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001974 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1975 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001976 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001977 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001978 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1979 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001980 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001981 return NO_ERROR;
1982}
1983
Eric Laurente0720872014-03-11 09:30:41 -07001984bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001985{
1986 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001987 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1988 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1989 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001990 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001991 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001992 return true;
1993 }
1994 }
1995 return false;
1996}
1997
Eric Laurente0720872014-03-11 09:30:41 -07001998bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001999{
2000 nsecs_t sysTime = systemTime();
2001 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002002 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07002003 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002004 return true;
2005 }
2006 }
2007 return false;
2008}
2009
Eric Laurente0720872014-03-11 09:30:41 -07002010bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07002011 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002012{
2013 nsecs_t sysTime = systemTime();
2014 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002015 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002016 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002017 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurentc722f302014-12-10 11:21:49 -08002018 // do not consider re routing (when the output is going to a dynamic policy)
2019 // as "remote playback"
2020 if (outputDesc->mPolicyMix == NULL) {
Jean-Michel Trivi1767df72014-12-09 18:11:49 -08002021 return true;
2022 }
Eric Laurente552edb2014-03-10 17:42:56 -07002023 }
2024 }
2025 return false;
2026}
2027
Eric Laurente0720872014-03-11 09:30:41 -07002028bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002029{
2030 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002031 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002032 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07002033 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07002034 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
2035 && (inputDescriptor->mRefCount > 0)) {
2036 return true;
2037 }
2038 }
2039 return false;
2040}
2041
Eric Laurent275e8e92014-11-30 15:14:47 -08002042// Register a list of custom mixes with their attributes and format.
2043// When a mix is registered, corresponding input and output profiles are
2044// added to the remote submix hw module. The profile contains only the
2045// parameters (sampling rate, format...) specified by the mix.
2046// The corresponding input remote submix device is also connected.
2047//
2048// When a remote submix device is connected, the address is checked to select the
2049// appropriate profile and the corresponding input or output stream is opened.
2050//
2051// When capture starts, getInputForAttr() will:
2052// - 1 look for a mix matching the address passed in attribtutes tags if any
2053// - 2 if none found, getDeviceForInputSource() will:
2054// - 2.1 look for a mix matching the attributes source
2055// - 2.2 if none found, default to device selection by policy rules
2056// At this time, the corresponding output remote submix device is also connected
2057// and active playback use cases can be transferred to this mix if needed when reconnecting
2058// after AudioTracks are invalidated
2059//
2060// When playback starts, getOutputForAttr() will:
2061// - 1 look for a mix matching the address passed in attribtutes tags if any
2062// - 2 if none found, look for a mix matching the attributes usage
2063// - 3 if none found, default to device and output selection by policy rules.
2064
2065status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2066{
2067 sp<HwModule> module;
2068 for (size_t i = 0; i < mHwModules.size(); i++) {
2069 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2070 mHwModules[i]->mHandle != 0) {
2071 module = mHwModules[i];
2072 break;
2073 }
2074 }
2075
2076 if (module == 0) {
2077 return INVALID_OPERATION;
2078 }
2079
2080 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2081
2082 for (size_t i = 0; i < mixes.size(); i++) {
2083 String8 address = mixes[i].mRegistrationId;
2084 ssize_t index = mPolicyMixes.indexOfKey(address);
2085 if (index >= 0) {
2086 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2087 continue;
2088 }
2089 audio_config_t outputConfig = mixes[i].mFormat;
2090 audio_config_t inputConfig = mixes[i].mFormat;
2091 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2092 // stereo and let audio flinger do the channel conversion if needed.
2093 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2094 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2095 module->addOutputProfile(address, &outputConfig,
2096 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2097 module->addInputProfile(address, &inputConfig,
2098 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2099 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2100 policyMix->mMix = mixes[i];
2101 mPolicyMixes.add(address, policyMix);
Eric Laurentc722f302014-12-10 11:21:49 -08002102 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002103 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002104 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2105 address.string());
2106 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002107 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002108 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2109 address.string());
2110 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002111 }
2112 return NO_ERROR;
2113}
2114
2115status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2116{
2117 sp<HwModule> module;
2118 for (size_t i = 0; i < mHwModules.size(); i++) {
2119 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2120 mHwModules[i]->mHandle != 0) {
2121 module = mHwModules[i];
2122 break;
2123 }
2124 }
2125
2126 if (module == 0) {
2127 return INVALID_OPERATION;
2128 }
2129
2130 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2131
2132 for (size_t i = 0; i < mixes.size(); i++) {
2133 String8 address = mixes[i].mRegistrationId;
2134 ssize_t index = mPolicyMixes.indexOfKey(address);
2135 if (index < 0) {
2136 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2137 continue;
2138 }
2139
2140 mPolicyMixes.removeItemsAt(index);
2141
Eric Laurentc722f302014-12-10 11:21:49 -08002142 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2143 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2144 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002145 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002146 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2147 address.string());
2148 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002149
2150 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2151 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2152 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002153 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002154 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2155 address.string());
2156 }
2157 module->removeOutputProfile(address);
2158 module->removeInputProfile(address);
2159 }
2160 return NO_ERROR;
2161}
2162
Eric Laurente552edb2014-03-10 17:42:56 -07002163
Eric Laurente0720872014-03-11 09:30:41 -07002164status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002165{
2166 const size_t SIZE = 256;
2167 char buffer[SIZE];
2168 String8 result;
2169
2170 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2171 result.append(buffer);
2172
2173 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2174 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002175 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2176 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002177 snprintf(buffer, SIZE, " Force use for communications %d\n",
2178 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002179 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002180 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002181 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002182 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07002183 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002184 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07002185 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002186 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002187 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002188 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2189 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2190 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002191
Eric Laurent3a4311c2014-03-17 12:00:47 -07002192 snprintf(buffer, SIZE, " Available output devices:\n");
2193 result.append(buffer);
2194 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002195 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002196 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002197 }
2198 snprintf(buffer, SIZE, "\n Available input devices:\n");
2199 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002200 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002201 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002202 }
Eric Laurente552edb2014-03-10 17:42:56 -07002203
2204 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2205 write(fd, buffer, strlen(buffer));
2206 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002207 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002208 write(fd, buffer, strlen(buffer));
2209 mHwModules[i]->dump(fd);
2210 }
2211
2212 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2213 write(fd, buffer, strlen(buffer));
2214 for (size_t i = 0; i < mOutputs.size(); i++) {
2215 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2216 write(fd, buffer, strlen(buffer));
2217 mOutputs.valueAt(i)->dump(fd);
2218 }
2219
2220 snprintf(buffer, SIZE, "\nInputs dump:\n");
2221 write(fd, buffer, strlen(buffer));
2222 for (size_t i = 0; i < mInputs.size(); i++) {
2223 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2224 write(fd, buffer, strlen(buffer));
2225 mInputs.valueAt(i)->dump(fd);
2226 }
2227
2228 snprintf(buffer, SIZE, "\nStreams dump:\n");
2229 write(fd, buffer, strlen(buffer));
2230 snprintf(buffer, SIZE,
2231 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2232 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002233 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002234 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002235 write(fd, buffer, strlen(buffer));
2236 mStreams[i].dump(fd);
2237 }
2238
2239 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2240 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2241 write(fd, buffer, strlen(buffer));
2242
2243 snprintf(buffer, SIZE, "Registered effects:\n");
2244 write(fd, buffer, strlen(buffer));
2245 for (size_t i = 0; i < mEffects.size(); i++) {
2246 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2247 write(fd, buffer, strlen(buffer));
2248 mEffects.valueAt(i)->dump(fd);
2249 }
2250
Eric Laurent4d416952014-08-10 14:07:09 -07002251 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2252 write(fd, buffer, strlen(buffer));
2253 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2254 mAudioPatches[i]->dump(fd, 2, i);
2255 }
Eric Laurente552edb2014-03-10 17:42:56 -07002256
2257 return NO_ERROR;
2258}
2259
2260// This function checks for the parameters which can be offloaded.
2261// This can be enhanced depending on the capability of the DSP and policy
2262// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002263bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002264{
2265 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002266 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002267 offloadInfo.sample_rate, offloadInfo.channel_mask,
2268 offloadInfo.format,
2269 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2270 offloadInfo.has_video);
2271
2272 // Check if offload has been disabled
2273 char propValue[PROPERTY_VALUE_MAX];
2274 if (property_get("audio.offload.disable", propValue, "0")) {
2275 if (atoi(propValue) != 0) {
2276 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2277 return false;
2278 }
2279 }
2280
2281 // Check if stream type is music, then only allow offload as of now.
2282 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2283 {
2284 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2285 return false;
2286 }
2287
2288 //TODO: enable audio offloading with video when ready
2289 if (offloadInfo.has_video)
2290 {
2291 ALOGV("isOffloadSupported: has_video == true, returning false");
2292 return false;
2293 }
2294
2295 //If duration is less than minimum value defined in property, return false
2296 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2297 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2298 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2299 return false;
2300 }
2301 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2302 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2303 return false;
2304 }
2305
2306 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2307 // creating an offloaded track and tearing it down immediately after start when audioflinger
2308 // detects there is an active non offloadable effect.
2309 // FIXME: We should check the audio session here but we do not have it in this context.
2310 // This may prevent offloading in rare situations where effects are left active by apps
2311 // in the background.
2312 if (isNonOffloadableEffectEnabled()) {
2313 return false;
2314 }
2315
2316 // See if there is a profile to support this.
2317 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002318 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002319 offloadInfo.sample_rate,
2320 offloadInfo.format,
2321 offloadInfo.channel_mask,
2322 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002323 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2324 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002325}
2326
Eric Laurent6a94d692014-05-20 11:18:06 -07002327status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2328 audio_port_type_t type,
2329 unsigned int *num_ports,
2330 struct audio_port *ports,
2331 unsigned int *generation)
2332{
2333 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2334 generation == NULL) {
2335 return BAD_VALUE;
2336 }
2337 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2338 if (ports == NULL) {
2339 *num_ports = 0;
2340 }
2341
2342 size_t portsWritten = 0;
2343 size_t portsMax = *num_ports;
2344 *num_ports = 0;
2345 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2346 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2347 for (size_t i = 0;
2348 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2349 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2350 }
2351 *num_ports += mAvailableOutputDevices.size();
2352 }
2353 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2354 for (size_t i = 0;
2355 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2356 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2357 }
2358 *num_ports += mAvailableInputDevices.size();
2359 }
2360 }
2361 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2362 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2363 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2364 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2365 }
2366 *num_ports += mInputs.size();
2367 }
2368 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002369 size_t numOutputs = 0;
2370 for (size_t i = 0; i < mOutputs.size(); i++) {
2371 if (!mOutputs[i]->isDuplicated()) {
2372 numOutputs++;
2373 if (portsWritten < portsMax) {
2374 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2375 }
2376 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002377 }
Eric Laurent84c70242014-06-23 08:46:27 -07002378 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002379 }
2380 }
2381 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002382 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002383 return NO_ERROR;
2384}
2385
2386status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2387{
2388 return NO_ERROR;
2389}
2390
Eric Laurent1f2f2232014-06-02 12:01:23 -07002391sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002392 audio_port_handle_t id) const
2393{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002394 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002395 for (size_t i = 0; i < mOutputs.size(); i++) {
2396 outputDesc = mOutputs.valueAt(i);
2397 if (outputDesc->mId == id) {
2398 break;
2399 }
2400 }
2401 return outputDesc;
2402}
2403
Eric Laurent1f2f2232014-06-02 12:01:23 -07002404sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002405 audio_port_handle_t id) const
2406{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002407 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002408 for (size_t i = 0; i < mInputs.size(); i++) {
2409 inputDesc = mInputs.valueAt(i);
2410 if (inputDesc->mId == id) {
2411 break;
2412 }
2413 }
2414 return inputDesc;
2415}
2416
Eric Laurent1f2f2232014-06-02 12:01:23 -07002417sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2418 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002419{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002420 sp <HwModule> module;
2421
Eric Laurent6a94d692014-05-20 11:18:06 -07002422 for (size_t i = 0; i < mHwModules.size(); i++) {
2423 if (mHwModules[i]->mHandle == 0) {
2424 continue;
2425 }
2426 if (audio_is_output_device(device)) {
2427 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2428 {
2429 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2430 return mHwModules[i];
2431 }
2432 }
2433 } else {
2434 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2435 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2436 device & ~AUDIO_DEVICE_BIT_IN) {
2437 return mHwModules[i];
2438 }
2439 }
2440 }
2441 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002442 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002443}
2444
Eric Laurent1f2f2232014-06-02 12:01:23 -07002445sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002446{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002447 sp <HwModule> module;
2448
Eric Laurent1afeecb2014-05-14 08:52:28 -07002449 for (size_t i = 0; i < mHwModules.size(); i++)
2450 {
2451 if (strcmp(mHwModules[i]->mName, name) == 0) {
2452 return mHwModules[i];
2453 }
2454 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002455 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002456}
2457
Eric Laurentc2730ba2014-07-20 15:47:07 -07002458audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2459{
2460 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2461 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2462 return devices & mAvailableOutputDevices.types();
2463}
2464
2465audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2466{
2467 audio_module_handle_t primaryHandle =
2468 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2469 audio_devices_t devices = AUDIO_DEVICE_NONE;
2470 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2471 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2472 devices |= mAvailableInputDevices[i]->mDeviceType;
2473 }
2474 }
2475 return devices;
2476}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002477
Eric Laurent6a94d692014-05-20 11:18:06 -07002478status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2479 audio_patch_handle_t *handle,
2480 uid_t uid)
2481{
2482 ALOGV("createAudioPatch()");
2483
2484 if (handle == NULL || patch == NULL) {
2485 return BAD_VALUE;
2486 }
2487 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2488
Eric Laurent874c42872014-08-08 15:13:39 -07002489 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2490 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2491 return BAD_VALUE;
2492 }
2493 // only one source per audio patch supported for now
2494 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002495 return INVALID_OPERATION;
2496 }
Eric Laurent874c42872014-08-08 15:13:39 -07002497
2498 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002499 return INVALID_OPERATION;
2500 }
Eric Laurent874c42872014-08-08 15:13:39 -07002501 for (size_t i = 0; i < patch->num_sinks; i++) {
2502 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2503 return INVALID_OPERATION;
2504 }
2505 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002506
2507 sp<AudioPatch> patchDesc;
2508 ssize_t index = mAudioPatches.indexOfKey(*handle);
2509
Eric Laurent6a94d692014-05-20 11:18:06 -07002510 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2511 patch->sources[0].role,
2512 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002513#if LOG_NDEBUG == 0
2514 for (size_t i = 0; i < patch->num_sinks; i++) {
2515 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2516 patch->sinks[i].role,
2517 patch->sinks[i].type);
2518 }
2519#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002520
2521 if (index >= 0) {
2522 patchDesc = mAudioPatches.valueAt(index);
2523 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2524 mUidCached, patchDesc->mUid, uid);
2525 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2526 return INVALID_OPERATION;
2527 }
2528 } else {
2529 *handle = 0;
2530 }
2531
2532 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002533 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002534 if (outputDesc == NULL) {
2535 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2536 return BAD_VALUE;
2537 }
Eric Laurent84c70242014-06-23 08:46:27 -07002538 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2539 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002540 if (patchDesc != 0) {
2541 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2542 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2543 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2544 return BAD_VALUE;
2545 }
2546 }
Eric Laurent874c42872014-08-08 15:13:39 -07002547 DeviceVector devices;
2548 for (size_t i = 0; i < patch->num_sinks; i++) {
2549 // Only support mix to devices connection
2550 // TODO add support for mix to mix connection
2551 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2552 ALOGV("createAudioPatch() source mix but sink is not a device");
2553 return INVALID_OPERATION;
2554 }
2555 sp<DeviceDescriptor> devDesc =
2556 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2557 if (devDesc == 0) {
2558 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2559 return BAD_VALUE;
2560 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002561
Eric Laurent874c42872014-08-08 15:13:39 -07002562 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002563 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002564 patch->sources[0].sample_rate,
2565 NULL, // updatedSamplingRate
2566 patch->sources[0].format,
2567 patch->sources[0].channel_mask,
2568 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2569 ALOGV("createAudioPatch() profile not supported for device %08x",
2570 devDesc->mDeviceType);
2571 return INVALID_OPERATION;
2572 }
2573 devices.add(devDesc);
2574 }
2575 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002576 return INVALID_OPERATION;
2577 }
Eric Laurent874c42872014-08-08 15:13:39 -07002578
Eric Laurent6a94d692014-05-20 11:18:06 -07002579 // TODO: reconfigure output format and channels here
2580 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002581 devices.types(), outputDesc->mIoHandle);
2582 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002583 index = mAudioPatches.indexOfKey(*handle);
2584 if (index >= 0) {
2585 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2586 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2587 }
2588 patchDesc = mAudioPatches.valueAt(index);
2589 patchDesc->mUid = uid;
2590 ALOGV("createAudioPatch() success");
2591 } else {
2592 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2593 return INVALID_OPERATION;
2594 }
2595 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2596 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2597 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002598 // only one sink supported when connecting an input device to a mix
2599 if (patch->num_sinks > 1) {
2600 return INVALID_OPERATION;
2601 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002602 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002603 if (inputDesc == NULL) {
2604 return BAD_VALUE;
2605 }
2606 if (patchDesc != 0) {
2607 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2608 return BAD_VALUE;
2609 }
2610 }
2611 sp<DeviceDescriptor> devDesc =
2612 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2613 if (devDesc == 0) {
2614 return BAD_VALUE;
2615 }
2616
Eric Laurent84c70242014-06-23 08:46:27 -07002617 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002618 devDesc->mAddress,
2619 patch->sinks[0].sample_rate,
2620 NULL, /*updatedSampleRate*/
2621 patch->sinks[0].format,
2622 patch->sinks[0].channel_mask,
2623 // FIXME for the parameter type,
2624 // and the NONE
2625 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002626 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002627 return INVALID_OPERATION;
2628 }
2629 // TODO: reconfigure output format and channels here
2630 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002631 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002632 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002633 index = mAudioPatches.indexOfKey(*handle);
2634 if (index >= 0) {
2635 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2636 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2637 }
2638 patchDesc = mAudioPatches.valueAt(index);
2639 patchDesc->mUid = uid;
2640 ALOGV("createAudioPatch() success");
2641 } else {
2642 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2643 return INVALID_OPERATION;
2644 }
2645 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2646 // device to device connection
2647 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002648 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002649 return BAD_VALUE;
2650 }
2651 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002652 sp<DeviceDescriptor> srcDeviceDesc =
2653 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002654 if (srcDeviceDesc == 0) {
2655 return BAD_VALUE;
2656 }
Eric Laurent874c42872014-08-08 15:13:39 -07002657
Eric Laurent6a94d692014-05-20 11:18:06 -07002658 //update source and sink with our own data as the data passed in the patch may
2659 // be incomplete.
2660 struct audio_patch newPatch = *patch;
2661 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002662
Eric Laurent874c42872014-08-08 15:13:39 -07002663 for (size_t i = 0; i < patch->num_sinks; i++) {
2664 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2665 ALOGV("createAudioPatch() source device but one sink is not a device");
2666 return INVALID_OPERATION;
2667 }
2668
2669 sp<DeviceDescriptor> sinkDeviceDesc =
2670 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2671 if (sinkDeviceDesc == 0) {
2672 return BAD_VALUE;
2673 }
2674 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2675
2676 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2677 // only one sink supported when connected devices across HW modules
2678 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002679 return INVALID_OPERATION;
2680 }
Eric Laurent874c42872014-08-08 15:13:39 -07002681 SortedVector<audio_io_handle_t> outputs =
2682 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2683 mOutputs);
2684 // if the sink device is reachable via an opened output stream, request to go via
2685 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002686 audio_io_handle_t output = selectOutput(outputs,
2687 AUDIO_OUTPUT_FLAG_NONE,
2688 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002689 if (output != AUDIO_IO_HANDLE_NONE) {
2690 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2691 if (outputDesc->isDuplicated()) {
2692 return INVALID_OPERATION;
2693 }
2694 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2695 newPatch.num_sources = 2;
2696 }
Eric Laurent83b88082014-06-20 18:31:16 -07002697 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002698 }
2699 // TODO: check from routing capabilities in config file and other conflicting patches
2700
2701 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2702 if (index >= 0) {
2703 afPatchHandle = patchDesc->mAfPatchHandle;
2704 }
2705
2706 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2707 &afPatchHandle,
2708 0);
2709 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2710 status, afPatchHandle);
2711 if (status == NO_ERROR) {
2712 if (index < 0) {
2713 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2714 &newPatch, uid);
2715 addAudioPatch(patchDesc->mHandle, patchDesc);
2716 } else {
2717 patchDesc->mPatch = newPatch;
2718 }
2719 patchDesc->mAfPatchHandle = afPatchHandle;
2720 *handle = patchDesc->mHandle;
2721 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002722 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002723 } else {
2724 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2725 status);
2726 return INVALID_OPERATION;
2727 }
2728 } else {
2729 return BAD_VALUE;
2730 }
2731 } else {
2732 return BAD_VALUE;
2733 }
2734 return NO_ERROR;
2735}
2736
2737status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2738 uid_t uid)
2739{
2740 ALOGV("releaseAudioPatch() patch %d", handle);
2741
2742 ssize_t index = mAudioPatches.indexOfKey(handle);
2743
2744 if (index < 0) {
2745 return BAD_VALUE;
2746 }
2747 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2748 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2749 mUidCached, patchDesc->mUid, uid);
2750 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2751 return INVALID_OPERATION;
2752 }
2753
2754 struct audio_patch *patch = &patchDesc->mPatch;
2755 patchDesc->mUid = mUidCached;
2756 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002757 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002758 if (outputDesc == NULL) {
2759 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2760 return BAD_VALUE;
2761 }
2762
2763 setOutputDevice(outputDesc->mIoHandle,
2764 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2765 true,
2766 0,
2767 NULL);
2768 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2769 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002770 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002771 if (inputDesc == NULL) {
2772 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2773 return BAD_VALUE;
2774 }
2775 setInputDevice(inputDesc->mIoHandle,
2776 getNewInputDevice(inputDesc->mIoHandle),
2777 true,
2778 NULL);
2779 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2780 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2781 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2782 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2783 status, patchDesc->mAfPatchHandle);
2784 removeAudioPatch(patchDesc->mHandle);
2785 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002786 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002787 } else {
2788 return BAD_VALUE;
2789 }
2790 } else {
2791 return BAD_VALUE;
2792 }
2793 return NO_ERROR;
2794}
2795
2796status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2797 struct audio_patch *patches,
2798 unsigned int *generation)
2799{
2800 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2801 generation == NULL) {
2802 return BAD_VALUE;
2803 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002804 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002805 *num_patches, patches, mAudioPatches.size());
2806 if (patches == NULL) {
2807 *num_patches = 0;
2808 }
2809
2810 size_t patchesWritten = 0;
2811 size_t patchesMax = *num_patches;
2812 for (size_t i = 0;
2813 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2814 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2815 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002816 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002817 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2818 }
2819 *num_patches = mAudioPatches.size();
2820
2821 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002822 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002823 return NO_ERROR;
2824}
2825
Eric Laurente1715a42014-05-20 11:30:42 -07002826status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002827{
Eric Laurente1715a42014-05-20 11:30:42 -07002828 ALOGV("setAudioPortConfig()");
2829
2830 if (config == NULL) {
2831 return BAD_VALUE;
2832 }
2833 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2834 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002835 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2836 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002837 }
2838
Eric Laurenta121f902014-06-03 13:32:54 -07002839 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002840 if (config->type == AUDIO_PORT_TYPE_MIX) {
2841 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002842 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002843 if (outputDesc == NULL) {
2844 return BAD_VALUE;
2845 }
Eric Laurent84c70242014-06-23 08:46:27 -07002846 ALOG_ASSERT(!outputDesc->isDuplicated(),
2847 "setAudioPortConfig() called on duplicated output %d",
2848 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002849 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002850 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002851 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002852 if (inputDesc == NULL) {
2853 return BAD_VALUE;
2854 }
Eric Laurenta121f902014-06-03 13:32:54 -07002855 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002856 } else {
2857 return BAD_VALUE;
2858 }
2859 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2860 sp<DeviceDescriptor> deviceDesc;
2861 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2862 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2863 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2864 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2865 } else {
2866 return BAD_VALUE;
2867 }
2868 if (deviceDesc == NULL) {
2869 return BAD_VALUE;
2870 }
Eric Laurenta121f902014-06-03 13:32:54 -07002871 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002872 } else {
2873 return BAD_VALUE;
2874 }
2875
Eric Laurenta121f902014-06-03 13:32:54 -07002876 struct audio_port_config backupConfig;
2877 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2878 if (status == NO_ERROR) {
2879 struct audio_port_config newConfig;
2880 audioPortConfig->toAudioPortConfig(&newConfig, config);
2881 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002882 }
Eric Laurenta121f902014-06-03 13:32:54 -07002883 if (status != NO_ERROR) {
2884 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002885 }
Eric Laurente1715a42014-05-20 11:30:42 -07002886
2887 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002888}
2889
2890void AudioPolicyManager::clearAudioPatches(uid_t uid)
2891{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002892 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002893 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2894 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002895 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002896 }
2897 }
2898}
2899
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002900status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2901 audio_io_handle_t *ioHandle,
2902 audio_devices_t *device)
2903{
2904 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2905 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002906 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002907
2908 mSoundTriggerSessions.add(*session, *ioHandle);
2909
2910 return NO_ERROR;
2911}
2912
2913status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2914{
2915 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2916 if (index < 0) {
2917 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2918 return BAD_VALUE;
2919 }
2920
2921 mSoundTriggerSessions.removeItem(session);
2922 return NO_ERROR;
2923}
2924
Eric Laurent6a94d692014-05-20 11:18:06 -07002925status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2926 const sp<AudioPatch>& patch)
2927{
2928 ssize_t index = mAudioPatches.indexOfKey(handle);
2929
2930 if (index >= 0) {
2931 ALOGW("addAudioPatch() patch %d already in", handle);
2932 return ALREADY_EXISTS;
2933 }
2934 mAudioPatches.add(handle, patch);
2935 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2936 "sink handle %d",
2937 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2938 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2939 return NO_ERROR;
2940}
2941
2942status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2943{
2944 ssize_t index = mAudioPatches.indexOfKey(handle);
2945
2946 if (index < 0) {
2947 ALOGW("removeAudioPatch() patch %d not in", handle);
2948 return ALREADY_EXISTS;
2949 }
2950 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2951 mAudioPatches.valueAt(index)->mAfPatchHandle);
2952 mAudioPatches.removeItemsAt(index);
2953 return NO_ERROR;
2954}
2955
Eric Laurente552edb2014-03-10 17:42:56 -07002956// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002957// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002958// ----------------------------------------------------------------------------
2959
Eric Laurent3a4311c2014-03-17 12:00:47 -07002960uint32_t AudioPolicyManager::nextUniqueId()
2961{
2962 return android_atomic_inc(&mNextUniqueId);
2963}
2964
Eric Laurent6a94d692014-05-20 11:18:06 -07002965uint32_t AudioPolicyManager::nextAudioPortGeneration()
2966{
2967 return android_atomic_inc(&mAudioPortGeneration);
2968}
2969
Eric Laurente0720872014-03-11 09:30:41 -07002970AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002971 :
2972#ifdef AUDIO_POLICY_TEST
2973 Thread(false),
2974#endif //AUDIO_POLICY_TEST
2975 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002976 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002977 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2978 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002979 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002980 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002981 mAudioPortGeneration(1),
2982 mBeaconMuteRefCount(0),
2983 mBeaconPlayingRefCount(0),
2984 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002985{
Eric Laurent6a94d692014-05-20 11:18:06 -07002986 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002987 mpClientInterface = clientInterface;
2988
Eric Laurent3b73df72014-03-11 09:06:29 -07002989 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2990 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002991 }
2992
Eric Laurent1afeecb2014-05-14 08:52:28 -07002993 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002994 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2995 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2996 ALOGE("could not load audio policy configuration file, setting defaults");
2997 defaultAudioPolicyConfig();
2998 }
2999 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003000 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003001
3002 // must be done after reading the policy
3003 initializeVolumeCurves();
3004
3005 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003006 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3007 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003008 for (size_t i = 0; i < mHwModules.size(); i++) {
3009 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3010 if (mHwModules[i]->mHandle == 0) {
3011 ALOGW("could not open HW module %s", mHwModules[i]->mName);
3012 continue;
3013 }
3014 // open all output streams needed to access attached devices
3015 // except for direct output streams that are only opened when they are actually
3016 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003017 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003018 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3019 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003020 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003021
Eric Laurent3a4311c2014-03-17 12:00:47 -07003022 if (outProfile->mSupportedDevices.isEmpty()) {
3023 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3024 continue;
3025 }
3026
Eric Laurentd78f1532014-09-16 16:38:20 -07003027 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3028 continue;
3029 }
Eric Laurent83b88082014-06-20 18:31:16 -07003030 audio_devices_t profileType = outProfile->mSupportedDevices.types();
3031 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3032 profileType = mDefaultOutputDevice->mDeviceType;
3033 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07003034 // chose first device present in mSupportedDevices also part of
3035 // outputDeviceTypes
3036 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3037 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3038 if ((profileType & outputDeviceTypes) != 0) {
3039 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003040 }
Eric Laurente552edb2014-03-10 17:42:56 -07003041 }
3042 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003043 if ((profileType & outputDeviceTypes) == 0) {
3044 continue;
3045 }
3046 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3047
3048 outputDesc->mDevice = profileType;
3049 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3050 config.sample_rate = outputDesc->mSamplingRate;
3051 config.channel_mask = outputDesc->mChannelMask;
3052 config.format = outputDesc->mFormat;
3053 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3054 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3055 &output,
3056 &config,
3057 &outputDesc->mDevice,
3058 String8(""),
3059 &outputDesc->mLatency,
3060 outputDesc->mFlags);
3061
3062 if (status != NO_ERROR) {
3063 ALOGW("Cannot open output stream for device %08x on hw module %s",
3064 outputDesc->mDevice,
3065 mHwModules[i]->mName);
3066 } else {
3067 outputDesc->mSamplingRate = config.sample_rate;
3068 outputDesc->mChannelMask = config.channel_mask;
3069 outputDesc->mFormat = config.format;
3070
3071 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3072 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3073 ssize_t index =
3074 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3075 // give a valid ID to an attached device once confirmed it is reachable
3076 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3077 mAvailableOutputDevices[index]->mId = nextUniqueId();
3078 mAvailableOutputDevices[index]->mModule = mHwModules[i];
3079 }
3080 }
3081 if (mPrimaryOutput == 0 &&
3082 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3083 mPrimaryOutput = output;
3084 }
3085 addOutput(output, outputDesc);
3086 setOutputDevice(output,
3087 outputDesc->mDevice,
3088 true);
3089 }
Eric Laurente552edb2014-03-10 17:42:56 -07003090 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003091 // open input streams needed to access attached devices to validate
3092 // mAvailableInputDevices list
3093 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3094 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003095 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003096
Eric Laurent3a4311c2014-03-17 12:00:47 -07003097 if (inProfile->mSupportedDevices.isEmpty()) {
3098 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3099 continue;
3100 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003101 // chose first device present in mSupportedDevices also part of
3102 // inputDeviceTypes
3103 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3104 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3105 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3106 if (profileType & inputDeviceTypes) {
3107 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003108 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003109 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003110 if ((profileType & inputDeviceTypes) == 0) {
3111 continue;
3112 }
3113 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3114
3115 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3116 inputDesc->mDevice = profileType;
3117
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003118 // find the address
3119 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3120 // the inputs vector must be of size 1, but we don't want to crash here
3121 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3122 : String8("");
3123 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3124 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3125
Eric Laurentd78f1532014-09-16 16:38:20 -07003126 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3127 config.sample_rate = inputDesc->mSamplingRate;
3128 config.channel_mask = inputDesc->mChannelMask;
3129 config.format = inputDesc->mFormat;
3130 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3131 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3132 &input,
3133 &config,
3134 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003135 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003136 AUDIO_SOURCE_MIC,
3137 AUDIO_INPUT_FLAG_NONE);
3138
3139 if (status == NO_ERROR) {
3140 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3141 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3142 ssize_t index =
3143 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3144 // give a valid ID to an attached device once confirmed it is reachable
3145 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3146 mAvailableInputDevices[index]->mId = nextUniqueId();
3147 mAvailableInputDevices[index]->mModule = mHwModules[i];
3148 }
3149 }
3150 mpClientInterface->closeInput(input);
3151 } else {
3152 ALOGW("Cannot open input stream for device %08x on hw module %s",
3153 inputDesc->mDevice,
3154 mHwModules[i]->mName);
3155 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003156 }
3157 }
3158 // make sure all attached devices have been allocated a unique ID
3159 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3160 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003161 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003162 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3163 continue;
3164 }
3165 i++;
3166 }
3167 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3168 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003169 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003170 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3171 continue;
3172 }
3173 i++;
3174 }
3175 // make sure default device is reachable
3176 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003177 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003178 }
Eric Laurente552edb2014-03-10 17:42:56 -07003179
3180 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3181
3182 updateDevicesAndOutputs();
3183
3184#ifdef AUDIO_POLICY_TEST
3185 if (mPrimaryOutput != 0) {
3186 AudioParameter outputCmd = AudioParameter();
3187 outputCmd.addInt(String8("set_id"), 0);
3188 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3189
3190 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3191 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003192 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3193 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003194 mTestLatencyMs = 0;
3195 mCurOutput = 0;
3196 mDirectOutput = false;
3197 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3198 mTestOutputs[i] = 0;
3199 }
3200
3201 const size_t SIZE = 256;
3202 char buffer[SIZE];
3203 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3204 run(buffer, ANDROID_PRIORITY_AUDIO);
3205 }
3206#endif //AUDIO_POLICY_TEST
3207}
3208
Eric Laurente0720872014-03-11 09:30:41 -07003209AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003210{
3211#ifdef AUDIO_POLICY_TEST
3212 exit();
3213#endif //AUDIO_POLICY_TEST
3214 for (size_t i = 0; i < mOutputs.size(); i++) {
3215 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003216 }
3217 for (size_t i = 0; i < mInputs.size(); i++) {
3218 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003219 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003220 mAvailableOutputDevices.clear();
3221 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003222 mOutputs.clear();
3223 mInputs.clear();
3224 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003225}
3226
Eric Laurente0720872014-03-11 09:30:41 -07003227status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003228{
3229 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3230}
3231
3232#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003233bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003234{
3235 ALOGV("entering threadLoop()");
3236 while (!exitPending())
3237 {
3238 String8 command;
3239 int valueInt;
3240 String8 value;
3241
3242 Mutex::Autolock _l(mLock);
3243 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3244
3245 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3246 AudioParameter param = AudioParameter(command);
3247
3248 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3249 valueInt != 0) {
3250 ALOGV("Test command %s received", command.string());
3251 String8 target;
3252 if (param.get(String8("target"), target) != NO_ERROR) {
3253 target = "Manager";
3254 }
3255 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3256 param.remove(String8("test_cmd_policy_output"));
3257 mCurOutput = valueInt;
3258 }
3259 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3260 param.remove(String8("test_cmd_policy_direct"));
3261 if (value == "false") {
3262 mDirectOutput = false;
3263 } else if (value == "true") {
3264 mDirectOutput = true;
3265 }
3266 }
3267 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3268 param.remove(String8("test_cmd_policy_input"));
3269 mTestInput = valueInt;
3270 }
3271
3272 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3273 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003274 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003275 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003276 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003277 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003278 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003279 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003280 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003281 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003282 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003283 if (target == "Manager") {
3284 mTestFormat = format;
3285 } else if (mTestOutputs[mCurOutput] != 0) {
3286 AudioParameter outputParam = AudioParameter();
3287 outputParam.addInt(String8("format"), format);
3288 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3289 }
3290 }
3291 }
3292 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3293 param.remove(String8("test_cmd_policy_channels"));
3294 int channels = 0;
3295
3296 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003297 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003298 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003299 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003300 }
3301 if (channels != 0) {
3302 if (target == "Manager") {
3303 mTestChannels = channels;
3304 } else if (mTestOutputs[mCurOutput] != 0) {
3305 AudioParameter outputParam = AudioParameter();
3306 outputParam.addInt(String8("channels"), channels);
3307 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3308 }
3309 }
3310 }
3311 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3312 param.remove(String8("test_cmd_policy_sampleRate"));
3313 if (valueInt >= 0 && valueInt <= 96000) {
3314 int samplingRate = valueInt;
3315 if (target == "Manager") {
3316 mTestSamplingRate = samplingRate;
3317 } else if (mTestOutputs[mCurOutput] != 0) {
3318 AudioParameter outputParam = AudioParameter();
3319 outputParam.addInt(String8("sampling_rate"), samplingRate);
3320 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3321 }
3322 }
3323 }
3324
3325 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3326 param.remove(String8("test_cmd_policy_reopen"));
3327
Eric Laurent1f2f2232014-06-02 12:01:23 -07003328 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003329 mpClientInterface->closeOutput(mPrimaryOutput);
3330
3331 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3332
Eric Laurente552edb2014-03-10 17:42:56 -07003333 mOutputs.removeItem(mPrimaryOutput);
3334
Eric Laurent1f2f2232014-06-02 12:01:23 -07003335 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003336 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003337 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3338 config.sample_rate = outputDesc->mSamplingRate;
3339 config.channel_mask = outputDesc->mChannelMask;
3340 config.format = outputDesc->mFormat;
3341 status_t status = mpClientInterface->openOutput(moduleHandle,
3342 &mPrimaryOutput,
3343 &config,
3344 &outputDesc->mDevice,
3345 String8(""),
3346 &outputDesc->mLatency,
3347 outputDesc->mFlags);
3348 if (status != NO_ERROR) {
3349 ALOGE("Failed to reopen hardware output stream, "
3350 "samplingRate: %d, format %d, channels %d",
3351 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003352 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003353 outputDesc->mSamplingRate = config.sample_rate;
3354 outputDesc->mChannelMask = config.channel_mask;
3355 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003356 AudioParameter outputCmd = AudioParameter();
3357 outputCmd.addInt(String8("set_id"), 0);
3358 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3359 addOutput(mPrimaryOutput, outputDesc);
3360 }
3361 }
3362
3363
3364 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3365 }
3366 }
3367 return false;
3368}
3369
Eric Laurente0720872014-03-11 09:30:41 -07003370void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003371{
3372 {
3373 AutoMutex _l(mLock);
3374 requestExit();
3375 mWaitWorkCV.signal();
3376 }
3377 requestExitAndWait();
3378}
3379
Eric Laurente0720872014-03-11 09:30:41 -07003380int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003381{
3382 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3383 if (output == mTestOutputs[i]) return i;
3384 }
3385 return 0;
3386}
3387#endif //AUDIO_POLICY_TEST
3388
3389// ---
3390
Eric Laurent1f2f2232014-06-02 12:01:23 -07003391void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003392{
Eric Laurent1c333e22014-05-20 10:48:17 -07003393 outputDesc->mIoHandle = output;
3394 outputDesc->mId = nextUniqueId();
3395 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003396 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003397}
3398
Eric Laurent1f2f2232014-06-02 12:01:23 -07003399void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003400{
Eric Laurent1c333e22014-05-20 10:48:17 -07003401 inputDesc->mIoHandle = input;
3402 inputDesc->mId = nextUniqueId();
3403 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003404 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003405}
Eric Laurente552edb2014-03-10 17:42:56 -07003406
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003407void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3408 const String8 address /*in*/,
3409 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3410 // look for a match on the given address on the addresses of the outputs:
3411 // find the address by finding the patch that maps to this output
3412 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3413 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3414 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3415 if (patchIdx >= 0) {
3416 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3417 const int numSinks = patchDesc->mPatch.num_sinks;
3418 for (ssize_t j=0; j < numSinks; j++) {
3419 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3420 const char* patchAddr =
3421 patchDesc->mPatch.sinks[j].ext.device.address;
3422 if (strncmp(patchAddr,
3423 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003424 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003425 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3426 outputs.add(desc->mIoHandle);
3427 break;
3428 }
3429 }
3430 }
3431 }
3432}
3433
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003434status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003435 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003436 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003437 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003438{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003439 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003440 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003441 // erase all current sample rates, formats and channel masks
3442 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003443
Eric Laurent3b73df72014-03-11 09:06:29 -07003444 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003445 // first list already open outputs that can be routed to this device
3446 for (size_t i = 0; i < mOutputs.size(); i++) {
3447 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003448 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003449 if (!deviceDistinguishesOnAddress(device)) {
3450 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3451 outputs.add(mOutputs.keyAt(i));
3452 } else {
3453 ALOGV(" checking address match due to device 0x%x", device);
3454 findIoHandlesByAddress(desc, address, outputs);
3455 }
Eric Laurente552edb2014-03-10 17:42:56 -07003456 }
3457 }
3458 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003459 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003460 for (size_t i = 0; i < mHwModules.size(); i++)
3461 {
3462 if (mHwModules[i]->mHandle == 0) {
3463 continue;
3464 }
3465 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3466 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003467 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3468 if (profile->mSupportedDevices.types() & device) {
3469 if (!deviceDistinguishesOnAddress(device) ||
3470 address == profile->mSupportedDevices[0]->mAddress) {
3471 profiles.add(profile);
3472 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3473 }
Eric Laurente552edb2014-03-10 17:42:56 -07003474 }
3475 }
3476 }
3477
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003478 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3479
Eric Laurente552edb2014-03-10 17:42:56 -07003480 if (profiles.isEmpty() && outputs.isEmpty()) {
3481 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3482 return BAD_VALUE;
3483 }
3484
3485 // open outputs for matching profiles if needed. Direct outputs are also opened to
3486 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3487 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003488 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003489
3490 // nothing to do if one output is already opened for this profile
3491 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003492 for (j = 0; j < outputs.size(); j++) {
3493 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003494 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003495 // matching profile: save the sample rates, format and channel masks supported
3496 // by the profile in our device descriptor
3497 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003498 break;
3499 }
3500 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003501 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003502 continue;
3503 }
3504
Eric Laurent83b88082014-06-20 18:31:16 -07003505 ALOGV("opening output for device %08x with params %s profile %p",
3506 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003507 desc = new AudioOutputDescriptor(profile);
3508 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003509 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3510 config.sample_rate = desc->mSamplingRate;
3511 config.channel_mask = desc->mChannelMask;
3512 config.format = desc->mFormat;
3513 config.offload_info.sample_rate = desc->mSamplingRate;
3514 config.offload_info.channel_mask = desc->mChannelMask;
3515 config.offload_info.format = desc->mFormat;
3516 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3517 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3518 &output,
3519 &config,
3520 &desc->mDevice,
3521 address,
3522 &desc->mLatency,
3523 desc->mFlags);
3524 if (status == NO_ERROR) {
3525 desc->mSamplingRate = config.sample_rate;
3526 desc->mChannelMask = config.channel_mask;
3527 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003528
Eric Laurentd4692962014-05-05 18:13:44 -07003529 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003530 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003531 char *param = audio_device_address_to_parameter(device, address);
3532 mpClientInterface->setParameters(output, String8(param));
3533 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003534 }
3535
Eric Laurentd4692962014-05-05 18:13:44 -07003536 // Here is where we step through and resolve any "dynamic" fields
3537 String8 reply;
3538 char *value;
3539 if (profile->mSamplingRates[0] == 0) {
3540 reply = mpClientInterface->getParameters(output,
3541 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003542 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003543 reply.string());
3544 value = strpbrk((char *)reply.string(), "=");
3545 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003546 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003547 }
Eric Laurentd4692962014-05-05 18:13:44 -07003548 }
3549 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3550 reply = mpClientInterface->getParameters(output,
3551 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003552 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003553 reply.string());
3554 value = strpbrk((char *)reply.string(), "=");
3555 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003556 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003557 }
Eric Laurentd4692962014-05-05 18:13:44 -07003558 }
3559 if (profile->mChannelMasks[0] == 0) {
3560 reply = mpClientInterface->getParameters(output,
3561 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003562 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003563 reply.string());
3564 value = strpbrk((char *)reply.string(), "=");
3565 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003566 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003567 }
Eric Laurentd4692962014-05-05 18:13:44 -07003568 }
3569 if (((profile->mSamplingRates[0] == 0) &&
3570 (profile->mSamplingRates.size() < 2)) ||
3571 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3572 (profile->mFormats.size() < 2)) ||
3573 ((profile->mChannelMasks[0] == 0) &&
3574 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003575 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003576 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003577 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003578 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3579 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003580 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003581 config.sample_rate = profile->pickSamplingRate();
3582 config.channel_mask = profile->pickChannelMask();
3583 config.format = profile->pickFormat();
3584 config.offload_info.sample_rate = config.sample_rate;
3585 config.offload_info.channel_mask = config.channel_mask;
3586 config.offload_info.format = config.format;
3587 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3588 &output,
3589 &config,
3590 &desc->mDevice,
3591 address,
3592 &desc->mLatency,
3593 desc->mFlags);
3594 if (status == NO_ERROR) {
3595 desc->mSamplingRate = config.sample_rate;
3596 desc->mChannelMask = config.channel_mask;
3597 desc->mFormat = config.format;
3598 } else {
3599 output = AUDIO_IO_HANDLE_NONE;
3600 }
Eric Laurentd4692962014-05-05 18:13:44 -07003601 }
3602
Eric Laurentcf2c0212014-07-25 16:20:43 -07003603 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003604 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003605 if (deviceDistinguishesOnAddress(device) && address != "0") {
3606 ssize_t index = mPolicyMixes.indexOfKey(address);
3607 if (index >= 0) {
3608 mPolicyMixes[index]->mOutput = desc;
Eric Laurentc722f302014-12-10 11:21:49 -08003609 desc->mPolicyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08003610 } else {
3611 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3612 address.string());
3613 }
Eric Laurentc722f302014-12-10 11:21:49 -08003614 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3615 // no duplicated output for direct outputs and
3616 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003617 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003618
Eric Laurentd4692962014-05-05 18:13:44 -07003619 // set initial stream volume for device
3620 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003621
Eric Laurentd4692962014-05-05 18:13:44 -07003622 //TODO: configure audio effect output stage here
3623
3624 // open a duplicating output thread for the new output and the primary output
3625 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3626 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003627 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003628 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003629 sp<AudioOutputDescriptor> dupOutputDesc =
3630 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003631 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3632 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3633 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3634 dupOutputDesc->mFormat = desc->mFormat;
3635 dupOutputDesc->mChannelMask = desc->mChannelMask;
3636 dupOutputDesc->mLatency = desc->mLatency;
3637 addOutput(duplicatedOutput, dupOutputDesc);
3638 applyStreamVolumes(duplicatedOutput, device, 0, true);
3639 } else {
3640 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3641 mPrimaryOutput, output);
3642 mpClientInterface->closeOutput(output);
3643 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003644 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003645 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003646 }
Eric Laurente552edb2014-03-10 17:42:56 -07003647 }
3648 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003649 } else {
3650 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003651 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003652 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003653 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003654 profiles.removeAt(profile_index);
3655 profile_index--;
3656 } else {
3657 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003658 devDesc->importAudioPort(profile);
3659
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003660 if (deviceDistinguishesOnAddress(device)) {
3661 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3662 device, address.string());
3663 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3664 NULL/*patch handle*/, address.string());
3665 }
Eric Laurente552edb2014-03-10 17:42:56 -07003666 ALOGV("checkOutputsForDevice(): adding output %d", output);
3667 }
3668 }
3669
3670 if (profiles.isEmpty()) {
3671 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3672 return BAD_VALUE;
3673 }
Eric Laurentd4692962014-05-05 18:13:44 -07003674 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003675 // check if one opened output is not needed any more after disconnecting one device
3676 for (size_t i = 0; i < mOutputs.size(); i++) {
3677 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003678 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003679 // exact match on device
3680 if (deviceDistinguishesOnAddress(device) &&
3681 (desc->mProfile->mSupportedDevices.types() == device)) {
3682 findIoHandlesByAddress(desc, address, outputs);
3683 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003684 & mAvailableOutputDevices.types())) {
3685 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3686 mOutputs.keyAt(i));
3687 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003688 }
Eric Laurente552edb2014-03-10 17:42:56 -07003689 }
3690 }
Eric Laurentd4692962014-05-05 18:13:44 -07003691 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003692 for (size_t i = 0; i < mHwModules.size(); i++)
3693 {
3694 if (mHwModules[i]->mHandle == 0) {
3695 continue;
3696 }
3697 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3698 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003699 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003700 if (profile->mSupportedDevices.types() & device) {
3701 ALOGV("checkOutputsForDevice(): "
3702 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003703 if (profile->mSamplingRates[0] == 0) {
3704 profile->mSamplingRates.clear();
3705 profile->mSamplingRates.add(0);
3706 }
3707 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3708 profile->mFormats.clear();
3709 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3710 }
3711 if (profile->mChannelMasks[0] == 0) {
3712 profile->mChannelMasks.clear();
3713 profile->mChannelMasks.add(0);
3714 }
3715 }
3716 }
3717 }
3718 }
3719 return NO_ERROR;
3720}
3721
Eric Laurentd4692962014-05-05 18:13:44 -07003722status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3723 audio_policy_dev_state_t state,
3724 SortedVector<audio_io_handle_t>& inputs,
3725 const String8 address)
3726{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003727 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003728 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3729 // first list already open inputs that can be routed to this device
3730 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3731 desc = mInputs.valueAt(input_index);
3732 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3733 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3734 inputs.add(mInputs.keyAt(input_index));
3735 }
3736 }
3737
3738 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003739 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003740 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3741 {
3742 if (mHwModules[module_idx]->mHandle == 0) {
3743 continue;
3744 }
3745 for (size_t profile_index = 0;
3746 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3747 profile_index++)
3748 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003749 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3750
3751 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3752 if (!deviceDistinguishesOnAddress(device) ||
3753 address == profile->mSupportedDevices[0]->mAddress) {
3754 profiles.add(profile);
3755 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3756 profile_index, module_idx);
3757 }
Eric Laurentd4692962014-05-05 18:13:44 -07003758 }
3759 }
3760 }
3761
3762 if (profiles.isEmpty() && inputs.isEmpty()) {
3763 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3764 return BAD_VALUE;
3765 }
3766
3767 // open inputs for matching profiles if needed. Direct inputs are also opened to
3768 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3769 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3770
Eric Laurent1c333e22014-05-20 10:48:17 -07003771 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003772 // nothing to do if one input is already opened for this profile
3773 size_t input_index;
3774 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3775 desc = mInputs.valueAt(input_index);
3776 if (desc->mProfile == profile) {
3777 break;
3778 }
3779 }
3780 if (input_index != mInputs.size()) {
3781 continue;
3782 }
3783
3784 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3785 desc = new AudioInputDescriptor(profile);
3786 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003787 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3788 config.sample_rate = desc->mSamplingRate;
3789 config.channel_mask = desc->mChannelMask;
3790 config.format = desc->mFormat;
3791 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3792 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3793 &input,
3794 &config,
3795 &desc->mDevice,
3796 address,
3797 AUDIO_SOURCE_MIC,
3798 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003799
Eric Laurentcf2c0212014-07-25 16:20:43 -07003800 if (status == NO_ERROR) {
3801 desc->mSamplingRate = config.sample_rate;
3802 desc->mChannelMask = config.channel_mask;
3803 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003804
Eric Laurentd4692962014-05-05 18:13:44 -07003805 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003806 char *param = audio_device_address_to_parameter(device, address);
3807 mpClientInterface->setParameters(input, String8(param));
3808 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003809 }
3810
3811 // Here is where we step through and resolve any "dynamic" fields
3812 String8 reply;
3813 char *value;
3814 if (profile->mSamplingRates[0] == 0) {
3815 reply = mpClientInterface->getParameters(input,
3816 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3817 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3818 reply.string());
3819 value = strpbrk((char *)reply.string(), "=");
3820 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003821 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003822 }
3823 }
3824 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3825 reply = mpClientInterface->getParameters(input,
3826 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3827 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3828 value = strpbrk((char *)reply.string(), "=");
3829 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003830 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003831 }
3832 }
3833 if (profile->mChannelMasks[0] == 0) {
3834 reply = mpClientInterface->getParameters(input,
3835 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3836 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3837 reply.string());
3838 value = strpbrk((char *)reply.string(), "=");
3839 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003840 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003841 }
3842 }
3843 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3844 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3845 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3846 ALOGW("checkInputsForDevice() direct input missing param");
3847 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003848 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003849 }
3850
3851 if (input != 0) {
3852 addInput(input, desc);
3853 }
3854 } // endif input != 0
3855
Eric Laurentcf2c0212014-07-25 16:20:43 -07003856 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003857 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003858 profiles.removeAt(profile_index);
3859 profile_index--;
3860 } else {
3861 inputs.add(input);
3862 ALOGV("checkInputsForDevice(): adding input %d", input);
3863 }
3864 } // end scan profiles
3865
3866 if (profiles.isEmpty()) {
3867 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3868 return BAD_VALUE;
3869 }
3870 } else {
3871 // Disconnect
3872 // check if one opened input is not needed any more after disconnecting one device
3873 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3874 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003875 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3876 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003877 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3878 mInputs.keyAt(input_index));
3879 inputs.add(mInputs.keyAt(input_index));
3880 }
3881 }
3882 // Clear any profiles associated with the disconnected device.
3883 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3884 if (mHwModules[module_index]->mHandle == 0) {
3885 continue;
3886 }
3887 for (size_t profile_index = 0;
3888 profile_index < mHwModules[module_index]->mInputProfiles.size();
3889 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003890 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003891 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003892 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003893 profile_index, module_index);
3894 if (profile->mSamplingRates[0] == 0) {
3895 profile->mSamplingRates.clear();
3896 profile->mSamplingRates.add(0);
3897 }
3898 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3899 profile->mFormats.clear();
3900 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3901 }
3902 if (profile->mChannelMasks[0] == 0) {
3903 profile->mChannelMasks.clear();
3904 profile->mChannelMasks.add(0);
3905 }
3906 }
3907 }
3908 }
3909 } // end disconnect
3910
3911 return NO_ERROR;
3912}
3913
3914
Eric Laurente0720872014-03-11 09:30:41 -07003915void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003916{
3917 ALOGV("closeOutput(%d)", output);
3918
Eric Laurent1f2f2232014-06-02 12:01:23 -07003919 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003920 if (outputDesc == NULL) {
3921 ALOGW("closeOutput() unknown output %d", output);
3922 return;
3923 }
3924
Eric Laurent275e8e92014-11-30 15:14:47 -08003925 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3926 if (mPolicyMixes[i]->mOutput == outputDesc) {
3927 mPolicyMixes[i]->mOutput.clear();
3928 }
3929 }
3930
Eric Laurente552edb2014-03-10 17:42:56 -07003931 // look for duplicated outputs connected to the output being removed.
3932 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003933 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003934 if (dupOutputDesc->isDuplicated() &&
3935 (dupOutputDesc->mOutput1 == outputDesc ||
3936 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003937 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003938 if (dupOutputDesc->mOutput1 == outputDesc) {
3939 outputDesc2 = dupOutputDesc->mOutput2;
3940 } else {
3941 outputDesc2 = dupOutputDesc->mOutput1;
3942 }
3943 // As all active tracks on duplicated output will be deleted,
3944 // and as they were also referenced on the other output, the reference
3945 // count for their stream type must be adjusted accordingly on
3946 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003947 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003948 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003949 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003950 }
3951 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3952 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3953
3954 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003955 mOutputs.removeItem(duplicatedOutput);
3956 }
3957 }
3958
Eric Laurent05b90f82014-08-27 15:32:29 -07003959 nextAudioPortGeneration();
3960
3961 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3962 if (index >= 0) {
3963 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3964 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3965 mAudioPatches.removeItemsAt(index);
3966 mpClientInterface->onAudioPatchListUpdate();
3967 }
3968
Eric Laurente552edb2014-03-10 17:42:56 -07003969 AudioParameter param;
3970 param.add(String8("closing"), String8("true"));
3971 mpClientInterface->setParameters(output, param.toString());
3972
3973 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003974 mOutputs.removeItem(output);
3975 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003976}
3977
3978void AudioPolicyManager::closeInput(audio_io_handle_t input)
3979{
3980 ALOGV("closeInput(%d)", input);
3981
3982 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3983 if (inputDesc == NULL) {
3984 ALOGW("closeInput() unknown input %d", input);
3985 return;
3986 }
3987
Eric Laurent6a94d692014-05-20 11:18:06 -07003988 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003989
3990 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3991 if (index >= 0) {
3992 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3993 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3994 mAudioPatches.removeItemsAt(index);
3995 mpClientInterface->onAudioPatchListUpdate();
3996 }
3997
3998 mpClientInterface->closeInput(input);
3999 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004000}
4001
Eric Laurente0720872014-03-11 09:30:41 -07004002SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07004003 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004004{
4005 SortedVector<audio_io_handle_t> outputs;
4006
4007 ALOGVV("getOutputsForDevice() device %04x", device);
4008 for (size_t i = 0; i < openOutputs.size(); i++) {
4009 ALOGVV("output %d isDuplicated=%d device=%04x",
4010 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4011 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4012 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4013 outputs.add(openOutputs.keyAt(i));
4014 }
4015 }
4016 return outputs;
4017}
4018
Eric Laurente0720872014-03-11 09:30:41 -07004019bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07004020 SortedVector<audio_io_handle_t>& outputs2)
4021{
4022 if (outputs1.size() != outputs2.size()) {
4023 return false;
4024 }
4025 for (size_t i = 0; i < outputs1.size(); i++) {
4026 if (outputs1[i] != outputs2[i]) {
4027 return false;
4028 }
4029 }
4030 return true;
4031}
4032
Eric Laurente0720872014-03-11 09:30:41 -07004033void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004034{
4035 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4036 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4037 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4038 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4039
4040 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4041 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4042 strategy, srcOutputs[0], dstOutputs[0]);
4043 // mute strategy while moving tracks from one output to another
4044 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004045 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004046 if (desc->isStrategyActive(strategy)) {
4047 setStrategyMute(strategy, true, srcOutputs[i]);
4048 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4049 }
4050 }
4051
4052 // Move effects associated to this strategy from previous output to new output
4053 if (strategy == STRATEGY_MEDIA) {
4054 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4055 SortedVector<audio_io_handle_t> moved;
4056 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004057 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4058 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4059 effectDesc->mIo != fxOutput) {
4060 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004061 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4062 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004063 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004064 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004065 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004066 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004067 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004068 }
4069 }
4070 }
4071 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004072 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004073 if (i == AUDIO_STREAM_PATCH) {
4074 continue;
4075 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004076 if (getStrategy((audio_stream_type_t)i) == strategy) {
4077 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004078 }
4079 }
4080 }
4081}
4082
Eric Laurente0720872014-03-11 09:30:41 -07004083void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004084{
Jon Eklund966095e2014-09-09 15:39:49 -05004085 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4086 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004087 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004088 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4089 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004090 checkOutputForStrategy(STRATEGY_SONIFICATION);
4091 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004092 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004093 checkOutputForStrategy(STRATEGY_MEDIA);
4094 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004095 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004096}
4097
Eric Laurente0720872014-03-11 09:30:41 -07004098audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004099{
Eric Laurente552edb2014-03-10 17:42:56 -07004100 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004101 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004102 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4103 return mOutputs.keyAt(i);
4104 }
4105 }
4106
4107 return 0;
4108}
4109
Eric Laurente0720872014-03-11 09:30:41 -07004110void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004111{
Eric Laurente552edb2014-03-10 17:42:56 -07004112 audio_io_handle_t a2dpOutput = getA2dpOutput();
4113 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004114 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004115 return;
4116 }
4117
Eric Laurent3a4311c2014-03-17 12:00:47 -07004118 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004119 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4120 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4121 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004122 // suspend A2DP output if:
4123 // (NOT already suspended) &&
4124 // ((SCO device is connected &&
4125 // (forced usage for communication || for record is SCO))) ||
4126 // (phone state is ringing || in call)
4127 //
4128 // restore A2DP output if:
4129 // (Already suspended) &&
4130 // ((SCO device is NOT connected ||
4131 // (forced usage NOT for communication && NOT for record is SCO))) &&
4132 // (phone state is NOT ringing && NOT in call)
4133 //
4134 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004135 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004136 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4137 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4138 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4139 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004140
4141 mpClientInterface->restoreOutput(a2dpOutput);
4142 mA2dpSuspended = false;
4143 }
4144 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004145 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004146 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4147 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4148 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4149 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004150
4151 mpClientInterface->suspendOutput(a2dpOutput);
4152 mA2dpSuspended = true;
4153 }
4154 }
4155}
4156
Eric Laurent1c333e22014-05-20 10:48:17 -07004157audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004158{
4159 audio_devices_t device = AUDIO_DEVICE_NONE;
4160
Eric Laurent1f2f2232014-06-02 12:01:23 -07004161 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004162
4163 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4164 if (index >= 0) {
4165 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4166 if (patchDesc->mUid != mUidCached) {
4167 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4168 outputDesc->device(), outputDesc->mPatchHandle);
4169 return outputDesc->device();
4170 }
4171 }
4172
Eric Laurente552edb2014-03-10 17:42:56 -07004173 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004174 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004175 // use device for strategy enforced audible
4176 // 2: we are in call or the strategy phone is active on the output:
4177 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004178 // 3: the strategy for enforced audible is active but not enforced on the output:
4179 // use the device for strategy enforced audible
4180 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004181 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004182 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004183 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004184 // 6: the strategy accessibility is active on the output:
4185 // use device for strategy accessibility
4186 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004187 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004188 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004189 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004190 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004191 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004192 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4193 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004194 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4195 } else if (isInCall() ||
4196 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4197 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004198 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4199 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004200 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4201 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4202 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4203 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004204 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4205 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004206 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4207 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4208 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4209 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004210 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4211 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004212 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4213 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004214 }
4215
Eric Laurent1c333e22014-05-20 10:48:17 -07004216 ALOGV("getNewOutputDevice() selected device %x", device);
4217 return device;
4218}
4219
4220audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4221{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004222 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004223
4224 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4225 if (index >= 0) {
4226 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4227 if (patchDesc->mUid != mUidCached) {
4228 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4229 inputDesc->mDevice, inputDesc->mPatchHandle);
4230 return inputDesc->mDevice;
4231 }
4232 }
4233
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004234 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07004235
4236 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004237 return device;
4238}
4239
Eric Laurente0720872014-03-11 09:30:41 -07004240uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004241 return (uint32_t)getStrategy(stream);
4242}
4243
Eric Laurente0720872014-03-11 09:30:41 -07004244audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004245 // By checking the range of stream before calling getStrategy, we avoid
4246 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4247 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004248 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004249 return AUDIO_DEVICE_NONE;
4250 }
4251 audio_devices_t devices;
4252 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4253 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4254 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4255 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004256 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004257 if (outputDesc->isStrategyActive(strategy)) {
4258 devices = outputDesc->device();
4259 break;
4260 }
Eric Laurente552edb2014-03-10 17:42:56 -07004261 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004262
4263 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4264 and doesn't really need to.*/
4265 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4266 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4267 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4268 }
4269
Eric Laurente552edb2014-03-10 17:42:56 -07004270 return devices;
4271}
4272
Eric Laurente0720872014-03-11 09:30:41 -07004273AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004274 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004275
4276 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4277
Eric Laurente552edb2014-03-10 17:42:56 -07004278 // stream to strategy mapping
4279 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004280 case AUDIO_STREAM_VOICE_CALL:
4281 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004282 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004283 case AUDIO_STREAM_RING:
4284 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004285 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004286 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004287 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004288 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004289 return STRATEGY_DTMF;
4290 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004291 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004292 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004293 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4294 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004295 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004296 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004297 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004298 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004299 case AUDIO_STREAM_TTS:
4300 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004301 case AUDIO_STREAM_ACCESSIBILITY:
4302 return STRATEGY_ACCESSIBILITY;
4303 case AUDIO_STREAM_REROUTING:
4304 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004305 }
4306}
4307
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004308uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4309 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004310 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4311 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4312 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004313 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4314 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4315 }
4316
4317 // usage to strategy mapping
4318 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004319 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4320 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4321 return (uint32_t) STRATEGY_SONIFICATION;
4322 }
4323 if (isInCall()) {
4324 return (uint32_t) STRATEGY_PHONE;
4325 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004326 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004327
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004328 case AUDIO_USAGE_MEDIA:
4329 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004330 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4331 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4332 return (uint32_t) STRATEGY_MEDIA;
4333
4334 case AUDIO_USAGE_VOICE_COMMUNICATION:
4335 return (uint32_t) STRATEGY_PHONE;
4336
4337 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4338 return (uint32_t) STRATEGY_DTMF;
4339
4340 case AUDIO_USAGE_ALARM:
4341 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4342 return (uint32_t) STRATEGY_SONIFICATION;
4343
4344 case AUDIO_USAGE_NOTIFICATION:
4345 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4346 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4347 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4348 case AUDIO_USAGE_NOTIFICATION_EVENT:
4349 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4350
4351 case AUDIO_USAGE_UNKNOWN:
4352 default:
4353 return (uint32_t) STRATEGY_MEDIA;
4354 }
4355}
4356
Eric Laurente0720872014-03-11 09:30:41 -07004357void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004358 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004359 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004360 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4361 updateDevicesAndOutputs();
4362 break;
4363 default:
4364 break;
4365 }
4366}
4367
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004368bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4369 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4370 if (s == (size_t) streamToIgnore) {
4371 continue;
4372 }
4373 for (size_t i = 0; i < mOutputs.size(); i++) {
4374 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4375 if (outputDesc->mRefCount[s] != 0) {
4376 return true;
4377 }
4378 }
4379 }
4380 return false;
4381}
4382
4383uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4384 switch(event) {
4385 case STARTING_OUTPUT:
4386 mBeaconMuteRefCount++;
4387 break;
4388 case STOPPING_OUTPUT:
4389 if (mBeaconMuteRefCount > 0) {
4390 mBeaconMuteRefCount--;
4391 }
4392 break;
4393 case STARTING_BEACON:
4394 mBeaconPlayingRefCount++;
4395 break;
4396 case STOPPING_BEACON:
4397 if (mBeaconPlayingRefCount > 0) {
4398 mBeaconPlayingRefCount--;
4399 }
4400 break;
4401 }
4402
4403 if (mBeaconMuteRefCount > 0) {
4404 // any playback causes beacon to be muted
4405 return setBeaconMute(true);
4406 } else {
4407 // no other playback: unmute when beacon starts playing, mute when it stops
4408 return setBeaconMute(mBeaconPlayingRefCount == 0);
4409 }
4410}
4411
4412uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4413 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4414 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4415 // keep track of muted state to avoid repeating mute/unmute operations
4416 if (mBeaconMuted != mute) {
4417 // mute/unmute AUDIO_STREAM_TTS on all outputs
4418 ALOGV("\t muting %d", mute);
4419 uint32_t maxLatency = 0;
4420 for (size_t i = 0; i < mOutputs.size(); i++) {
4421 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4422 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4423 desc->mIoHandle,
4424 0 /*delay*/, AUDIO_DEVICE_NONE);
4425 const uint32_t latency = desc->latency() * 2;
4426 if (latency > maxLatency) {
4427 maxLatency = latency;
4428 }
4429 }
4430 mBeaconMuted = mute;
4431 return maxLatency;
4432 }
4433 return 0;
4434}
4435
Eric Laurente0720872014-03-11 09:30:41 -07004436audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004437 bool fromCache)
4438{
4439 uint32_t device = AUDIO_DEVICE_NONE;
4440
4441 if (fromCache) {
4442 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4443 strategy, mDeviceForStrategy[strategy]);
4444 return mDeviceForStrategy[strategy];
4445 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004446 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004447 switch (strategy) {
4448
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004449 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4450 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4451 if (!device) {
4452 ALOGE("getDeviceForStrategy() no device found for "\
4453 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4454 }
4455 break;
4456
Eric Laurente552edb2014-03-10 17:42:56 -07004457 case STRATEGY_SONIFICATION_RESPECTFUL:
4458 if (isInCall()) {
4459 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004460 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004461 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4462 // while media is playing on a remote device, use the the sonification behavior.
4463 // Note that we test this usecase before testing if media is playing because
4464 // the isStreamActive() method only informs about the activity of a stream, not
4465 // if it's for local playback. Note also that we use the same delay between both tests
4466 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004467 //user "safe" speaker if available instead of normal speaker to avoid triggering
4468 //other acoustic safety mechanisms for notification
4469 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4470 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004471 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004472 // while media is playing (or has recently played), use the same device
4473 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4474 } else {
4475 // when media is not playing anymore, fall back on the sonification behavior
4476 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004477 //user "safe" speaker if available instead of normal speaker to avoid triggering
4478 //other acoustic safety mechanisms for notification
4479 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4480 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004481 }
4482
4483 break;
4484
4485 case STRATEGY_DTMF:
4486 if (!isInCall()) {
4487 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4488 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4489 break;
4490 }
4491 // when in call, DTMF and PHONE strategies follow the same rules
4492 // FALL THROUGH
4493
4494 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004495 // Force use of only devices on primary output if:
4496 // - in call AND
4497 // - cannot route from voice call RX OR
4498 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4499 if (mPhoneState == AUDIO_MODE_IN_CALL) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004500 audio_devices_t txDevice =
4501 getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -07004502 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4503 if (((mAvailableInputDevices.types() &
4504 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4505 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004506 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004507 AUDIO_DEVICE_API_VERSION_3_0))) {
4508 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4509 }
4510 }
Eric Laurente552edb2014-03-10 17:42:56 -07004511 // for phone strategy, we first consider the forced use and then the available devices by order
4512 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004513 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4514 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004515 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004516 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004517 if (device) break;
4518 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004519 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004520 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004521 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004522 if (device) break;
4523 // if SCO device is requested but no SCO device is available, fall back to default case
4524 // FALL THROUGH
4525
4526 default: // FORCE_NONE
4527 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004528 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004529 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004530 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004531 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004532 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004533 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004534 if (device) break;
4535 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004536 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004537 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004538 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004539 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004540 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4541 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004542 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004543 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004544 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004545 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004546 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004547 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004548 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004549 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004550 if (device) break;
4551 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004552 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004553 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004554 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004555 if (device == AUDIO_DEVICE_NONE) {
4556 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4557 }
4558 break;
4559
Eric Laurent3b73df72014-03-11 09:06:29 -07004560 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004561 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4562 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004563 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004564 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004565 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004566 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004567 if (device) break;
4568 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004569 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004570 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004571 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004572 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004573 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004574 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004575 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004576 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004577 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004578 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004579 if (device) break;
4580 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004581 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4582 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004583 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004584 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004585 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004586 if (device == AUDIO_DEVICE_NONE) {
4587 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4588 }
4589 break;
4590 }
4591 break;
4592
4593 case STRATEGY_SONIFICATION:
4594
4595 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4596 // handleIncallSonification().
4597 if (isInCall()) {
4598 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4599 break;
4600 }
4601 // FALL THROUGH
4602
4603 case STRATEGY_ENFORCED_AUDIBLE:
4604 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4605 // except:
4606 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4607 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4608
4609 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004610 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004611 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004612 if (device == AUDIO_DEVICE_NONE) {
4613 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4614 }
4615 }
4616 // The second device used for sonification is the same as the device used by media strategy
4617 // FALL THROUGH
4618
Eric Laurent223fd5c2014-11-11 13:43:36 -08004619 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4620 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004621 if (strategy == STRATEGY_ACCESSIBILITY) {
4622 // do not route accessibility prompts to a digital output currently configured with a
4623 // compressed format as they would likely not be mixed and dropped.
4624 for (size_t i = 0; i < mOutputs.size(); i++) {
4625 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4626 audio_devices_t devices = desc->device() &
4627 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4628 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4629 devices != AUDIO_DEVICE_NONE) {
4630 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4631 }
4632 }
4633 }
4634 // FALL THROUGH
4635
Eric Laurent223fd5c2014-11-11 13:43:36 -08004636 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004637 case STRATEGY_MEDIA: {
4638 uint32_t device2 = AUDIO_DEVICE_NONE;
4639 if (strategy != STRATEGY_SONIFICATION) {
4640 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004641 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4642 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4643 }
Eric Laurente552edb2014-03-10 17:42:56 -07004644 }
4645 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004646 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004647 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004648 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004649 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004650 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004651 }
4652 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004653 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004654 }
4655 }
Hochi Huang327cb702014-09-21 09:47:31 +08004656 if ((device2 == AUDIO_DEVICE_NONE) &&
4657 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4658 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4659 }
Eric Laurente552edb2014-03-10 17:42:56 -07004660 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004661 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004662 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004663 if ((device2 == AUDIO_DEVICE_NONE)) {
4664 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4665 }
Eric Laurente552edb2014-03-10 17:42:56 -07004666 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004667 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004668 }
4669 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004670 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004671 }
4672 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004673 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004674 }
4675 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004676 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004677 }
4678 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4679 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004680 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004681 }
4682 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004683 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004684 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004685 }
4686 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004687 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004688 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004689 int device3 = AUDIO_DEVICE_NONE;
4690 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004691 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004692 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4693 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004694 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004695 }
Eric Laurente552edb2014-03-10 17:42:56 -07004696
Jungshik Jang839e4f32014-06-26 17:23:40 +09004697 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004698 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4699 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4700 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004701
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004702 // If hdmi system audio mode is on, remove speaker out of output list.
4703 if ((strategy == STRATEGY_MEDIA) &&
4704 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4705 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4706 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4707 }
4708
Eric Laurente552edb2014-03-10 17:42:56 -07004709 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004710 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004711 if (device == AUDIO_DEVICE_NONE) {
4712 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4713 }
4714 } break;
4715
4716 default:
4717 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4718 break;
4719 }
4720
4721 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4722 return device;
4723}
4724
Eric Laurente0720872014-03-11 09:30:41 -07004725void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004726{
4727 for (int i = 0; i < NUM_STRATEGIES; i++) {
4728 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4729 }
4730 mPreviousOutputs = mOutputs;
4731}
4732
Eric Laurent1f2f2232014-06-02 12:01:23 -07004733uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004734 audio_devices_t prevDevice,
4735 uint32_t delayMs)
4736{
4737 // mute/unmute strategies using an incompatible device combination
4738 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4739 // if unmuting, unmute only after the specified delay
4740 if (outputDesc->isDuplicated()) {
4741 return 0;
4742 }
4743
4744 uint32_t muteWaitMs = 0;
4745 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004746 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004747
4748 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4749 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004750 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004751 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4752 bool doMute = false;
4753
4754 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4755 doMute = true;
4756 outputDesc->mStrategyMutedByDevice[i] = true;
4757 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4758 doMute = true;
4759 outputDesc->mStrategyMutedByDevice[i] = false;
4760 }
Eric Laurent99401132014-05-07 19:48:15 -07004761 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004762 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004763 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004764 // skip output if it does not share any device with current output
4765 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4766 == AUDIO_DEVICE_NONE) {
4767 continue;
4768 }
4769 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4770 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4771 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4772 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4773 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004774 if (mute) {
4775 // FIXME: should not need to double latency if volume could be applied
4776 // immediately by the audioflinger mixer. We must account for the delay
4777 // between now and the next time the audioflinger thread for this output
4778 // will process a buffer (which corresponds to one buffer size,
4779 // usually 1/2 or 1/4 of the latency).
4780 if (muteWaitMs < desc->latency() * 2) {
4781 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004782 }
4783 }
4784 }
4785 }
4786 }
4787 }
4788
Eric Laurent99401132014-05-07 19:48:15 -07004789 // temporary mute output if device selection changes to avoid volume bursts due to
4790 // different per device volumes
4791 if (outputDesc->isActive() && (device != prevDevice)) {
4792 if (muteWaitMs < outputDesc->latency() * 2) {
4793 muteWaitMs = outputDesc->latency() * 2;
4794 }
4795 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4796 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004797 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004798 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004799 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004800 muteWaitMs *2, device);
4801 }
4802 }
4803 }
4804
Eric Laurente552edb2014-03-10 17:42:56 -07004805 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4806 if (muteWaitMs > delayMs) {
4807 muteWaitMs -= delayMs;
4808 usleep(muteWaitMs * 1000);
4809 return muteWaitMs;
4810 }
4811 return 0;
4812}
4813
Eric Laurente0720872014-03-11 09:30:41 -07004814uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004815 audio_devices_t device,
4816 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004817 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004818 audio_patch_handle_t *patchHandle,
4819 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004820{
4821 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004822 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004823 AudioParameter param;
4824 uint32_t muteWaitMs;
4825
4826 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004827 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4828 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004829 return muteWaitMs;
4830 }
4831 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4832 // output profile
4833 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004834 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004835 return 0;
4836 }
4837
4838 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004839 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004840
4841 audio_devices_t prevDevice = outputDesc->mDevice;
4842
4843 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4844
4845 if (device != AUDIO_DEVICE_NONE) {
4846 outputDesc->mDevice = device;
4847 }
4848 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4849
4850 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004851 // the requested device is AUDIO_DEVICE_NONE
4852 // OR the requested device is the same as current device
4853 // AND force is not specified
4854 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004855 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004856 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4857 outputDesc->mPatchHandle != 0) {
4858 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4859 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004860 return muteWaitMs;
4861 }
4862
4863 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004864
Eric Laurente552edb2014-03-10 17:42:56 -07004865 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004866 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004867 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004868 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004869 DeviceVector deviceList = (address == NULL) ?
4870 mAvailableOutputDevices.getDevicesFromType(device)
4871 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004872 if (!deviceList.isEmpty()) {
4873 struct audio_patch patch;
4874 outputDesc->toAudioPortConfig(&patch.sources[0]);
4875 patch.num_sources = 1;
4876 patch.num_sinks = 0;
4877 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4878 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004879 patch.num_sinks++;
4880 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004881 ssize_t index;
4882 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4883 index = mAudioPatches.indexOfKey(*patchHandle);
4884 } else {
4885 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4886 }
4887 sp< AudioPatch> patchDesc;
4888 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4889 if (index >= 0) {
4890 patchDesc = mAudioPatches.valueAt(index);
4891 afPatchHandle = patchDesc->mAfPatchHandle;
4892 }
4893
Eric Laurent1c333e22014-05-20 10:48:17 -07004894 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004895 &afPatchHandle,
4896 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004897 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4898 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004900 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004901 if (index < 0) {
4902 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4903 &patch, mUidCached);
4904 addAudioPatch(patchDesc->mHandle, patchDesc);
4905 } else {
4906 patchDesc->mPatch = patch;
4907 }
4908 patchDesc->mAfPatchHandle = afPatchHandle;
4909 patchDesc->mUid = mUidCached;
4910 if (patchHandle) {
4911 *patchHandle = patchDesc->mHandle;
4912 }
4913 outputDesc->mPatchHandle = patchDesc->mHandle;
4914 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004915 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004916 }
4917 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004918
4919 // inform all input as well
4920 for (size_t i = 0; i < mInputs.size(); i++) {
4921 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4922 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4923 AudioParameter inputCmd = AudioParameter();
4924 ALOGV("%s: inform input %d of device:%d", __func__,
4925 inputDescriptor->mIoHandle, device);
4926 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4927 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4928 inputCmd.toString(),
4929 delayMs);
4930 }
4931 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004932 }
Eric Laurente552edb2014-03-10 17:42:56 -07004933
4934 // update stream volumes according to new device
4935 applyStreamVolumes(output, device, delayMs);
4936
4937 return muteWaitMs;
4938}
4939
Eric Laurent1c333e22014-05-20 10:48:17 -07004940status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004941 int delayMs,
4942 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004943{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004944 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004945 ssize_t index;
4946 if (patchHandle) {
4947 index = mAudioPatches.indexOfKey(*patchHandle);
4948 } else {
4949 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4950 }
4951 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004952 return INVALID_OPERATION;
4953 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004954 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4955 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004956 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4957 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 removeAudioPatch(patchDesc->mHandle);
4959 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004960 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004961 return status;
4962}
4963
4964status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4965 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004966 bool force,
4967 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004968{
4969 status_t status = NO_ERROR;
4970
Eric Laurent1f2f2232014-06-02 12:01:23 -07004971 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004972 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4973 inputDesc->mDevice = device;
4974
4975 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4976 if (!deviceList.isEmpty()) {
4977 struct audio_patch patch;
4978 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004979 // AUDIO_SOURCE_HOTWORD is for internal use only:
4980 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004981 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4982 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004983 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4984 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004985 patch.num_sinks = 1;
4986 //only one input device for now
4987 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004988 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004989 ssize_t index;
4990 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4991 index = mAudioPatches.indexOfKey(*patchHandle);
4992 } else {
4993 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4994 }
4995 sp< AudioPatch> patchDesc;
4996 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4997 if (index >= 0) {
4998 patchDesc = mAudioPatches.valueAt(index);
4999 afPatchHandle = patchDesc->mAfPatchHandle;
5000 }
5001
Eric Laurent1c333e22014-05-20 10:48:17 -07005002 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005003 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005004 0);
5005 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005006 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005007 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005008 if (index < 0) {
5009 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5010 &patch, mUidCached);
5011 addAudioPatch(patchDesc->mHandle, patchDesc);
5012 } else {
5013 patchDesc->mPatch = patch;
5014 }
5015 patchDesc->mAfPatchHandle = afPatchHandle;
5016 patchDesc->mUid = mUidCached;
5017 if (patchHandle) {
5018 *patchHandle = patchDesc->mHandle;
5019 }
5020 inputDesc->mPatchHandle = patchDesc->mHandle;
5021 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005022 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005023 }
5024 }
5025 }
5026 return status;
5027}
5028
Eric Laurent6a94d692014-05-20 11:18:06 -07005029status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5030 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005031{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005032 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005033 ssize_t index;
5034 if (patchHandle) {
5035 index = mAudioPatches.indexOfKey(*patchHandle);
5036 } else {
5037 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5038 }
5039 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005040 return INVALID_OPERATION;
5041 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005042 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5043 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005044 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5045 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005046 removeAudioPatch(patchDesc->mHandle);
5047 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005048 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005049 return status;
5050}
5051
5052sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08005053 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07005054 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005055 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005056 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07005057 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005058{
5059 // Choose an input profile based on the requested capture parameters: select the first available
5060 // profile supporting all requested parameters.
5061
5062 for (size_t i = 0; i < mHwModules.size(); i++)
5063 {
5064 if (mHwModules[i]->mHandle == 0) {
5065 continue;
5066 }
5067 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5068 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005069 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005070 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005071 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005072 &samplingRate /*updatedSamplingRate*/,
5073 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005074
Eric Laurente552edb2014-03-10 17:42:56 -07005075 return profile;
5076 }
5077 }
5078 }
5079 return NULL;
5080}
5081
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005082
5083audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
Eric Laurentc722f302014-12-10 11:21:49 -08005084 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005085{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005086 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5087 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005088
5089 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5090 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5091 continue;
5092 }
5093 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5094 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5095 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5096 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5097 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5098 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurentc722f302014-12-10 11:21:49 -08005099 if (policyMix != NULL) {
5100 *policyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005101 }
5102 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5103 }
5104 break;
5105 }
5106 }
5107 }
5108
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005109 return getDeviceForInputSource(inputSource);
5110}
5111
5112audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5113{
5114 uint32_t device = AUDIO_DEVICE_NONE;
5115 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5116 ~AUDIO_DEVICE_BIT_IN;
5117
Eric Laurente552edb2014-03-10 17:42:56 -07005118 switch (inputSource) {
5119 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005120 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005121 device = AUDIO_DEVICE_IN_VOICE_CALL;
5122 break;
5123 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005124 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005125
5126 case AUDIO_SOURCE_DEFAULT:
5127 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005128 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5129 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005130 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5131 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5132 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5133 device = AUDIO_DEVICE_IN_USB_DEVICE;
5134 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5135 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005136 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005137 break;
5138
5139 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5140 // Allow only use of devices on primary input if in call and HAL does not support routing
5141 // to voice call path.
5142 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5143 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5144 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5145 }
5146
5147 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5148 case AUDIO_POLICY_FORCE_BT_SCO:
5149 // if SCO device is requested but no SCO device is available, fall back to default case
5150 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5151 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5152 break;
5153 }
5154 // FALL THROUGH
5155
5156 default: // FORCE_NONE
5157 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5158 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5159 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5160 device = AUDIO_DEVICE_IN_USB_DEVICE;
5161 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5162 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5163 }
5164 break;
5165
5166 case AUDIO_POLICY_FORCE_SPEAKER:
5167 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5168 device = AUDIO_DEVICE_IN_BACK_MIC;
5169 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5170 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5171 }
5172 break;
5173 }
5174 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005175
Eric Laurente552edb2014-03-10 17:42:56 -07005176 case AUDIO_SOURCE_VOICE_RECOGNITION:
5177 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005178 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005179 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005180 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005181 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005182 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005183 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5184 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005185 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005186 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5187 }
5188 break;
5189 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005190 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005191 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005192 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005193 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5194 }
5195 break;
5196 case AUDIO_SOURCE_VOICE_DOWNLINK:
5197 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005198 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005199 device = AUDIO_DEVICE_IN_VOICE_CALL;
5200 }
5201 break;
5202 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005203 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005204 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5205 }
5206 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005207 case AUDIO_SOURCE_FM_TUNER:
5208 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5209 device = AUDIO_DEVICE_IN_FM_TUNER;
5210 }
5211 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005212 default:
5213 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5214 break;
5215 }
5216 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5217 return device;
5218}
5219
Eric Laurente0720872014-03-11 09:30:41 -07005220bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005221{
5222 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5223 device &= ~AUDIO_DEVICE_BIT_IN;
5224 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5225 return true;
5226 }
5227 return false;
5228}
5229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005230bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005231 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005232}
5233
Eric Laurente0720872014-03-11 09:30:41 -07005234audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005235{
5236 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005237 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005238 if ((input_descriptor->mRefCount > 0)
5239 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5240 return mInputs.keyAt(i);
5241 }
5242 }
5243 return 0;
5244}
5245
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005246uint32_t AudioPolicyManager::activeInputsCount() const
5247{
5248 uint32_t count = 0;
5249 for (size_t i = 0; i < mInputs.size(); i++) {
5250 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5251 if (desc->mRefCount > 0) {
5252 return count++;
5253 }
5254 }
5255 return count;
5256}
5257
Eric Laurente552edb2014-03-10 17:42:56 -07005258
Eric Laurente0720872014-03-11 09:30:41 -07005259audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005260{
5261 if (device == AUDIO_DEVICE_NONE) {
5262 // this happens when forcing a route update and no track is active on an output.
5263 // In this case the returned category is not important.
5264 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005265 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005266 // Multiple device selection is either:
5267 // - speaker + one other device: give priority to speaker in this case.
5268 // - one A2DP device + another device: happens with duplicated output. In this case
5269 // retain the device on the A2DP output as the other must not correspond to an active
5270 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005271 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005272 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5273 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005274 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5275 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5276 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5277 device = AUDIO_DEVICE_OUT_AUX_LINE;
5278 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5279 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005280 } else {
5281 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5282 }
5283 }
5284
Jon Eklund11c9fb12014-06-23 14:47:03 -05005285 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5286 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5287 device = AUDIO_DEVICE_OUT_SPEAKER;
5288
Eric Laurent3b73df72014-03-11 09:06:29 -07005289 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005290 "getDeviceForVolume() invalid device combination: %08x",
5291 device);
5292
5293 return device;
5294}
5295
Eric Laurente0720872014-03-11 09:30:41 -07005296AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005297{
5298 switch(getDeviceForVolume(device)) {
5299 case AUDIO_DEVICE_OUT_EARPIECE:
5300 return DEVICE_CATEGORY_EARPIECE;
5301 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5302 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5303 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5304 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5305 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5306 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5307 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005308 case AUDIO_DEVICE_OUT_LINE:
5309 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5310 /*USB? Remote submix?*/
5311 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005312 case AUDIO_DEVICE_OUT_SPEAKER:
5313 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5314 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005315 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5316 case AUDIO_DEVICE_OUT_USB_DEVICE:
5317 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5318 default:
5319 return DEVICE_CATEGORY_SPEAKER;
5320 }
5321}
5322
Eric Laurent223fd5c2014-11-11 13:43:36 -08005323/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005324float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005325 int indexInUi)
5326{
5327 device_category deviceCategory = getDeviceCategory(device);
5328 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5329
5330 // the volume index in the UI is relative to the min and max volume indices for this stream type
5331 int nbSteps = 1 + curve[VOLMAX].mIndex -
5332 curve[VOLMIN].mIndex;
5333 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5334 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5335
5336 // find what part of the curve this index volume belongs to, or if it's out of bounds
5337 int segment = 0;
5338 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5339 return 0.0f;
5340 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5341 segment = 0;
5342 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5343 segment = 1;
5344 } else if (volIdx <= curve[VOLMAX].mIndex) {
5345 segment = 2;
5346 } else { // out of bounds
5347 return 1.0f;
5348 }
5349
5350 // linear interpolation in the attenuation table in dB
5351 float decibels = curve[segment].mDBAttenuation +
5352 ((float)(volIdx - curve[segment].mIndex)) *
5353 ( (curve[segment+1].mDBAttenuation -
5354 curve[segment].mDBAttenuation) /
5355 ((float)(curve[segment+1].mIndex -
5356 curve[segment].mIndex)) );
5357
5358 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5359
5360 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5361 curve[segment].mIndex, volIdx,
5362 curve[segment+1].mIndex,
5363 curve[segment].mDBAttenuation,
5364 decibels,
5365 curve[segment+1].mDBAttenuation,
5366 amplification);
5367
5368 return amplification;
5369}
5370
Eric Laurente0720872014-03-11 09:30:41 -07005371const AudioPolicyManager::VolumeCurvePoint
5372 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005373 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5374};
5375
Eric Laurente0720872014-03-11 09:30:41 -07005376const AudioPolicyManager::VolumeCurvePoint
5377 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005378 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5379};
5380
Eric Laurente0720872014-03-11 09:30:41 -07005381const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005382 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5383 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5384};
5385
5386const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005387 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005388 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5389};
5390
Eric Laurente0720872014-03-11 09:30:41 -07005391const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005392 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005393 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005394};
5395
5396const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005397 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005398 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5399};
5400
Eric Laurente0720872014-03-11 09:30:41 -07005401const AudioPolicyManager::VolumeCurvePoint
5402 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005403 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5404};
5405
5406// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5407// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5408// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5409// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5410
Eric Laurente0720872014-03-11 09:30:41 -07005411const AudioPolicyManager::VolumeCurvePoint
5412 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005413 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5414};
5415
Eric Laurente0720872014-03-11 09:30:41 -07005416const AudioPolicyManager::VolumeCurvePoint
5417 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005418 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5419};
5420
Eric Laurente0720872014-03-11 09:30:41 -07005421const AudioPolicyManager::VolumeCurvePoint
5422 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005423 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5424};
5425
Eric Laurente0720872014-03-11 09:30:41 -07005426const AudioPolicyManager::VolumeCurvePoint
5427 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005428 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5429};
5430
Eric Laurente0720872014-03-11 09:30:41 -07005431const AudioPolicyManager::VolumeCurvePoint
5432 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005433 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5434};
5435
Eric Laurente0720872014-03-11 09:30:41 -07005436const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005437 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5438 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5439};
5440
5441const AudioPolicyManager::VolumeCurvePoint
5442 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5443 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5444};
5445
5446const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005447 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5448 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5449};
5450
5451const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005452 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5453 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005454 { // AUDIO_STREAM_VOICE_CALL
5455 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5456 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005457 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5458 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005459 },
5460 { // AUDIO_STREAM_SYSTEM
5461 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5462 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005463 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5464 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005465 },
5466 { // AUDIO_STREAM_RING
5467 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5468 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005469 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5470 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005471 },
5472 { // AUDIO_STREAM_MUSIC
5473 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5474 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005475 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5476 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005477 },
5478 { // AUDIO_STREAM_ALARM
5479 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5480 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005481 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5482 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005483 },
5484 { // AUDIO_STREAM_NOTIFICATION
5485 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5486 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005487 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5488 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005489 },
5490 { // AUDIO_STREAM_BLUETOOTH_SCO
5491 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5492 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005493 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5494 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005495 },
5496 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5497 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5498 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005499 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5500 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005501 },
5502 { // AUDIO_STREAM_DTMF
5503 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5504 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005505 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5506 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005507 },
5508 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005509 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5510 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5511 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5512 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5513 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005514 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005515 { // AUDIO_STREAM_ACCESSIBILITY
5516 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5517 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5518 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5519 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5520 },
5521 { // AUDIO_STREAM_REROUTING
5522 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5523 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5524 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5525 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5526 },
5527 { // AUDIO_STREAM_PATCH
5528 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5529 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5530 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5531 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5532 },
Eric Laurente552edb2014-03-10 17:42:56 -07005533};
5534
Eric Laurente0720872014-03-11 09:30:41 -07005535void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005536{
5537 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5538 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5539 mStreams[i].mVolumeCurve[j] =
5540 sVolumeProfiles[i][j];
5541 }
5542 }
5543
5544 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5545 if (mSpeakerDrcEnabled) {
5546 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5547 sDefaultSystemVolumeCurveDrc;
5548 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5549 sSpeakerSonificationVolumeCurveDrc;
5550 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5551 sSpeakerSonificationVolumeCurveDrc;
5552 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5553 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005554 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5555 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005556 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5557 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005558 }
5559}
5560
Eric Laurente0720872014-03-11 09:30:41 -07005561float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005562 int index,
5563 audio_io_handle_t output,
5564 audio_devices_t device)
5565{
5566 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005567 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005568 StreamDescriptor &streamDesc = mStreams[stream];
5569
5570 if (device == AUDIO_DEVICE_NONE) {
5571 device = outputDesc->device();
5572 }
5573
Eric Laurente552edb2014-03-10 17:42:56 -07005574 volume = volIndexToAmpl(device, streamDesc, index);
5575
5576 // if a headset is connected, apply the following rules to ring tones and notifications
5577 // to avoid sound level bursts in user's ears:
5578 // - always attenuate ring tones and notifications volume by 6dB
5579 // - if music is playing, always limit the volume to current music volume,
5580 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005581 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005582 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5583 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5584 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5585 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5586 ((stream_strategy == STRATEGY_SONIFICATION)
5587 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005588 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005589 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005590 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005591 streamDesc.mCanBeMuted) {
5592 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5593 // when the phone is ringing we must consider that music could have been paused just before
5594 // by the music application and behave as if music was active if the last music track was
5595 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005596 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005597 mLimitRingtoneVolume) {
5598 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005599 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5600 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005601 output,
5602 musicDevice);
5603 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5604 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5605 if (volume > minVol) {
5606 volume = minVol;
5607 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5608 }
5609 }
5610 }
5611
5612 return volume;
5613}
5614
Eric Laurente0720872014-03-11 09:30:41 -07005615status_t AudioPolicyManager::checkAndSetVolume(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 int delayMs,
5620 bool force)
5621{
5622
5623 // do not change actual stream volume if the stream is muted
5624 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5625 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5626 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5627 return NO_ERROR;
5628 }
5629
5630 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005631 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5632 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5633 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5634 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005635 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005636 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005637 return INVALID_OPERATION;
5638 }
5639
5640 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005641 // unit gain if rerouting to external policy
5642 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5643 ssize_t index = mOutputs.indexOfKey(output);
5644 if (index >= 0) {
5645 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurentc722f302014-12-10 11:21:49 -08005646 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005647 ALOGV("max gain when rerouting for output=%d", output);
5648 volume = 1.0f;
5649 }
5650 }
5651
5652 }
Eric Laurente552edb2014-03-10 17:42:56 -07005653 // We actually change the volume if:
5654 // - the float value returned by computeVolume() changed
5655 // - the force flag is set
5656 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5657 force) {
5658 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5659 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5660 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5661 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005662 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5663 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005664 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005665 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005666 }
5667
Eric Laurent3b73df72014-03-11 09:06:29 -07005668 if (stream == AUDIO_STREAM_VOICE_CALL ||
5669 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005670 float voiceVolume;
5671 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005672 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005673 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5674 } else {
5675 voiceVolume = 1.0;
5676 }
5677
5678 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5679 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5680 mLastVoiceVolume = voiceVolume;
5681 }
5682 }
5683
5684 return NO_ERROR;
5685}
5686
Eric Laurente0720872014-03-11 09:30:41 -07005687void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005688 audio_devices_t device,
5689 int delayMs,
5690 bool force)
5691{
5692 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5693
Eric Laurent3b73df72014-03-11 09:06:29 -07005694 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005695 if (stream == AUDIO_STREAM_PATCH) {
5696 continue;
5697 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005698 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005699 mStreams[stream].getVolumeIndex(device),
5700 output,
5701 device,
5702 delayMs,
5703 force);
5704 }
5705}
5706
Eric Laurente0720872014-03-11 09:30:41 -07005707void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005708 bool on,
5709 audio_io_handle_t output,
5710 int delayMs,
5711 audio_devices_t device)
5712{
5713 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005714 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005715 if (stream == AUDIO_STREAM_PATCH) {
5716 continue;
5717 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005718 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5719 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005720 }
5721 }
5722}
5723
Eric Laurente0720872014-03-11 09:30:41 -07005724void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005725 bool on,
5726 audio_io_handle_t output,
5727 int delayMs,
5728 audio_devices_t device)
5729{
5730 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005731 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005732 if (device == AUDIO_DEVICE_NONE) {
5733 device = outputDesc->device();
5734 }
5735
5736 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5737 stream, on, output, outputDesc->mMuteCount[stream], device);
5738
5739 if (on) {
5740 if (outputDesc->mMuteCount[stream] == 0) {
5741 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005742 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5743 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005744 checkAndSetVolume(stream, 0, output, device, delayMs);
5745 }
5746 }
5747 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5748 outputDesc->mMuteCount[stream]++;
5749 } else {
5750 if (outputDesc->mMuteCount[stream] == 0) {
5751 ALOGV("setStreamMute() unmuting non muted stream!");
5752 return;
5753 }
5754 if (--outputDesc->mMuteCount[stream] == 0) {
5755 checkAndSetVolume(stream,
5756 streamDesc.getVolumeIndex(device),
5757 output,
5758 device,
5759 delayMs);
5760 }
5761 }
5762}
5763
Eric Laurente0720872014-03-11 09:30:41 -07005764void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005765 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005766{
5767 // if the stream pertains to sonification strategy and we are in call we must
5768 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5769 // in the device used for phone strategy and play the tone if the selected device does not
5770 // interfere with the device used for phone strategy
5771 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5772 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005773 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005774 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5775 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005776 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005777 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5778 stream, starting, outputDesc->mDevice, stateChange);
5779 if (outputDesc->mRefCount[stream]) {
5780 int muteCount = 1;
5781 if (stateChange) {
5782 muteCount = outputDesc->mRefCount[stream];
5783 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005784 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005785 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5786 for (int i = 0; i < muteCount; i++) {
5787 setStreamMute(stream, starting, mPrimaryOutput);
5788 }
5789 } else {
5790 ALOGV("handleIncallSonification() high visibility");
5791 if (outputDesc->device() &
5792 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5793 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5794 for (int i = 0; i < muteCount; i++) {
5795 setStreamMute(stream, starting, mPrimaryOutput);
5796 }
5797 }
5798 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005799 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5800 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005801 } else {
5802 mpClientInterface->stopTone();
5803 }
5804 }
5805 }
5806 }
5807}
5808
Eric Laurente0720872014-03-11 09:30:41 -07005809bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005810{
5811 return isStateInCall(mPhoneState);
5812}
5813
Eric Laurente0720872014-03-11 09:30:41 -07005814bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005815 return ((state == AUDIO_MODE_IN_CALL) ||
5816 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005817}
5818
Eric Laurente0720872014-03-11 09:30:41 -07005819uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005820{
5821 return MAX_EFFECTS_CPU_LOAD;
5822}
5823
Eric Laurente0720872014-03-11 09:30:41 -07005824uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005825{
5826 return MAX_EFFECTS_MEMORY;
5827}
5828
Eric Laurent6a94d692014-05-20 11:18:06 -07005829
Eric Laurente552edb2014-03-10 17:42:56 -07005830// --- AudioOutputDescriptor class implementation
5831
Eric Laurente0720872014-03-11 09:30:41 -07005832AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005833 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005834 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurentc722f302014-12-10 11:21:49 -08005835 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
Eric Laurent275e8e92014-11-30 15:14:47 -08005836 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005837 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5838{
5839 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005840 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005841 mRefCount[i] = 0;
5842 mCurVolume[i] = -1.0;
5843 mMuteCount[i] = 0;
5844 mStopTime[i] = 0;
5845 }
5846 for (int i = 0; i < NUM_STRATEGIES; i++) {
5847 mStrategyMutedByDevice[i] = false;
5848 }
5849 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005850 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005851 mSamplingRate = profile->pickSamplingRate();
5852 mFormat = profile->pickFormat();
5853 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005854 if (profile->mGains.size() > 0) {
5855 profile->mGains[0]->getDefaultConfig(&mGain);
5856 }
Eric Laurente552edb2014-03-10 17:42:56 -07005857 }
5858}
5859
Eric Laurente0720872014-03-11 09:30:41 -07005860audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005861{
5862 if (isDuplicated()) {
5863 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5864 } else {
5865 return mDevice;
5866 }
5867}
5868
Eric Laurente0720872014-03-11 09:30:41 -07005869uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005870{
5871 if (isDuplicated()) {
5872 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5873 } else {
5874 return mLatency;
5875 }
5876}
5877
Eric Laurente0720872014-03-11 09:30:41 -07005878bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005879 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005880{
5881 if (isDuplicated()) {
5882 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5883 } else if (outputDesc->isDuplicated()){
5884 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5885 } else {
5886 return (mProfile->mModule == outputDesc->mProfile->mModule);
5887 }
5888}
5889
Eric Laurente0720872014-03-11 09:30:41 -07005890void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005891 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005892{
5893 // forward usage count change to attached outputs
5894 if (isDuplicated()) {
5895 mOutput1->changeRefCount(stream, delta);
5896 mOutput2->changeRefCount(stream, delta);
5897 }
5898 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005899 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5900 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005901 mRefCount[stream] = 0;
5902 return;
5903 }
5904 mRefCount[stream] += delta;
5905 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5906}
5907
Eric Laurente0720872014-03-11 09:30:41 -07005908audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005909{
5910 if (isDuplicated()) {
5911 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5912 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005913 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005914 }
5915}
5916
Eric Laurente0720872014-03-11 09:30:41 -07005917bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005918{
5919 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5920}
5921
Eric Laurente0720872014-03-11 09:30:41 -07005922bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005923 uint32_t inPastMs,
5924 nsecs_t sysTime) const
5925{
5926 if ((sysTime == 0) && (inPastMs != 0)) {
5927 sysTime = systemTime();
5928 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005929 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005930 if (i == AUDIO_STREAM_PATCH) {
5931 continue;
5932 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005933 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005934 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005935 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005936 return true;
5937 }
5938 }
5939 return false;
5940}
5941
Eric Laurente0720872014-03-11 09:30:41 -07005942bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005943 uint32_t inPastMs,
5944 nsecs_t sysTime) const
5945{
5946 if (mRefCount[stream] != 0) {
5947 return true;
5948 }
5949 if (inPastMs == 0) {
5950 return false;
5951 }
5952 if (sysTime == 0) {
5953 sysTime = systemTime();
5954 }
5955 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5956 return true;
5957 }
5958 return false;
5959}
5960
Eric Laurent1c333e22014-05-20 10:48:17 -07005961void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005962 struct audio_port_config *dstConfig,
5963 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005964{
Eric Laurent84c70242014-06-23 08:46:27 -07005965 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5966
Eric Laurent1f2f2232014-06-02 12:01:23 -07005967 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5968 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5969 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005970 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005971 }
5972 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5973
Eric Laurent6a94d692014-05-20 11:18:06 -07005974 dstConfig->id = mId;
5975 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5976 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005977 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5978 dstConfig->ext.mix.handle = mIoHandle;
5979 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005980}
5981
5982void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5983 struct audio_port *port) const
5984{
Eric Laurent84c70242014-06-23 08:46:27 -07005985 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005986 mProfile->toAudioPort(port);
5987 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005988 toAudioPortConfig(&port->active_config);
5989 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005990 port->ext.mix.handle = mIoHandle;
5991 port->ext.mix.latency_class =
5992 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5993}
Eric Laurente552edb2014-03-10 17:42:56 -07005994
Eric Laurente0720872014-03-11 09:30:41 -07005995status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005996{
5997 const size_t SIZE = 256;
5998 char buffer[SIZE];
5999 String8 result;
6000
Eric Laurent4d416952014-08-10 14:07:09 -07006001 snprintf(buffer, SIZE, " ID: %d\n", mId);
6002 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006003 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6004 result.append(buffer);
6005 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
6006 result.append(buffer);
6007 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6008 result.append(buffer);
6009 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
6010 result.append(buffer);
6011 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
6012 result.append(buffer);
6013 snprintf(buffer, SIZE, " Devices %08x\n", device());
6014 result.append(buffer);
6015 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
6016 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07006017 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6018 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
6019 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07006020 result.append(buffer);
6021 }
6022 write(fd, result.string(), result.size());
6023
6024 return NO_ERROR;
6025}
6026
6027// --- AudioInputDescriptor class implementation
6028
Eric Laurent1c333e22014-05-20 10:48:17 -07006029AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006030 : mId(0), mIoHandle(0),
Eric Laurentc722f302014-12-10 11:21:49 -08006031 mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006032 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07006033{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006034 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006035 mSamplingRate = profile->pickSamplingRate();
6036 mFormat = profile->pickFormat();
6037 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07006038 if (profile->mGains.size() > 0) {
6039 profile->mGains[0]->getDefaultConfig(&mGain);
6040 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006041 }
Eric Laurente552edb2014-03-10 17:42:56 -07006042}
6043
Eric Laurent1c333e22014-05-20 10:48:17 -07006044void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006045 struct audio_port_config *dstConfig,
6046 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006047{
Eric Laurent84c70242014-06-23 08:46:27 -07006048 ALOG_ASSERT(mProfile != 0,
6049 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07006050 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6051 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6052 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006053 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006054 }
6055
6056 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6057
Eric Laurent6a94d692014-05-20 11:18:06 -07006058 dstConfig->id = mId;
6059 dstConfig->role = AUDIO_PORT_ROLE_SINK;
6060 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07006061 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6062 dstConfig->ext.mix.handle = mIoHandle;
6063 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07006064}
6065
6066void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6067 struct audio_port *port) const
6068{
Eric Laurent84c70242014-06-23 08:46:27 -07006069 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6070
Eric Laurent1c333e22014-05-20 10:48:17 -07006071 mProfile->toAudioPort(port);
6072 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006073 toAudioPortConfig(&port->active_config);
6074 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006075 port->ext.mix.handle = mIoHandle;
6076 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6077}
6078
Eric Laurente0720872014-03-11 09:30:41 -07006079status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006080{
6081 const size_t SIZE = 256;
6082 char buffer[SIZE];
6083 String8 result;
6084
Eric Laurent4d416952014-08-10 14:07:09 -07006085 snprintf(buffer, SIZE, " ID: %d\n", mId);
6086 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006087 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6088 result.append(buffer);
6089 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6090 result.append(buffer);
6091 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6092 result.append(buffer);
6093 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6094 result.append(buffer);
6095 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6096 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006097 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6098 result.append(buffer);
6099
Eric Laurente552edb2014-03-10 17:42:56 -07006100 write(fd, result.string(), result.size());
6101
6102 return NO_ERROR;
6103}
6104
6105// --- StreamDescriptor class implementation
6106
Eric Laurente0720872014-03-11 09:30:41 -07006107AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006108 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6109{
6110 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6111}
6112
Eric Laurente0720872014-03-11 09:30:41 -07006113int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006114{
Eric Laurente0720872014-03-11 09:30:41 -07006115 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006116 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6117 if (mIndexCur.indexOfKey(device) < 0) {
6118 device = AUDIO_DEVICE_OUT_DEFAULT;
6119 }
6120 return mIndexCur.valueFor(device);
6121}
6122
Eric Laurente0720872014-03-11 09:30:41 -07006123void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006124{
6125 const size_t SIZE = 256;
6126 char buffer[SIZE];
6127 String8 result;
6128
6129 snprintf(buffer, SIZE, "%s %02d %02d ",
6130 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6131 result.append(buffer);
6132 for (size_t i = 0; i < mIndexCur.size(); i++) {
6133 snprintf(buffer, SIZE, "%04x : %02d, ",
6134 mIndexCur.keyAt(i),
6135 mIndexCur.valueAt(i));
6136 result.append(buffer);
6137 }
6138 result.append("\n");
6139
6140 write(fd, result.string(), result.size());
6141}
6142
6143// --- EffectDescriptor class implementation
6144
Eric Laurente0720872014-03-11 09:30:41 -07006145status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006146{
6147 const size_t SIZE = 256;
6148 char buffer[SIZE];
6149 String8 result;
6150
6151 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6152 result.append(buffer);
6153 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6154 result.append(buffer);
6155 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6156 result.append(buffer);
6157 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6158 result.append(buffer);
6159 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6160 result.append(buffer);
6161 write(fd, result.string(), result.size());
6162
6163 return NO_ERROR;
6164}
6165
Eric Laurent1c333e22014-05-20 10:48:17 -07006166// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006167
Eric Laurente0720872014-03-11 09:30:41 -07006168AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006169 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6170 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006171{
6172}
6173
Eric Laurente0720872014-03-11 09:30:41 -07006174AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006175{
6176 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006177 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006178 }
6179 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006180 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006181 }
6182 free((void *)mName);
6183}
6184
Eric Laurent1afeecb2014-05-14 08:52:28 -07006185status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6186{
6187 cnode *node = root->first_child;
6188
6189 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6190
6191 while (node) {
6192 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6193 profile->loadSamplingRates((char *)node->value);
6194 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6195 profile->loadFormats((char *)node->value);
6196 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6197 profile->loadInChannels((char *)node->value);
6198 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6199 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6200 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006201 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6202 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006203 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6204 profile->loadGains(node);
6205 }
6206 node = node->next;
6207 }
6208 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6209 "loadInput() invalid supported devices");
6210 ALOGW_IF(profile->mChannelMasks.size() == 0,
6211 "loadInput() invalid supported channel masks");
6212 ALOGW_IF(profile->mSamplingRates.size() == 0,
6213 "loadInput() invalid supported sampling rates");
6214 ALOGW_IF(profile->mFormats.size() == 0,
6215 "loadInput() invalid supported formats");
6216 if (!profile->mSupportedDevices.isEmpty() &&
6217 (profile->mChannelMasks.size() != 0) &&
6218 (profile->mSamplingRates.size() != 0) &&
6219 (profile->mFormats.size() != 0)) {
6220
6221 ALOGV("loadInput() adding input Supported Devices %04x",
6222 profile->mSupportedDevices.types());
6223
6224 mInputProfiles.add(profile);
6225 return NO_ERROR;
6226 } else {
6227 return BAD_VALUE;
6228 }
6229}
6230
6231status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6232{
6233 cnode *node = root->first_child;
6234
6235 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6236
6237 while (node) {
6238 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6239 profile->loadSamplingRates((char *)node->value);
6240 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6241 profile->loadFormats((char *)node->value);
6242 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6243 profile->loadOutChannels((char *)node->value);
6244 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6245 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6246 mDeclaredDevices);
6247 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006248 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006249 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6250 profile->loadGains(node);
6251 }
6252 node = node->next;
6253 }
6254 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6255 "loadOutput() invalid supported devices");
6256 ALOGW_IF(profile->mChannelMasks.size() == 0,
6257 "loadOutput() invalid supported channel masks");
6258 ALOGW_IF(profile->mSamplingRates.size() == 0,
6259 "loadOutput() invalid supported sampling rates");
6260 ALOGW_IF(profile->mFormats.size() == 0,
6261 "loadOutput() invalid supported formats");
6262 if (!profile->mSupportedDevices.isEmpty() &&
6263 (profile->mChannelMasks.size() != 0) &&
6264 (profile->mSamplingRates.size() != 0) &&
6265 (profile->mFormats.size() != 0)) {
6266
6267 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6268 profile->mSupportedDevices.types(), profile->mFlags);
6269
6270 mOutputProfiles.add(profile);
6271 return NO_ERROR;
6272 } else {
6273 return BAD_VALUE;
6274 }
6275}
6276
6277status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6278{
6279 cnode *node = root->first_child;
6280
6281 audio_devices_t type = AUDIO_DEVICE_NONE;
6282 while (node) {
6283 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6284 type = parseDeviceNames((char *)node->value);
6285 break;
6286 }
6287 node = node->next;
6288 }
6289 if (type == AUDIO_DEVICE_NONE ||
6290 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6291 ALOGW("loadDevice() bad type %08x", type);
6292 return BAD_VALUE;
6293 }
6294 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6295 deviceDesc->mModule = this;
6296
6297 node = root->first_child;
6298 while (node) {
6299 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6300 deviceDesc->mAddress = String8((char *)node->value);
6301 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6302 if (audio_is_input_device(type)) {
6303 deviceDesc->loadInChannels((char *)node->value);
6304 } else {
6305 deviceDesc->loadOutChannels((char *)node->value);
6306 }
6307 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6308 deviceDesc->loadGains(node);
6309 }
6310 node = node->next;
6311 }
6312
6313 ALOGV("loadDevice() adding device name %s type %08x address %s",
6314 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6315
6316 mDeclaredDevices.add(deviceDesc);
6317
6318 return NO_ERROR;
6319}
6320
Eric Laurent275e8e92014-11-30 15:14:47 -08006321status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6322 audio_devices_t device, String8 address)
6323{
6324 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6325
6326 profile->mSamplingRates.add(config->sample_rate);
6327 profile->mChannelMasks.add(config->channel_mask);
6328 profile->mFormats.add(config->format);
6329
6330 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6331 devDesc->mAddress = address;
6332 profile->mSupportedDevices.add(devDesc);
6333
6334 mOutputProfiles.add(profile);
6335
6336 return NO_ERROR;
6337}
6338
6339status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6340{
6341 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6342 if (mOutputProfiles[i]->mName == name) {
6343 mOutputProfiles.removeAt(i);
6344 break;
6345 }
6346 }
6347
6348 return NO_ERROR;
6349}
6350
6351status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6352 audio_devices_t device, String8 address)
6353{
6354 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6355
6356 profile->mSamplingRates.add(config->sample_rate);
6357 profile->mChannelMasks.add(config->channel_mask);
6358 profile->mFormats.add(config->format);
6359
6360 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6361 devDesc->mAddress = address;
6362 profile->mSupportedDevices.add(devDesc);
6363
6364 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6365
6366 mInputProfiles.add(profile);
6367
6368 return NO_ERROR;
6369}
6370
6371status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6372{
6373 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6374 if (mInputProfiles[i]->mName == name) {
6375 mInputProfiles.removeAt(i);
6376 break;
6377 }
6378 }
6379
6380 return NO_ERROR;
6381}
6382
6383
Eric Laurente0720872014-03-11 09:30:41 -07006384void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006385{
6386 const size_t SIZE = 256;
6387 char buffer[SIZE];
6388 String8 result;
6389
6390 snprintf(buffer, SIZE, " - name: %s\n", mName);
6391 result.append(buffer);
6392 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6393 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006394 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6395 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006396 write(fd, result.string(), result.size());
6397 if (mOutputProfiles.size()) {
6398 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6399 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006400 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006401 write(fd, buffer, strlen(buffer));
6402 mOutputProfiles[i]->dump(fd);
6403 }
6404 }
6405 if (mInputProfiles.size()) {
6406 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6407 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006408 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006409 write(fd, buffer, strlen(buffer));
6410 mInputProfiles[i]->dump(fd);
6411 }
6412 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006413 if (mDeclaredDevices.size()) {
6414 write(fd, " - devices:\n", strlen(" - devices:\n"));
6415 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6416 mDeclaredDevices[i]->dump(fd, 4, i);
6417 }
6418 }
Eric Laurente552edb2014-03-10 17:42:56 -07006419}
6420
Eric Laurent1c333e22014-05-20 10:48:17 -07006421// --- AudioPort class implementation
6422
Eric Laurenta121f902014-06-03 13:32:54 -07006423
6424AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6425 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006426 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006427{
6428 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6429 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6430}
6431
Eric Laurent1c333e22014-05-20 10:48:17 -07006432void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6433{
6434 port->role = mRole;
6435 port->type = mType;
6436 unsigned int i;
6437 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006438 if (mSamplingRates[i] != 0) {
6439 port->sample_rates[i] = mSamplingRates[i];
6440 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006441 }
6442 port->num_sample_rates = i;
6443 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006444 if (mChannelMasks[i] != 0) {
6445 port->channel_masks[i] = mChannelMasks[i];
6446 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006447 }
6448 port->num_channel_masks = i;
6449 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006450 if (mFormats[i] != 0) {
6451 port->formats[i] = mFormats[i];
6452 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006453 }
6454 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006455
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006456 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006457
6458 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6459 port->gains[i] = mGains[i]->mGain;
6460 }
6461 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006462}
6463
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006464void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6465 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6466 const uint32_t rate = port->mSamplingRates.itemAt(k);
6467 if (rate != 0) { // skip "dynamic" rates
6468 bool hasRate = false;
6469 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6470 if (rate == mSamplingRates.itemAt(l)) {
6471 hasRate = true;
6472 break;
6473 }
6474 }
6475 if (!hasRate) { // never import a sampling rate twice
6476 mSamplingRates.add(rate);
6477 }
6478 }
6479 }
6480 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6481 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6482 if (mask != 0) { // skip "dynamic" masks
6483 bool hasMask = false;
6484 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6485 if (mask == mChannelMasks.itemAt(l)) {
6486 hasMask = true;
6487 break;
6488 }
6489 }
6490 if (!hasMask) { // never import a channel mask twice
6491 mChannelMasks.add(mask);
6492 }
6493 }
6494 }
6495 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6496 const audio_format_t format = port->mFormats.itemAt(k);
6497 if (format != 0) { // skip "dynamic" formats
6498 bool hasFormat = false;
6499 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6500 if (format == mFormats.itemAt(l)) {
6501 hasFormat = true;
6502 break;
6503 }
6504 }
6505 if (!hasFormat) { // never import a channel mask twice
6506 mFormats.add(format);
6507 }
6508 }
6509 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006510 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6511 sp<AudioGain> gain = port->mGains.itemAt(k);
6512 if (gain != 0) {
6513 bool hasGain = false;
6514 for (size_t l = 0 ; l < mGains.size() ; l++) {
6515 if (gain == mGains.itemAt(l)) {
6516 hasGain = true;
6517 break;
6518 }
6519 }
6520 if (!hasGain) { // never import a gain twice
6521 mGains.add(gain);
6522 }
6523 }
6524 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006525}
6526
6527void AudioPolicyManager::AudioPort::clearCapabilities() {
6528 mChannelMasks.clear();
6529 mFormats.clear();
6530 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006531 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006532}
Eric Laurent1c333e22014-05-20 10:48:17 -07006533
6534void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6535{
6536 char *str = strtok(name, "|");
6537
6538 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6539 // rates should be read from the output stream after it is opened for the first time
6540 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6541 mSamplingRates.add(0);
6542 return;
6543 }
6544
6545 while (str != NULL) {
6546 uint32_t rate = atoi(str);
6547 if (rate != 0) {
6548 ALOGV("loadSamplingRates() adding rate %d", rate);
6549 mSamplingRates.add(rate);
6550 }
6551 str = strtok(NULL, "|");
6552 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006553}
6554
6555void AudioPolicyManager::AudioPort::loadFormats(char *name)
6556{
6557 char *str = strtok(name, "|");
6558
6559 // by convention, "0' in the first entry in mFormats indicates the supported formats
6560 // should be read from the output stream after it is opened for the first time
6561 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6562 mFormats.add(AUDIO_FORMAT_DEFAULT);
6563 return;
6564 }
6565
6566 while (str != NULL) {
6567 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6568 ARRAY_SIZE(sFormatNameToEnumTable),
6569 str);
6570 if (format != AUDIO_FORMAT_DEFAULT) {
6571 mFormats.add(format);
6572 }
6573 str = strtok(NULL, "|");
6574 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006575}
6576
6577void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6578{
6579 const char *str = strtok(name, "|");
6580
6581 ALOGV("loadInChannels() %s", name);
6582
6583 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6584 mChannelMasks.add(0);
6585 return;
6586 }
6587
6588 while (str != NULL) {
6589 audio_channel_mask_t channelMask =
6590 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6591 ARRAY_SIZE(sInChannelsNameToEnumTable),
6592 str);
6593 if (channelMask != 0) {
6594 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6595 mChannelMasks.add(channelMask);
6596 }
6597 str = strtok(NULL, "|");
6598 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006599}
6600
6601void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6602{
6603 const char *str = strtok(name, "|");
6604
6605 ALOGV("loadOutChannels() %s", name);
6606
6607 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6608 // masks should be read from the output stream after it is opened for the first time
6609 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6610 mChannelMasks.add(0);
6611 return;
6612 }
6613
6614 while (str != NULL) {
6615 audio_channel_mask_t channelMask =
6616 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6617 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6618 str);
6619 if (channelMask != 0) {
6620 mChannelMasks.add(channelMask);
6621 }
6622 str = strtok(NULL, "|");
6623 }
6624 return;
6625}
6626
Eric Laurent1afeecb2014-05-14 08:52:28 -07006627audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6628{
6629 const char *str = strtok(name, "|");
6630
6631 ALOGV("loadGainMode() %s", name);
6632 audio_gain_mode_t mode = 0;
6633 while (str != NULL) {
6634 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6635 ARRAY_SIZE(sGainModeNameToEnumTable),
6636 str);
6637 str = strtok(NULL, "|");
6638 }
6639 return mode;
6640}
6641
Eric Laurenta121f902014-06-03 13:32:54 -07006642void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006643{
6644 cnode *node = root->first_child;
6645
Eric Laurenta121f902014-06-03 13:32:54 -07006646 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006647
6648 while (node) {
6649 if (strcmp(node->name, GAIN_MODE) == 0) {
6650 gain->mGain.mode = loadGainMode((char *)node->value);
6651 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006652 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006653 gain->mGain.channel_mask =
6654 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6655 ARRAY_SIZE(sInChannelsNameToEnumTable),
6656 (char *)node->value);
6657 } else {
6658 gain->mGain.channel_mask =
6659 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6660 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6661 (char *)node->value);
6662 }
6663 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6664 gain->mGain.min_value = atoi((char *)node->value);
6665 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6666 gain->mGain.max_value = atoi((char *)node->value);
6667 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6668 gain->mGain.default_value = atoi((char *)node->value);
6669 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6670 gain->mGain.step_value = atoi((char *)node->value);
6671 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6672 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6673 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6674 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6675 }
6676 node = node->next;
6677 }
6678
6679 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6680 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6681
6682 if (gain->mGain.mode == 0) {
6683 return;
6684 }
6685 mGains.add(gain);
6686}
6687
6688void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6689{
6690 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006691 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006692 while (node) {
6693 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006694 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006695 node = node->next;
6696 }
6697}
6698
Glenn Kastencbd48022014-07-24 13:46:44 -07006699status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006700{
Eric Laurent0daea392014-12-04 19:14:54 -08006701 if (mSamplingRates.isEmpty()) {
6702 return NO_ERROR;
6703 }
6704
Eric Laurenta121f902014-06-03 13:32:54 -07006705 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6706 if (mSamplingRates[i] == samplingRate) {
6707 return NO_ERROR;
6708 }
6709 }
6710 return BAD_VALUE;
6711}
6712
Glenn Kastencbd48022014-07-24 13:46:44 -07006713status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6714 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006715{
Eric Laurent0daea392014-12-04 19:14:54 -08006716 if (mSamplingRates.isEmpty()) {
6717 return NO_ERROR;
6718 }
6719
Glenn Kastencbd48022014-07-24 13:46:44 -07006720 // Search for the closest supported sampling rate that is above (preferred)
6721 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6722 // The sampling rates do not need to be sorted in ascending order.
6723 ssize_t maxBelow = -1;
6724 ssize_t minAbove = -1;
6725 uint32_t candidate;
6726 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6727 candidate = mSamplingRates[i];
6728 if (candidate == samplingRate) {
6729 if (updatedSamplingRate != NULL) {
6730 *updatedSamplingRate = candidate;
6731 }
6732 return NO_ERROR;
6733 }
6734 // candidate < desired
6735 if (candidate < samplingRate) {
6736 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6737 maxBelow = i;
6738 }
6739 // candidate > desired
6740 } else {
6741 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6742 minAbove = i;
6743 }
6744 }
6745 }
6746 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6747 // TODO Move these assumptions out.
6748 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6749 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6750 // due to approximation by an int32_t of the
6751 // phase increments
6752 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6753 if (minAbove >= 0) {
6754 candidate = mSamplingRates[minAbove];
6755 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6756 if (updatedSamplingRate != NULL) {
6757 *updatedSamplingRate = candidate;
6758 }
6759 return NO_ERROR;
6760 }
6761 }
6762 // But if we have to up-sample from a lower sampling rate, that's OK.
6763 if (maxBelow >= 0) {
6764 candidate = mSamplingRates[maxBelow];
6765 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6766 if (updatedSamplingRate != NULL) {
6767 *updatedSamplingRate = candidate;
6768 }
6769 return NO_ERROR;
6770 }
6771 }
6772 // leave updatedSamplingRate unmodified
6773 return BAD_VALUE;
6774}
6775
6776status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6777{
Eric Laurent0daea392014-12-04 19:14:54 -08006778 if (mChannelMasks.isEmpty()) {
6779 return NO_ERROR;
6780 }
6781
Glenn Kastencbd48022014-07-24 13:46:44 -07006782 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006783 if (mChannelMasks[i] == channelMask) {
6784 return NO_ERROR;
6785 }
6786 }
6787 return BAD_VALUE;
6788}
6789
Glenn Kastencbd48022014-07-24 13:46:44 -07006790status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6791 const
6792{
Eric Laurent0daea392014-12-04 19:14:54 -08006793 if (mChannelMasks.isEmpty()) {
6794 return NO_ERROR;
6795 }
6796
Glenn Kastencbd48022014-07-24 13:46:44 -07006797 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6798 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6799 // FIXME Does not handle multi-channel automatic conversions yet
6800 audio_channel_mask_t supported = mChannelMasks[i];
6801 if (supported == channelMask) {
6802 return NO_ERROR;
6803 }
6804 if (isRecordThread) {
6805 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6806 // FIXME Abstract this out to a table.
6807 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6808 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6809 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6810 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6811 return NO_ERROR;
6812 }
6813 }
6814 }
6815 return BAD_VALUE;
6816}
6817
Eric Laurenta121f902014-06-03 13:32:54 -07006818status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6819{
Eric Laurent0daea392014-12-04 19:14:54 -08006820 if (mFormats.isEmpty()) {
6821 return NO_ERROR;
6822 }
6823
Eric Laurenta121f902014-06-03 13:32:54 -07006824 for (size_t i = 0; i < mFormats.size(); i ++) {
6825 if (mFormats[i] == format) {
6826 return NO_ERROR;
6827 }
6828 }
6829 return BAD_VALUE;
6830}
6831
Eric Laurent1e693b52014-07-09 15:03:28 -07006832
6833uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6834{
6835 // special case for uninitialized dynamic profile
6836 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6837 return 0;
6838 }
6839
Eric Laurent828bcff2014-09-07 12:26:06 -07006840 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6841 // channel count / sampling rate combination chosen will be supported by the connected
6842 // sink
6843 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6844 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6845 uint32_t samplingRate = UINT_MAX;
6846 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6847 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6848 samplingRate = mSamplingRates[i];
6849 }
6850 }
6851 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6852 }
6853
Eric Laurent1e693b52014-07-09 15:03:28 -07006854 uint32_t samplingRate = 0;
6855 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6856
6857 // For mixed output and inputs, use max mixer sampling rates. Do not
6858 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006859 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006860 maxRate = UINT_MAX;
6861 }
6862 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6863 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6864 samplingRate = mSamplingRates[i];
6865 }
6866 }
6867 return samplingRate;
6868}
6869
6870audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6871{
6872 // special case for uninitialized dynamic profile
6873 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6874 return AUDIO_CHANNEL_NONE;
6875 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006876 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006877
6878 // For direct outputs, pick minimum channel count: this helps ensuring that the
6879 // channel count / sampling rate combination chosen will be supported by the connected
6880 // sink
6881 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6882 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6883 uint32_t channelCount = UINT_MAX;
6884 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6885 uint32_t cnlCount;
6886 if (mUseInChannelMask) {
6887 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6888 } else {
6889 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6890 }
6891 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6892 channelMask = mChannelMasks[i];
6893 channelCount = cnlCount;
6894 }
6895 }
6896 return channelMask;
6897 }
6898
Eric Laurent1e693b52014-07-09 15:03:28 -07006899 uint32_t channelCount = 0;
6900 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6901
6902 // For mixed output and inputs, use max mixer channel count. Do not
6903 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006904 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006905 maxCount = UINT_MAX;
6906 }
6907 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6908 uint32_t cnlCount;
6909 if (mUseInChannelMask) {
6910 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6911 } else {
6912 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6913 }
6914 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6915 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006916 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006917 }
6918 }
6919 return channelMask;
6920}
6921
Andy Hung9a605382014-07-28 16:16:31 -07006922/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006923const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6924 AUDIO_FORMAT_DEFAULT,
6925 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006926 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006927 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006928 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006929 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006930};
6931
6932int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6933 audio_format_t format2)
6934{
6935 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6936 // compressed format and better than any PCM format. This is by design of pickFormat()
6937 if (!audio_is_linear_pcm(format1)) {
6938 if (!audio_is_linear_pcm(format2)) {
6939 return 0;
6940 }
6941 return 1;
6942 }
6943 if (!audio_is_linear_pcm(format2)) {
6944 return -1;
6945 }
6946
6947 int index1 = -1, index2 = -1;
6948 for (size_t i = 0;
6949 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6950 i ++) {
6951 if (sPcmFormatCompareTable[i] == format1) {
6952 index1 = i;
6953 }
6954 if (sPcmFormatCompareTable[i] == format2) {
6955 index2 = i;
6956 }
6957 }
6958 // format1 not found => index1 < 0 => format2 > format1
6959 // format2 not found => index2 < 0 => format2 < format1
6960 return index1 - index2;
6961}
6962
6963audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6964{
6965 // special case for uninitialized dynamic profile
6966 if (mFormats.size() == 1 && mFormats[0] == 0) {
6967 return AUDIO_FORMAT_DEFAULT;
6968 }
6969
6970 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006971 audio_format_t bestFormat =
6972 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6973 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006974 // For mixed output and inputs, use best mixer output format. Do not
6975 // limit format otherwise
6976 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6977 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006978 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006979 bestFormat = AUDIO_FORMAT_INVALID;
6980 }
6981
6982 for (size_t i = 0; i < mFormats.size(); i ++) {
6983 if ((compareFormats(mFormats[i], format) > 0) &&
6984 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6985 format = mFormats[i];
6986 }
6987 }
6988 return format;
6989}
6990
Eric Laurenta121f902014-06-03 13:32:54 -07006991status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6992 int index) const
6993{
6994 if (index < 0 || (size_t)index >= mGains.size()) {
6995 return BAD_VALUE;
6996 }
6997 return mGains[index]->checkConfig(gainConfig);
6998}
6999
Eric Laurent1afeecb2014-05-14 08:52:28 -07007000void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
7001{
7002 const size_t SIZE = 256;
7003 char buffer[SIZE];
7004 String8 result;
7005
7006 if (mName.size() != 0) {
7007 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
7008 result.append(buffer);
7009 }
7010
7011 if (mSamplingRates.size() != 0) {
7012 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
7013 result.append(buffer);
7014 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007015 if (i == 0 && mSamplingRates[i] == 0) {
7016 snprintf(buffer, SIZE, "Dynamic");
7017 } else {
7018 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7019 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007020 result.append(buffer);
7021 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7022 }
7023 result.append("\n");
7024 }
7025
7026 if (mChannelMasks.size() != 0) {
7027 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7028 result.append(buffer);
7029 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007030 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7031
7032 if (i == 0 && mChannelMasks[i] == 0) {
7033 snprintf(buffer, SIZE, "Dynamic");
7034 } else {
7035 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7036 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007037 result.append(buffer);
7038 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7039 }
7040 result.append("\n");
7041 }
7042
7043 if (mFormats.size() != 0) {
7044 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7045 result.append(buffer);
7046 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007047 const char *formatStr = enumToString(sFormatNameToEnumTable,
7048 ARRAY_SIZE(sFormatNameToEnumTable),
7049 mFormats[i]);
7050 if (i == 0 && strcmp(formatStr, "") == 0) {
7051 snprintf(buffer, SIZE, "Dynamic");
7052 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07007053 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07007054 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007055 result.append(buffer);
7056 result.append(i == (mFormats.size() - 1) ? "" : ", ");
7057 }
7058 result.append("\n");
7059 }
7060 write(fd, result.string(), result.size());
7061 if (mGains.size() != 0) {
7062 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7063 write(fd, buffer, strlen(buffer) + 1);
7064 result.append(buffer);
7065 for (size_t i = 0; i < mGains.size(); i++) {
7066 mGains[i]->dump(fd, spaces + 2, i);
7067 }
7068 }
7069}
7070
7071// --- AudioGain class implementation
7072
Eric Laurenta121f902014-06-03 13:32:54 -07007073AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07007074{
Eric Laurenta121f902014-06-03 13:32:54 -07007075 mIndex = index;
7076 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007077 memset(&mGain, 0, sizeof(struct audio_gain));
7078}
7079
Eric Laurenta121f902014-06-03 13:32:54 -07007080void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7081{
7082 config->index = mIndex;
7083 config->mode = mGain.mode;
7084 config->channel_mask = mGain.channel_mask;
7085 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7086 config->values[0] = mGain.default_value;
7087 } else {
7088 uint32_t numValues;
7089 if (mUseInChannelMask) {
7090 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7091 } else {
7092 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7093 }
7094 for (size_t i = 0; i < numValues; i++) {
7095 config->values[i] = mGain.default_value;
7096 }
7097 }
7098 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7099 config->ramp_duration_ms = mGain.min_ramp_ms;
7100 }
7101}
7102
7103status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7104{
7105 if ((config->mode & ~mGain.mode) != 0) {
7106 return BAD_VALUE;
7107 }
7108 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7109 if ((config->values[0] < mGain.min_value) ||
7110 (config->values[0] > mGain.max_value)) {
7111 return BAD_VALUE;
7112 }
7113 } else {
7114 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7115 return BAD_VALUE;
7116 }
7117 uint32_t numValues;
7118 if (mUseInChannelMask) {
7119 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7120 } else {
7121 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7122 }
7123 for (size_t i = 0; i < numValues; i++) {
7124 if ((config->values[i] < mGain.min_value) ||
7125 (config->values[i] > mGain.max_value)) {
7126 return BAD_VALUE;
7127 }
7128 }
7129 }
7130 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7131 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7132 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7133 return BAD_VALUE;
7134 }
7135 }
7136 return NO_ERROR;
7137}
7138
Eric Laurent1afeecb2014-05-14 08:52:28 -07007139void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7140{
7141 const size_t SIZE = 256;
7142 char buffer[SIZE];
7143 String8 result;
7144
7145 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7146 result.append(buffer);
7147 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7148 result.append(buffer);
7149 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7150 result.append(buffer);
7151 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7152 result.append(buffer);
7153 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7154 result.append(buffer);
7155 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7156 result.append(buffer);
7157 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7158 result.append(buffer);
7159 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7160 result.append(buffer);
7161 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7162 result.append(buffer);
7163
7164 write(fd, result.string(), result.size());
7165}
7166
Eric Laurent1f2f2232014-06-02 12:01:23 -07007167// --- AudioPortConfig class implementation
7168
7169AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7170{
7171 mSamplingRate = 0;
7172 mChannelMask = AUDIO_CHANNEL_NONE;
7173 mFormat = AUDIO_FORMAT_INVALID;
7174 mGain.index = -1;
7175}
7176
Eric Laurenta121f902014-06-03 13:32:54 -07007177status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7178 const struct audio_port_config *config,
7179 struct audio_port_config *backupConfig)
7180{
7181 struct audio_port_config localBackupConfig;
7182 status_t status = NO_ERROR;
7183
7184 localBackupConfig.config_mask = config->config_mask;
7185 toAudioPortConfig(&localBackupConfig);
7186
Marco Nelissen961ec212014-08-25 15:58:39 -07007187 sp<AudioPort> audioport = getAudioPort();
7188 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007189 status = NO_INIT;
7190 goto exit;
7191 }
7192 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007193 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007194 if (status != NO_ERROR) {
7195 goto exit;
7196 }
7197 mSamplingRate = config->sample_rate;
7198 }
7199 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007200 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007201 if (status != NO_ERROR) {
7202 goto exit;
7203 }
7204 mChannelMask = config->channel_mask;
7205 }
7206 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007207 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007208 if (status != NO_ERROR) {
7209 goto exit;
7210 }
7211 mFormat = config->format;
7212 }
7213 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007214 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007215 if (status != NO_ERROR) {
7216 goto exit;
7217 }
7218 mGain = config->gain;
7219 }
7220
7221exit:
7222 if (status != NO_ERROR) {
7223 applyAudioPortConfig(&localBackupConfig);
7224 }
7225 if (backupConfig != NULL) {
7226 *backupConfig = localBackupConfig;
7227 }
7228 return status;
7229}
7230
Eric Laurent1f2f2232014-06-02 12:01:23 -07007231void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7232 struct audio_port_config *dstConfig,
7233 const struct audio_port_config *srcConfig) const
7234{
7235 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7236 dstConfig->sample_rate = mSamplingRate;
7237 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7238 dstConfig->sample_rate = srcConfig->sample_rate;
7239 }
7240 } else {
7241 dstConfig->sample_rate = 0;
7242 }
7243 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7244 dstConfig->channel_mask = mChannelMask;
7245 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7246 dstConfig->channel_mask = srcConfig->channel_mask;
7247 }
7248 } else {
7249 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7250 }
7251 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7252 dstConfig->format = mFormat;
7253 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7254 dstConfig->format = srcConfig->format;
7255 }
7256 } else {
7257 dstConfig->format = AUDIO_FORMAT_INVALID;
7258 }
7259 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7260 dstConfig->gain = mGain;
7261 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7262 dstConfig->gain = srcConfig->gain;
7263 }
7264 } else {
7265 dstConfig->gain.index = -1;
7266 }
7267 if (dstConfig->gain.index != -1) {
7268 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7269 } else {
7270 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7271 }
7272}
7273
Eric Laurent1c333e22014-05-20 10:48:17 -07007274// --- IOProfile class implementation
7275
Eric Laurent1afeecb2014-05-14 08:52:28 -07007276AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007277 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007278 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007279{
7280}
7281
Eric Laurente0720872014-03-11 09:30:41 -07007282AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007283{
7284}
7285
7286// checks if the IO profile is compatible with specified parameters.
7287// Sampling rate, format and channel mask must be specified in order to
7288// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007289bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007290 String8 address,
7291 uint32_t samplingRate,
7292 uint32_t *updatedSamplingRate,
7293 audio_format_t format,
7294 audio_channel_mask_t channelMask,
7295 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007296{
Glenn Kastencbd48022014-07-24 13:46:44 -07007297 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7298 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7299 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007300
Eric Laurent275e8e92014-11-30 15:14:47 -08007301 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007302 return false;
7303 }
7304
7305 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007306 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007307 }
7308 uint32_t myUpdatedSamplingRate = samplingRate;
7309 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007310 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007311 }
7312 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7313 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007314 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007315 }
7316
7317 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7318 return false;
7319 }
7320
7321 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7322 checkExactChannelMask(channelMask) != NO_ERROR)) {
7323 return false;
7324 }
7325 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7326 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7327 return false;
7328 }
7329
7330 if (isPlaybackThread && (mFlags & flags) != flags) {
7331 return false;
7332 }
7333 // The only input flag that is allowed to be different is the fast flag.
7334 // An existing fast stream is compatible with a normal track request.
7335 // An existing normal stream is compatible with a fast track request,
7336 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007337 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007338 ~AUDIO_INPUT_FLAG_FAST)) {
7339 return false;
7340 }
7341
7342 if (updatedSamplingRate != NULL) {
7343 *updatedSamplingRate = myUpdatedSamplingRate;
7344 }
7345 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007346}
7347
Eric Laurente0720872014-03-11 09:30:41 -07007348void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007349{
7350 const size_t SIZE = 256;
7351 char buffer[SIZE];
7352 String8 result;
7353
Eric Laurent1afeecb2014-05-14 08:52:28 -07007354 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007355
Eric Laurente552edb2014-03-10 17:42:56 -07007356 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7357 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007358 snprintf(buffer, SIZE, " - devices:\n");
7359 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007360 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007361 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7362 mSupportedDevices[i]->dump(fd, 6, i);
7363 }
Eric Laurente552edb2014-03-10 17:42:56 -07007364}
7365
Eric Laurentd4692962014-05-05 18:13:44 -07007366void AudioPolicyManager::IOProfile::log()
7367{
7368 const size_t SIZE = 256;
7369 char buffer[SIZE];
7370 String8 result;
7371
7372 ALOGV(" - sampling rates: ");
7373 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7374 ALOGV(" %d", mSamplingRates[i]);
7375 }
7376
7377 ALOGV(" - channel masks: ");
7378 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7379 ALOGV(" 0x%04x", mChannelMasks[i]);
7380 }
7381
7382 ALOGV(" - formats: ");
7383 for (size_t i = 0; i < mFormats.size(); i++) {
7384 ALOGV(" 0x%08x", mFormats[i]);
7385 }
7386
7387 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7388 ALOGV(" - flags: 0x%04x\n", mFlags);
7389}
7390
7391
Eric Laurent3a4311c2014-03-17 12:00:47 -07007392// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007393
Eric Laurent1f2f2232014-06-02 12:01:23 -07007394
7395AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7396 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7397 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7398 AUDIO_PORT_ROLE_SOURCE,
7399 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007400 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007401{
Eric Laurenta121f902014-06-03 13:32:54 -07007402 if (mGains.size() > 0) {
7403 mGains[0]->getDefaultConfig(&mGain);
7404 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07007405}
7406
Eric Laurent3a4311c2014-03-17 12:00:47 -07007407bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007408{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007409 // Devices are considered equal if they:
7410 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7411 // - have the same address or one device does not specify the address
7412 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007413 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007414 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007415 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007416 mChannelMask == other->mChannelMask);
7417}
7418
7419void AudioPolicyManager::DeviceVector::refreshTypes()
7420{
Eric Laurent1c333e22014-05-20 10:48:17 -07007421 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007422 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007423 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007424 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007425 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007426}
7427
7428ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7429{
7430 for(size_t i = 0; i < size(); i++) {
7431 if (item->equals(itemAt(i))) {
7432 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007433 }
7434 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007435 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007436}
7437
Eric Laurent3a4311c2014-03-17 12:00:47 -07007438ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007439{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007440 ssize_t ret = indexOf(item);
7441
7442 if (ret < 0) {
7443 ret = SortedVector::add(item);
7444 if (ret >= 0) {
7445 refreshTypes();
7446 }
7447 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007448 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007449 ret = -1;
7450 }
7451 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007452}
7453
Eric Laurent3a4311c2014-03-17 12:00:47 -07007454ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7455{
7456 size_t i;
7457 ssize_t ret = indexOf(item);
7458
7459 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007460 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007461 } else {
7462 ret = SortedVector::removeAt(ret);
7463 if (ret >= 0) {
7464 refreshTypes();
7465 }
7466 }
7467 return ret;
7468}
7469
7470void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7471{
7472 DeviceVector deviceList;
7473
7474 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7475 types &= ~role_bit;
7476
7477 while (types) {
7478 uint32_t i = 31 - __builtin_clz(types);
7479 uint32_t type = 1 << i;
7480 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007481 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007482 }
7483}
7484
Eric Laurent1afeecb2014-05-14 08:52:28 -07007485void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7486 const DeviceVector& declaredDevices)
7487{
7488 char *devName = strtok(name, "|");
7489 while (devName != NULL) {
7490 if (strlen(devName) != 0) {
7491 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7492 ARRAY_SIZE(sDeviceNameToEnumTable),
7493 devName);
7494 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007495 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007496 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7497 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007498 dev->mAddress = String8("0");
7499 }
7500 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007501 } else {
7502 sp<DeviceDescriptor> deviceDesc =
7503 declaredDevices.getDeviceFromName(String8(devName));
7504 if (deviceDesc != 0) {
7505 add(deviceDesc);
7506 }
7507 }
7508 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007509 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007510 }
7511}
7512
Eric Laurent1c333e22014-05-20 10:48:17 -07007513sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7514 audio_devices_t type, String8 address) const
7515{
7516 sp<DeviceDescriptor> device;
7517 for (size_t i = 0; i < size(); i++) {
7518 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007519 if (address == "" || itemAt(i)->mAddress == address) {
7520 device = itemAt(i);
7521 if (itemAt(i)->mAddress == address) {
7522 break;
7523 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007524 }
7525 }
7526 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007527 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007528 type, address.string(), device.get());
7529 return device;
7530}
7531
Eric Laurent6a94d692014-05-20 11:18:06 -07007532sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7533 audio_port_handle_t id) const
7534{
7535 sp<DeviceDescriptor> device;
7536 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007537 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007538 if (itemAt(i)->mId == id) {
7539 device = itemAt(i);
7540 break;
7541 }
7542 }
7543 return device;
7544}
7545
Eric Laurent1c333e22014-05-20 10:48:17 -07007546AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7547 audio_devices_t type) const
7548{
7549 DeviceVector devices;
7550 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7551 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7552 devices.add(itemAt(i));
7553 type &= ~itemAt(i)->mDeviceType;
7554 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7555 itemAt(i)->mDeviceType, itemAt(i).get());
7556 }
7557 }
7558 return devices;
7559}
7560
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007561AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7562 audio_devices_t type, String8 address) const
7563{
7564 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007565 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007566 if (itemAt(i)->mDeviceType == type) {
7567 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007568 devices.add(itemAt(i));
7569 }
7570 }
7571 }
7572 return devices;
7573}
7574
Eric Laurent1afeecb2014-05-14 08:52:28 -07007575sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7576 const String8& name) const
7577{
7578 sp<DeviceDescriptor> device;
7579 for (size_t i = 0; i < size(); i++) {
7580 if (itemAt(i)->mName == name) {
7581 device = itemAt(i);
7582 break;
7583 }
7584 }
7585 return device;
7586}
7587
Eric Laurent6a94d692014-05-20 11:18:06 -07007588void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7589 struct audio_port_config *dstConfig,
7590 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007591{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007592 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7593 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007594 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007595 }
7596
7597 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7598
Eric Laurent6a94d692014-05-20 11:18:06 -07007599 dstConfig->id = mId;
7600 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007601 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007602 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007603 dstConfig->ext.device.type = mDeviceType;
7604 dstConfig->ext.device.hw_module = mModule->mHandle;
7605 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007606}
7607
7608void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7609{
Eric Laurent83b88082014-06-20 18:31:16 -07007610 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007611 AudioPort::toAudioPort(port);
7612 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007613 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007614 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007615 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007616 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7617}
7618
Eric Laurent1afeecb2014-05-14 08:52:28 -07007619status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007620{
7621 const size_t SIZE = 256;
7622 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007623 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007624
Eric Laurent1afeecb2014-05-14 08:52:28 -07007625 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7626 result.append(buffer);
7627 if (mId != 0) {
7628 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7629 result.append(buffer);
7630 }
7631 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7632 enumToString(sDeviceNameToEnumTable,
7633 ARRAY_SIZE(sDeviceNameToEnumTable),
7634 mDeviceType));
7635 result.append(buffer);
7636 if (mAddress.size() != 0) {
7637 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7638 result.append(buffer);
7639 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007640 write(fd, result.string(), result.size());
7641 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007642
7643 return NO_ERROR;
7644}
7645
Eric Laurent4d416952014-08-10 14:07:09 -07007646status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7647{
7648 const size_t SIZE = 256;
7649 char buffer[SIZE];
7650 String8 result;
7651
7652
7653 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7654 result.append(buffer);
7655 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7656 result.append(buffer);
7657 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7658 result.append(buffer);
7659 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7660 result.append(buffer);
7661 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7662 result.append(buffer);
7663 for (size_t i = 0; i < mPatch.num_sources; i++) {
7664 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7665 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7666 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7667 ARRAY_SIZE(sDeviceNameToEnumTable),
7668 mPatch.sources[i].ext.device.type));
7669 } else {
7670 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7671 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7672 }
7673 result.append(buffer);
7674 }
7675 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7676 result.append(buffer);
7677 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7678 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7679 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7680 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7681 ARRAY_SIZE(sDeviceNameToEnumTable),
7682 mPatch.sinks[i].ext.device.type));
7683 } else {
7684 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7685 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7686 }
7687 result.append(buffer);
7688 }
7689
7690 write(fd, result.string(), result.size());
7691 return NO_ERROR;
7692}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007693
7694// --- audio_policy.conf file parsing
7695
Eric Laurent5dbe4712014-09-19 19:04:57 -07007696uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007697{
7698 uint32_t flag = 0;
7699
7700 // it is OK to cast name to non const here as we are not going to use it after
7701 // strtok() modifies it
7702 char *flagName = strtok(name, "|");
7703 while (flagName != NULL) {
7704 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007705 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7706 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007707 flagName);
7708 }
7709 flagName = strtok(NULL, "|");
7710 }
7711 //force direct flag if offload flag is set: offloading implies a direct output stream
7712 // and all common behaviors are driven by checking only the direct flag
7713 // this should normally be set appropriately in the policy configuration file
7714 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7715 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7716 }
7717
Eric Laurent5dbe4712014-09-19 19:04:57 -07007718 return flag;
7719}
7720
7721uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7722{
7723 uint32_t flag = 0;
7724
7725 // it is OK to cast name to non const here as we are not going to use it after
7726 // strtok() modifies it
7727 char *flagName = strtok(name, "|");
7728 while (flagName != NULL) {
7729 if (strlen(flagName) != 0) {
7730 flag |= stringToEnum(sInputFlagNameToEnumTable,
7731 ARRAY_SIZE(sInputFlagNameToEnumTable),
7732 flagName);
7733 }
7734 flagName = strtok(NULL, "|");
7735 }
7736 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007737}
7738
Eric Laurente0720872014-03-11 09:30:41 -07007739audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007740{
7741 uint32_t device = 0;
7742
7743 char *devName = strtok(name, "|");
7744 while (devName != NULL) {
7745 if (strlen(devName) != 0) {
7746 device |= stringToEnum(sDeviceNameToEnumTable,
7747 ARRAY_SIZE(sDeviceNameToEnumTable),
7748 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007749 }
Eric Laurente552edb2014-03-10 17:42:56 -07007750 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007751 }
Eric Laurente552edb2014-03-10 17:42:56 -07007752 return device;
7753}
7754
Eric Laurente0720872014-03-11 09:30:41 -07007755void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007756{
Eric Laurente552edb2014-03-10 17:42:56 -07007757 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007758 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007759 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007760
Eric Laurent1afeecb2014-05-14 08:52:28 -07007761 node = config_find(root, DEVICES_TAG);
7762 if (node != NULL) {
7763 node = node->first_child;
7764 while (node) {
7765 ALOGV("loadHwModule() loading device %s", node->name);
7766 status_t tmpStatus = module->loadDevice(node);
7767 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7768 status = tmpStatus;
7769 }
7770 node = node->next;
7771 }
7772 }
7773 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007774 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007775 node = node->first_child;
7776 while (node) {
7777 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007778 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007779 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7780 status = tmpStatus;
7781 }
7782 node = node->next;
7783 }
7784 }
7785 node = config_find(root, INPUTS_TAG);
7786 if (node != NULL) {
7787 node = node->first_child;
7788 while (node) {
7789 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007790 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007791 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7792 status = tmpStatus;
7793 }
7794 node = node->next;
7795 }
7796 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007797 loadGlobalConfig(root, module);
7798
Eric Laurente552edb2014-03-10 17:42:56 -07007799 if (status == NO_ERROR) {
7800 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007801 }
7802}
7803
Eric Laurente0720872014-03-11 09:30:41 -07007804void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007805{
7806 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7807 if (node == NULL) {
7808 return;
7809 }
7810
7811 node = node->first_child;
7812 while (node) {
7813 ALOGV("loadHwModules() loading module %s", node->name);
7814 loadHwModule(node);
7815 node = node->next;
7816 }
7817}
7818
Eric Laurent1f2f2232014-06-02 12:01:23 -07007819void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007820{
7821 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007822
Eric Laurente552edb2014-03-10 17:42:56 -07007823 if (node == NULL) {
7824 return;
7825 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007826 DeviceVector declaredDevices;
7827 if (module != NULL) {
7828 declaredDevices = module->mDeclaredDevices;
7829 }
7830
Eric Laurente552edb2014-03-10 17:42:56 -07007831 node = node->first_child;
7832 while (node) {
7833 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007834 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7835 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007836 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7837 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007838 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007839 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007840 ARRAY_SIZE(sDeviceNameToEnumTable),
7841 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007842 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007843 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007844 } else {
7845 ALOGW("loadGlobalConfig() default device not specified");
7846 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007847 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007848 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007849 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7850 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007851 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007852 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7853 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7854 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007855 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7856 uint32_t major, minor;
7857 sscanf((char *)node->value, "%u.%u", &major, &minor);
7858 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7859 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7860 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007861 }
7862 node = node->next;
7863 }
7864}
7865
Eric Laurente0720872014-03-11 09:30:41 -07007866status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007867{
7868 cnode *root;
7869 char *data;
7870
7871 data = (char *)load_file(path, NULL);
7872 if (data == NULL) {
7873 return -ENODEV;
7874 }
7875 root = config_node("", "");
7876 config_load(root, data);
7877
Eric Laurente552edb2014-03-10 17:42:56 -07007878 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007879 // legacy audio_policy.conf files have one global_configuration section
7880 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007881 config_free(root);
7882 free(root);
7883 free(data);
7884
7885 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7886
7887 return NO_ERROR;
7888}
7889
Eric Laurente0720872014-03-11 09:30:41 -07007890void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007891{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007892 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007893 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007894 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7895 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007896 mAvailableOutputDevices.add(mDefaultOutputDevice);
7897 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007898
7899 module = new HwModule("primary");
7900
Eric Laurent1afeecb2014-05-14 08:52:28 -07007901 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007902 profile->mSamplingRates.add(44100);
7903 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7904 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007905 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007906 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7907 module->mOutputProfiles.add(profile);
7908
Eric Laurent1afeecb2014-05-14 08:52:28 -07007909 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007910 profile->mSamplingRates.add(8000);
7911 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7912 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007913 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007914 module->mInputProfiles.add(profile);
7915
7916 mHwModules.add(module);
7917}
7918
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007919audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7920{
7921 // flags to stream type mapping
7922 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7923 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7924 }
7925 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7926 return AUDIO_STREAM_BLUETOOTH_SCO;
7927 }
7928
7929 // usage to stream type mapping
7930 switch (attr->usage) {
7931 case AUDIO_USAGE_MEDIA:
7932 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007933 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7934 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007935 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007936 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7937 return AUDIO_STREAM_ALARM;
7938 }
7939 if (isStreamActive(AUDIO_STREAM_RING)) {
7940 return AUDIO_STREAM_RING;
7941 }
7942 if (isInCall()) {
7943 return AUDIO_STREAM_VOICE_CALL;
7944 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08007945 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007946 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7947 return AUDIO_STREAM_SYSTEM;
7948 case AUDIO_USAGE_VOICE_COMMUNICATION:
7949 return AUDIO_STREAM_VOICE_CALL;
7950
7951 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7952 return AUDIO_STREAM_DTMF;
7953
7954 case AUDIO_USAGE_ALARM:
7955 return AUDIO_STREAM_ALARM;
7956 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7957 return AUDIO_STREAM_RING;
7958
7959 case AUDIO_USAGE_NOTIFICATION:
7960 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7961 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7962 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7963 case AUDIO_USAGE_NOTIFICATION_EVENT:
7964 return AUDIO_STREAM_NOTIFICATION;
7965
7966 case AUDIO_USAGE_UNKNOWN:
7967 default:
7968 return AUDIO_STREAM_MUSIC;
7969 }
7970}
Eric Laurente83b55d2014-11-14 10:06:21 -08007971
7972bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
7973 // has flags that map to a strategy?
7974 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7975 return true;
7976 }
7977
7978 // has known usage?
7979 switch (paa->usage) {
7980 case AUDIO_USAGE_UNKNOWN:
7981 case AUDIO_USAGE_MEDIA:
7982 case AUDIO_USAGE_VOICE_COMMUNICATION:
7983 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7984 case AUDIO_USAGE_ALARM:
7985 case AUDIO_USAGE_NOTIFICATION:
7986 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7987 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7988 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7989 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7990 case AUDIO_USAGE_NOTIFICATION_EVENT:
7991 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7992 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7993 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7994 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007995 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08007996 break;
7997 default:
7998 return false;
7999 }
8000 return true;
8001}
8002
Eric Laurente552edb2014-03-10 17:42:56 -07008003}; // namespace android