blob: 8d1b3bb07bdef4768ab83f85678f480d27c0228b [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
Hochi Huang327cb702014-09-21 09:47:31 +080029#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
Eric Laurente552edb2014-03-10 17:42:56 -070030// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070047#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070048#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070049#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurent3b73df72014-03-11 09:06:29 -070051namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070052
53// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070054// Definitions for audio_policy.conf file parsing
55// ----------------------------------------------------------------------------
56
57struct StringToEnum {
58 const char *name;
59 uint32_t value;
60};
61
62#define STRING_TO_ENUM(string) { #string, string }
63#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64
65const StringToEnum sDeviceNameToEnumTable[] = {
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070069 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070081 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070087 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
91 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070092 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050093 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070094 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
98 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700108 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
110 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
111 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700112 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900113 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700114};
115
Eric Laurent5dbe4712014-09-19 19:04:57 -0700116const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700123 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700124};
125
Eric Laurent5dbe4712014-09-19 19:04:57 -0700126const StringToEnum sInputFlagNameToEnumTable[] = {
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
128 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
129};
130
Eric Laurent3a4311c2014-03-17 12:00:47 -0700131const StringToEnum sFormatNameToEnumTable[] = {
132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
137 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
138 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
149 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
152 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
153 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
154 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
155 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156};
157
158const StringToEnum sOutChannelsNameToEnumTable[] = {
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
163 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
164};
165
166const StringToEnum sInChannelsNameToEnumTable[] = {
167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
169 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
170};
171
Eric Laurent1afeecb2014-05-14 08:52:28 -0700172const StringToEnum sGainModeNameToEnumTable[] = {
173 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
174 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
175 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
176};
177
Eric Laurent3a4311c2014-03-17 12:00:47 -0700178
179uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
180 size_t size,
181 const char *name)
182{
183 for (size_t i = 0; i < size; i++) {
184 if (strcmp(table[i].name, name) == 0) {
185 ALOGV("stringToEnum() found %s", table[i].name);
186 return table[i].value;
187 }
188 }
189 return 0;
190}
191
192const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
193 size_t size,
194 uint32_t value)
195{
196 for (size_t i = 0; i < size; i++) {
197 if (table[i].value == value) {
198 return table[i].name;
199 }
200 }
201 return "";
202}
203
204bool AudioPolicyManager::stringToBool(const char *value)
205{
206 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
207}
208
209
210// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700211// AudioPolicyInterface implementation
212// ----------------------------------------------------------------------------
213
Eric Laurente0720872014-03-11 09:30:41 -0700214status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700216 const char *device_address)
217{
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800218 return setDeviceConnectionStateInt(device, state, device_address);
219}
220
221status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
222 audio_policy_dev_state_t state,
223 const char *device_address)
224{
Eric Laurent22226012014-08-01 17:00:54 -0700225 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700226 // handle legacy remote submix case where the address was not always specified
227 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
228 address = String8("0");
229 }
Eric Laurente552edb2014-03-10 17:42:56 -0700230
Eric Laurent22226012014-08-01 17:00:54 -0700231 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
232 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700233
234 // connect/disconnect only 1 device at a time
235 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
236
Eric Laurente552edb2014-03-10 17:42:56 -0700237 // handle output devices
238 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700239 SortedVector <audio_io_handle_t> outputs;
240
Eric Laurent1afeecb2014-05-14 08:52:28 -0700241 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
242 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700243 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
244
Eric Laurente552edb2014-03-10 17:42:56 -0700245 // save a copy of the opened output descriptors before any output is opened or closed
246 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
247 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700248 switch (state)
249 {
250 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700251 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700253 ALOGW("setDeviceConnectionState() device already connected: %x", device);
254 return INVALID_OPERATION;
255 }
256 ALOGV("setDeviceConnectionState() connecting device %x", device);
257
Eric Laurente552edb2014-03-10 17:42:56 -0700258 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700259 index = mAvailableOutputDevices.add(devDesc);
260 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700261 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700262 if (module == 0) {
263 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
264 device);
265 mAvailableOutputDevices.remove(devDesc);
266 return INVALID_OPERATION;
267 }
268 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700269 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700270 } else {
271 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700272 }
273
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700274 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700275 mAvailableOutputDevices.remove(devDesc);
276 return INVALID_OPERATION;
277 }
278 // outputs should never be empty here
279 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
280 "checkOutputsForDevice() returned no outputs but status OK");
281 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
282 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700283 break;
284 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700285 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700286 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700287 ALOGW("setDeviceConnectionState() device not connected: %x", device);
288 return INVALID_OPERATION;
289 }
290
Paul McLean5c477aa2014-08-20 16:47:57 -0700291 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
292
293 // Set Disconnect to HALs
294 AudioParameter param = AudioParameter(address);
295 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
296 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
297
Eric Laurente552edb2014-03-10 17:42:56 -0700298 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700300
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700301 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700302 } break;
303
304 default:
305 ALOGE("setDeviceConnectionState() invalid state: %x", state);
306 return BAD_VALUE;
307 }
308
Eric Laurent3a4311c2014-03-17 12:00:47 -0700309 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
310 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700311 checkA2dpSuspend();
312 checkOutputForAllStrategies();
313 // outputs must be closed after checkOutputForAllStrategies() is executed
314 if (!outputs.isEmpty()) {
315 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700316 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700317 // close unused outputs after device disconnection or direct outputs that have been
318 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700319 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700320 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
321 (desc->mDirectOpenCount == 0))) {
322 closeOutput(outputs[i]);
323 }
324 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 // check again after closing A2DP output to reset mA2dpSuspended if needed
326 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700327 }
328
329 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700330 if (mPhoneState == AUDIO_MODE_IN_CALL) {
331 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
332 updateCallRouting(newDevice);
333 }
Eric Laurente552edb2014-03-10 17:42:56 -0700334 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700335 audio_io_handle_t output = mOutputs.keyAt(i);
336 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
337 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
338 true /*fromCache*/);
339 // do not force device change on duplicated output because if device is 0, it will
340 // also force a device 0 for the two outputs it is duplicated to which may override
341 // a valid device selection on those outputs.
342 bool force = !mOutputs.valueAt(i)->isDuplicated()
343 && (!deviceDistinguishesOnAddress(device)
344 // always force when disconnecting (a non-duplicated device)
345 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
346 setOutputDevice(output, newDevice, force, 0);
347 }
Eric Laurente552edb2014-03-10 17:42:56 -0700348 }
349
Eric Laurent72aa32f2014-05-30 18:51:48 -0700350 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700351 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700352 } // end if is output device
353
Eric Laurente552edb2014-03-10 17:42:56 -0700354 // handle input devices
355 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700356 SortedVector <audio_io_handle_t> inputs;
357
Eric Laurent1afeecb2014-05-14 08:52:28 -0700358 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
359 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700360 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700361 switch (state)
362 {
363 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700364 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700365 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700366 ALOGW("setDeviceConnectionState() device already connected: %d", device);
367 return INVALID_OPERATION;
368 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700369 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700370 if (module == NULL) {
371 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
372 device);
373 return INVALID_OPERATION;
374 }
Eric Laurentd4692962014-05-05 18:13:44 -0700375 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
376 return INVALID_OPERATION;
377 }
378
Eric Laurent3a4311c2014-03-17 12:00:47 -0700379 index = mAvailableInputDevices.add(devDesc);
380 if (index >= 0) {
381 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700382 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700383 } else {
384 return NO_MEMORY;
385 }
Eric Laurentd4692962014-05-05 18:13:44 -0700386 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700387
388 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700389 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700390 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700391 ALOGW("setDeviceConnectionState() device not connected: %d", device);
392 return INVALID_OPERATION;
393 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700394
395 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
396
397 // Set Disconnect to HALs
398 AudioParameter param = AudioParameter(address);
399 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
400 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700403 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700406
407 default:
408 ALOGE("setDeviceConnectionState() invalid state: %x", state);
409 return BAD_VALUE;
410 }
411
Eric Laurentd4692962014-05-05 18:13:44 -0700412 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700413
Eric Laurentc2730ba2014-07-20 15:47:07 -0700414 if (mPhoneState == AUDIO_MODE_IN_CALL) {
415 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
416 updateCallRouting(newDevice);
417 }
418
Eric Laurentb52c1522014-05-20 11:27:36 -0700419 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700420 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700421 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700422
423 ALOGW("setDeviceConnectionState() invalid device: %x", device);
424 return BAD_VALUE;
425}
426
Eric Laurente0720872014-03-11 09:30:41 -0700427audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700428 const char *device_address)
429{
Eric Laurent3b73df72014-03-11 09:06:29 -0700430 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700431 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700432 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700433 // handle legacy remote submix case where the address was not always specified
434 if (deviceDistinguishesOnAddress(device) && (devDesc->mAddress.length() == 0)) {
435 devDesc->mAddress = String8("0");
436 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700437 ssize_t index;
438 DeviceVector *deviceVector;
439
Eric Laurente552edb2014-03-10 17:42:56 -0700440 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700441 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700442 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700443 deviceVector = &mAvailableInputDevices;
444 } else {
445 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
446 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700447 }
448
Eric Laurent3a4311c2014-03-17 12:00:47 -0700449 index = deviceVector->indexOf(devDesc);
450 if (index >= 0) {
451 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
452 } else {
453 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
454 }
Eric Laurente552edb2014-03-10 17:42:56 -0700455}
456
Eric Laurentc2730ba2014-07-20 15:47:07 -0700457void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
458{
459 bool createTxPatch = false;
460 struct audio_patch patch;
461 patch.num_sources = 1;
462 patch.num_sinks = 1;
463 status_t status;
464 audio_patch_handle_t afPatchHandle;
465 DeviceVector deviceList;
466
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800467 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
469
470 // release existing RX patch if any
471 if (mCallRxPatch != 0) {
472 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
473 mCallRxPatch.clear();
474 }
475 // release TX patch if any
476 if (mCallTxPatch != 0) {
477 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
478 mCallTxPatch.clear();
479 }
480
481 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
482 // via setOutputDevice() on primary output.
483 // Otherwise, create two audio patches for TX and RX path.
484 if (availablePrimaryOutputDevices() & rxDevice) {
485 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
486 // If the TX device is also on the primary HW module, setOutputDevice() will take care
487 // of it due to legacy implementation. If not, create a patch.
488 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
489 == AUDIO_DEVICE_NONE) {
490 createTxPatch = true;
491 }
492 } else {
493 // create RX path audio patch
494 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
495 ALOG_ASSERT(!deviceList.isEmpty(),
496 "updateCallRouting() selected device not in output device list");
497 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
498 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
499 ALOG_ASSERT(!deviceList.isEmpty(),
500 "updateCallRouting() no telephony RX device");
501 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
502
503 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
504 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
505
506 // request to reuse existing output stream if one is already opened to reach the RX device
507 SortedVector<audio_io_handle_t> outputs =
508 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700509 audio_io_handle_t output = selectOutput(outputs,
510 AUDIO_OUTPUT_FLAG_NONE,
511 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700512 if (output != AUDIO_IO_HANDLE_NONE) {
513 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
514 ALOG_ASSERT(!outputDesc->isDuplicated(),
515 "updateCallRouting() RX device output is duplicated");
516 outputDesc->toAudioPortConfig(&patch.sources[1]);
517 patch.num_sources = 2;
518 }
519
520 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
521 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
522 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
523 status);
524 if (status == NO_ERROR) {
525 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
526 &patch, mUidCached);
527 mCallRxPatch->mAfPatchHandle = afPatchHandle;
528 mCallRxPatch->mUid = mUidCached;
529 }
530 createTxPatch = true;
531 }
532 if (createTxPatch) {
533
534 struct audio_patch patch;
535 patch.num_sources = 1;
536 patch.num_sinks = 1;
537 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
538 ALOG_ASSERT(!deviceList.isEmpty(),
539 "updateCallRouting() selected device not in input device list");
540 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
541 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
542 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
543 ALOG_ASSERT(!deviceList.isEmpty(),
544 "updateCallRouting() no telephony TX device");
545 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
546 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
547
548 SortedVector<audio_io_handle_t> outputs =
549 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700550 audio_io_handle_t output = selectOutput(outputs,
551 AUDIO_OUTPUT_FLAG_NONE,
552 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700553 // request to reuse existing output stream if one is already opened to reach the TX
554 // path output device
555 if (output != AUDIO_IO_HANDLE_NONE) {
556 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
557 ALOG_ASSERT(!outputDesc->isDuplicated(),
558 "updateCallRouting() RX device output is duplicated");
559 outputDesc->toAudioPortConfig(&patch.sources[1]);
560 patch.num_sources = 2;
561 }
562
563 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
564 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
565 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
566 status);
567 if (status == NO_ERROR) {
568 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
569 &patch, mUidCached);
570 mCallTxPatch->mAfPatchHandle = afPatchHandle;
571 mCallTxPatch->mUid = mUidCached;
572 }
573 }
574}
575
Eric Laurente0720872014-03-11 09:30:41 -0700576void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700577{
578 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700579 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700580 ALOGW("setPhoneState() invalid state %d", state);
581 return;
582 }
583
584 if (state == mPhoneState ) {
585 ALOGW("setPhoneState() setting same state %d", state);
586 return;
587 }
588
589 // if leaving call state, handle special case of active streams
590 // pertaining to sonification strategy see handleIncallSonification()
591 if (isInCall()) {
592 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700593 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800594 if (stream == AUDIO_STREAM_PATCH) {
595 continue;
596 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700597 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700598 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800599
600 // force reevaluating accessibility routing when call starts
601 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700602 }
603
604 // store previous phone state for management of sonification strategy below
605 int oldState = mPhoneState;
606 mPhoneState = state;
607 bool force = false;
608
609 // are we entering or starting a call
610 if (!isStateInCall(oldState) && isStateInCall(state)) {
611 ALOGV(" Entering call in setPhoneState()");
612 // force routing command to audio hardware when starting a call
613 // even if no device change is needed
614 force = true;
615 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
616 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
617 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
618 }
619 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
620 ALOGV(" Exiting call in setPhoneState()");
621 // force routing command to audio hardware when exiting a call
622 // even if no device change is needed
623 force = true;
624 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
625 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
626 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
627 }
628 } else if (isStateInCall(state) && (state != oldState)) {
629 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
630 // force routing command to audio hardware when switching between telephony and VoIP
631 // even if no device change is needed
632 force = true;
633 }
634
635 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700636 checkA2dpSuspend();
637 checkOutputForAllStrategies();
638 updateDevicesAndOutputs();
639
Eric Laurent1f2f2232014-06-02 12:01:23 -0700640 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700641
Eric Laurente552edb2014-03-10 17:42:56 -0700642 int delayMs = 0;
643 if (isStateInCall(state)) {
644 nsecs_t sysTime = systemTime();
645 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700646 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700647 // mute media and sonification strategies and delay device switch by the largest
648 // latency of any output where either strategy is active.
649 // This avoid sending the ring tone or music tail into the earpiece or headset.
650 if ((desc->isStrategyActive(STRATEGY_MEDIA,
651 SONIFICATION_HEADSET_MUSIC_DELAY,
652 sysTime) ||
653 desc->isStrategyActive(STRATEGY_SONIFICATION,
654 SONIFICATION_HEADSET_MUSIC_DELAY,
655 sysTime)) &&
656 (delayMs < (int)desc->mLatency*2)) {
657 delayMs = desc->mLatency*2;
658 }
659 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
660 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
661 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
662 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
663 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
664 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
665 }
666 }
667
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
669 // the device returned is not necessarily reachable via this output
670 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
671 // force routing command to audio hardware when ending call
672 // even if no device change is needed
673 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
674 rxDevice = hwOutputDesc->device();
675 }
Eric Laurente552edb2014-03-10 17:42:56 -0700676
Eric Laurentc2730ba2014-07-20 15:47:07 -0700677 if (state == AUDIO_MODE_IN_CALL) {
678 updateCallRouting(rxDevice, delayMs);
679 } else if (oldState == AUDIO_MODE_IN_CALL) {
680 if (mCallRxPatch != 0) {
681 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
682 mCallRxPatch.clear();
683 }
684 if (mCallTxPatch != 0) {
685 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
686 mCallTxPatch.clear();
687 }
688 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
689 } else {
690 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
691 }
Eric Laurente552edb2014-03-10 17:42:56 -0700692 // if entering in call state, handle special case of active streams
693 // pertaining to sonification strategy see handleIncallSonification()
694 if (isStateInCall(state)) {
695 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700696 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800697 if (stream == AUDIO_STREAM_PATCH) {
698 continue;
699 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700700 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700701 }
702 }
703
704 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700705 if (state == AUDIO_MODE_RINGTONE &&
706 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700707 mLimitRingtoneVolume = true;
708 } else {
709 mLimitRingtoneVolume = false;
710 }
711}
712
Eric Laurente0720872014-03-11 09:30:41 -0700713void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700714 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700715{
716 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
717
718 bool forceVolumeReeval = false;
719 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700720 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
721 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
722 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700723 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
724 return;
725 }
726 forceVolumeReeval = true;
727 mForceUse[usage] = config;
728 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700729 case AUDIO_POLICY_FORCE_FOR_MEDIA:
730 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
731 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
732 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
733 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800734 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700735 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
736 return;
737 }
738 mForceUse[usage] = config;
739 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700740 case AUDIO_POLICY_FORCE_FOR_RECORD:
741 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
742 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700743 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
744 return;
745 }
746 mForceUse[usage] = config;
747 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700748 case AUDIO_POLICY_FORCE_FOR_DOCK:
749 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
750 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
751 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
752 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
753 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700754 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
755 }
756 forceVolumeReeval = true;
757 mForceUse[usage] = config;
758 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700759 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
760 if (config != AUDIO_POLICY_FORCE_NONE &&
761 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700762 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
763 }
764 forceVolumeReeval = true;
765 mForceUse[usage] = config;
766 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900767 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
768 if (config != AUDIO_POLICY_FORCE_NONE &&
769 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
770 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
771 }
772 mForceUse[usage] = config;
773 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700774 default:
775 ALOGW("setForceUse() invalid usage %d", usage);
776 break;
777 }
778
779 // check for device and output changes triggered by new force usage
780 checkA2dpSuspend();
781 checkOutputForAllStrategies();
782 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700783 if (mPhoneState == AUDIO_MODE_IN_CALL) {
784 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
785 updateCallRouting(newDevice);
786 }
Eric Laurente552edb2014-03-10 17:42:56 -0700787 for (size_t i = 0; i < mOutputs.size(); i++) {
788 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700789 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700790 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
791 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
792 }
Eric Laurente552edb2014-03-10 17:42:56 -0700793 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
794 applyStreamVolumes(output, newDevice, 0, true);
795 }
796 }
797
798 audio_io_handle_t activeInput = getActiveInput();
799 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700800 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700801 }
802
803}
804
Eric Laurente0720872014-03-11 09:30:41 -0700805audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700806{
807 return mForceUse[usage];
808}
809
Eric Laurente0720872014-03-11 09:30:41 -0700810void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700811{
812 ALOGV("setSystemProperty() property %s, value %s", property, value);
813}
814
815// Find a direct output profile compatible with the parameters passed, even if the input flags do
816// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700817sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700818 audio_devices_t device,
819 uint32_t samplingRate,
820 audio_format_t format,
821 audio_channel_mask_t channelMask,
822 audio_output_flags_t flags)
823{
824 for (size_t i = 0; i < mHwModules.size(); i++) {
825 if (mHwModules[i]->mHandle == 0) {
826 continue;
827 }
828 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700829 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent275e8e92014-11-30 15:14:47 -0800830 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -0700831 NULL /*updatedSamplingRate*/, format, channelMask,
832 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
833 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700834 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
835 return profile;
836 }
Eric Laurente552edb2014-03-10 17:42:56 -0700837 }
838 }
839 return 0;
840}
841
Eric Laurente0720872014-03-11 09:30:41 -0700842audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700843 uint32_t samplingRate,
844 audio_format_t format,
845 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700846 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700847 const audio_offload_info_t *offloadInfo)
848{
Eric Laurent3b73df72014-03-11 09:06:29 -0700849 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700850 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
851 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
852 device, stream, samplingRate, format, channelMask, flags);
853
Eric Laurente83b55d2014-11-14 10:06:21 -0800854 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
855 stream, samplingRate,format, channelMask,
856 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700857}
858
Eric Laurente83b55d2014-11-14 10:06:21 -0800859status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
860 audio_io_handle_t *output,
861 audio_session_t session,
862 audio_stream_type_t *stream,
863 uint32_t samplingRate,
864 audio_format_t format,
865 audio_channel_mask_t channelMask,
866 audio_output_flags_t flags,
867 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700868{
Eric Laurente83b55d2014-11-14 10:06:21 -0800869 audio_attributes_t attributes;
870 if (attr != NULL) {
871 if (!isValidAttributes(attr)) {
872 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
873 attr->usage, attr->content_type, attr->flags,
874 attr->tags);
875 return BAD_VALUE;
876 }
877 attributes = *attr;
878 } else {
879 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
880 ALOGE("getOutputForAttr(): invalid stream type");
881 return BAD_VALUE;
882 }
883 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700884 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800885
Eric Laurent275e8e92014-11-30 15:14:47 -0800886 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
887 sp<AudioOutputDescriptor> desc;
888 if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) {
889 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
890 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
891 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) ||
892 (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
893 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) {
894 desc = mPolicyMixes[i]->mOutput;
895 break;
896 }
897 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
898 strncmp(attributes.tags + strlen("addr="),
899 mPolicyMixes[i]->mMix.mRegistrationId.string(),
900 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
901 desc = mPolicyMixes[i]->mOutput;
902 break;
903 }
904 }
905 } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) {
906 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE &&
907 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
908 strncmp(attributes.tags + strlen("addr="),
909 mPolicyMixes[i]->mMix.mRegistrationId.string(),
910 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
911 desc = mPolicyMixes[i]->mOutput;
Eric Laurent275e8e92014-11-30 15:14:47 -0800912 }
913 }
914 if (desc != 0) {
915 if (!audio_is_linear_pcm(format)) {
916 return BAD_VALUE;
917 }
Eric Laurentc722f302014-12-10 11:21:49 -0800918 desc->mPolicyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -0800919 *stream = streamTypefromAttributesInt(&attributes);
920 *output = desc->mIoHandle;
921 ALOGV("getOutputForAttr() returns output %d", *output);
922 return NO_ERROR;
923 }
924 }
925 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
926 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
927 return BAD_VALUE;
928 }
929
Eric Laurent93c3d412014-08-01 14:48:35 -0700930 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800931 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700932
Eric Laurente83b55d2014-11-14 10:06:21 -0800933 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700934 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700935
Eric Laurente83b55d2014-11-14 10:06:21 -0800936 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700937 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
938 }
939
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700940 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700941 device, samplingRate, format, channelMask, flags);
942
Eric Laurente83b55d2014-11-14 10:06:21 -0800943 *stream = streamTypefromAttributesInt(&attributes);
944 *output = getOutputForDevice(device, session, *stream,
945 samplingRate, format, channelMask,
946 flags, offloadInfo);
947 if (*output == AUDIO_IO_HANDLE_NONE) {
948 return INVALID_OPERATION;
949 }
950 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700951}
952
953audio_io_handle_t AudioPolicyManager::getOutputForDevice(
954 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800955 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700956 audio_stream_type_t stream,
957 uint32_t samplingRate,
958 audio_format_t format,
959 audio_channel_mask_t channelMask,
960 audio_output_flags_t flags,
961 const audio_offload_info_t *offloadInfo)
962{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700963 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700964 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700965 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700966
Eric Laurente552edb2014-03-10 17:42:56 -0700967#ifdef AUDIO_POLICY_TEST
968 if (mCurOutput != 0) {
969 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
970 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
971
972 if (mTestOutputs[mCurOutput] == 0) {
973 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700974 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700975 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700976 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700977 outputDesc->mFlags =
978 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700979 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700980 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
981 config.sample_rate = mTestSamplingRate;
982 config.channel_mask = mTestChannels;
983 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700984 if (offloadInfo != NULL) {
985 config.offload_info = *offloadInfo;
986 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700987 status = mpClientInterface->openOutput(0,
988 &mTestOutputs[mCurOutput],
989 &config,
990 &outputDesc->mDevice,
991 String8(""),
992 &outputDesc->mLatency,
993 outputDesc->mFlags);
994 if (status == NO_ERROR) {
995 outputDesc->mSamplingRate = config.sample_rate;
996 outputDesc->mFormat = config.format;
997 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700998 AudioParameter outputCmd = AudioParameter();
999 outputCmd.addInt(String8("set_id"),mCurOutput);
1000 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
1001 addOutput(mTestOutputs[mCurOutput], outputDesc);
1002 }
1003 }
1004 return mTestOutputs[mCurOutput];
1005 }
1006#endif //AUDIO_POLICY_TEST
1007
1008 // open a direct output if required by specified parameters
1009 //force direct flag if offload flag is set: offloading implies a direct output stream
1010 // and all common behaviors are driven by checking only the direct flag
1011 // this should normally be set appropriately in the policy configuration file
1012 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001013 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001014 }
Eric Laurent93c3d412014-08-01 14:48:35 -07001015 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1016 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1017 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001018 // only allow deep buffering for music stream type
1019 if (stream != AUDIO_STREAM_MUSIC) {
1020 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1021 }
Eric Laurente552edb2014-03-10 17:42:56 -07001022
Eric Laurentb732cf52014-09-24 19:08:21 -07001023 sp<IOProfile> profile;
1024
1025 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001026 // and not explicitly requested
1027 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1028 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -07001029 audio_channel_count_from_out_mask(channelMask) <= 2) {
1030 goto non_direct_output;
1031 }
1032
Eric Laurente552edb2014-03-10 17:42:56 -07001033 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1034 // creating an offloaded track and tearing it down immediately after start when audioflinger
1035 // detects there is an active non offloadable effect.
1036 // FIXME: We should check the audio session here but we do not have it in this context.
1037 // This may prevent offloading in rare situations where effects are left active by apps
1038 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001039
Eric Laurente552edb2014-03-10 17:42:56 -07001040 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1041 !isNonOffloadableEffectEnabled()) {
1042 profile = getProfileForDirectOutput(device,
1043 samplingRate,
1044 format,
1045 channelMask,
1046 (audio_output_flags_t)flags);
1047 }
1048
Eric Laurent1c333e22014-05-20 10:48:17 -07001049 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001050 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -07001051
1052 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001053 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001054 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1055 outputDesc = desc;
1056 // reuse direct output if currently open and configured with same parameters
1057 if ((samplingRate == outputDesc->mSamplingRate) &&
1058 (format == outputDesc->mFormat) &&
1059 (channelMask == outputDesc->mChannelMask)) {
1060 outputDesc->mDirectOpenCount++;
1061 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1062 return mOutputs.keyAt(i);
1063 }
1064 }
1065 }
1066 // close direct output if currently open and configured with different parameters
1067 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001068 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001069 }
1070 outputDesc = new AudioOutputDescriptor(profile);
1071 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001072 outputDesc->mLatency = 0;
1073 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001074 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1075 config.sample_rate = samplingRate;
1076 config.channel_mask = channelMask;
1077 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001078 if (offloadInfo != NULL) {
1079 config.offload_info = *offloadInfo;
1080 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001081 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1082 &output,
1083 &config,
1084 &outputDesc->mDevice,
1085 String8(""),
1086 &outputDesc->mLatency,
1087 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001088
1089 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001090 if (status != NO_ERROR ||
1091 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1092 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1093 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001094 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1095 "format %d %d, channelMask %04x %04x", output, samplingRate,
1096 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1097 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001098 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001099 mpClientInterface->closeOutput(output);
1100 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001101 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001102 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001103 outputDesc->mSamplingRate = config.sample_rate;
1104 outputDesc->mChannelMask = config.channel_mask;
1105 outputDesc->mFormat = config.format;
1106 outputDesc->mRefCount[stream] = 0;
1107 outputDesc->mStopTime[stream] = 0;
1108 outputDesc->mDirectOpenCount = 1;
1109
Eric Laurente552edb2014-03-10 17:42:56 -07001110 audio_io_handle_t srcOutput = getOutputForEffect();
1111 addOutput(output, outputDesc);
1112 audio_io_handle_t dstOutput = getOutputForEffect();
1113 if (dstOutput == output) {
1114 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1115 }
1116 mPreviousOutputs = mOutputs;
1117 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001118 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001119 return output;
1120 }
1121
Eric Laurentb732cf52014-09-24 19:08:21 -07001122non_direct_output:
1123
Eric Laurente552edb2014-03-10 17:42:56 -07001124 // ignoring channel mask due to downmix capability in mixer
1125
1126 // open a non direct output
1127
1128 // for non direct outputs, only PCM is supported
1129 if (audio_is_linear_pcm(format)) {
1130 // get which output is suitable for the specified stream. The actual
1131 // routing change will happen when startOutput() will be called
1132 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1133
Eric Laurent8838a382014-09-08 16:44:28 -07001134 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1135 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1136 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001137 }
1138 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1139 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1140
1141 ALOGV("getOutput() returns output %d", output);
1142
1143 return output;
1144}
1145
Eric Laurente0720872014-03-11 09:30:41 -07001146audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001147 audio_output_flags_t flags,
1148 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001149{
1150 // select one output among several that provide a path to a particular device or set of
1151 // devices (the list was previously build by getOutputsForDevice()).
1152 // The priority is as follows:
1153 // 1: the output with the highest number of requested policy flags
1154 // 2: the primary output
1155 // 3: the first output in the list
1156
1157 if (outputs.size() == 0) {
1158 return 0;
1159 }
1160 if (outputs.size() == 1) {
1161 return outputs[0];
1162 }
1163
1164 int maxCommonFlags = 0;
1165 audio_io_handle_t outputFlags = 0;
1166 audio_io_handle_t outputPrimary = 0;
1167
1168 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001169 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001170 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001171 // if a valid format is specified, skip output if not compatible
1172 if (format != AUDIO_FORMAT_INVALID) {
1173 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1174 if (format != outputDesc->mFormat) {
1175 continue;
1176 }
1177 } else if (!audio_is_linear_pcm(format)) {
1178 continue;
1179 }
1180 }
1181
Eric Laurent3b73df72014-03-11 09:06:29 -07001182 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001183 if (commonFlags > maxCommonFlags) {
1184 outputFlags = outputs[i];
1185 maxCommonFlags = commonFlags;
1186 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1187 }
1188 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1189 outputPrimary = outputs[i];
1190 }
1191 }
1192 }
1193
1194 if (outputFlags != 0) {
1195 return outputFlags;
1196 }
1197 if (outputPrimary != 0) {
1198 return outputPrimary;
1199 }
1200
1201 return outputs[0];
1202}
1203
Eric Laurente0720872014-03-11 09:30:41 -07001204status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001205 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001206 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001207{
1208 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1209 ssize_t index = mOutputs.indexOfKey(output);
1210 if (index < 0) {
1211 ALOGW("startOutput() unknown output %d", output);
1212 return BAD_VALUE;
1213 }
1214
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001215 // cannot start playback of STREAM_TTS if any other output is being used
1216 uint32_t beaconMuteLatency = 0;
1217 if (stream == AUDIO_STREAM_TTS) {
1218 ALOGV("\t found BEACON stream");
1219 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1220 return INVALID_OPERATION;
1221 } else {
1222 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1223 }
1224 } else {
1225 // some playback other than beacon starts
1226 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1227 }
1228
Eric Laurent1f2f2232014-06-02 12:01:23 -07001229 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001230
1231 // increment usage count for this stream on the requested output:
1232 // NOTE that the usage count is the same for duplicated output and hardware output which is
1233 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1234 outputDesc->changeRefCount(stream, 1);
1235
1236 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001237 // starting an output being rerouted?
1238 audio_devices_t newDevice;
Eric Laurentc722f302014-12-10 11:21:49 -08001239 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001240 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1241 } else {
1242 newDevice = getNewOutputDevice(output, false /*fromCache*/);
1243 }
Eric Laurente552edb2014-03-10 17:42:56 -07001244 routing_strategy strategy = getStrategy(stream);
1245 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001246 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1247 (beaconMuteLatency > 0);
1248 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001249 bool force = false;
1250 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001251 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001252 if (desc != outputDesc) {
1253 // force a device change if any other output is managed by the same hw
1254 // module and has a current device selection that differs from selected device.
1255 // In this case, the audio HAL must receive the new device selection so that it can
1256 // change the device currently selected by the other active output.
1257 if (outputDesc->sharesHwModuleWith(desc) &&
1258 desc->device() != newDevice) {
1259 force = true;
1260 }
1261 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001262 // a notification so that audio focus effect can propagate, or that a mute/unmute
1263 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001264 uint32_t latency = desc->latency();
1265 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1266 waitMs = latency;
1267 }
1268 }
1269 }
1270 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1271
1272 // handle special case for sonification while in call
1273 if (isInCall()) {
1274 handleIncallSonification(stream, true, false);
1275 }
1276
1277 // apply volume rules for current stream and device if necessary
1278 checkAndSetVolume(stream,
1279 mStreams[stream].getVolumeIndex(newDevice),
1280 output,
1281 newDevice);
1282
1283 // update the outputs if starting an output with a stream that can affect notification
1284 // routing
1285 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001286
1287 // Automatically enable the remote submix input when output is started on a re routing mix
1288 // of type MIX_TYPE_RECORDERS
1289 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1290 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001291 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001292 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1293 outputDesc->mPolicyMix->mRegistrationId);
1294 }
1295
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001296 // force reevaluating accessibility routing when ringtone or alarm starts
1297 if (strategy == STRATEGY_SONIFICATION) {
1298 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1299 }
1300
Eric Laurente552edb2014-03-10 17:42:56 -07001301 if (waitMs > muteWaitMs) {
1302 usleep((waitMs - muteWaitMs) * 2 * 1000);
1303 }
1304 }
1305 return NO_ERROR;
1306}
1307
1308
Eric Laurente0720872014-03-11 09:30:41 -07001309status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001310 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001311 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001312{
1313 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1314 ssize_t index = mOutputs.indexOfKey(output);
1315 if (index < 0) {
1316 ALOGW("stopOutput() unknown output %d", output);
1317 return BAD_VALUE;
1318 }
1319
Eric Laurent1f2f2232014-06-02 12:01:23 -07001320 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001321
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001322 // always handle stream stop, check which stream type is stopping
1323 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1324
Eric Laurente552edb2014-03-10 17:42:56 -07001325 // handle special case for sonification while in call
1326 if (isInCall()) {
1327 handleIncallSonification(stream, false, false);
1328 }
1329
1330 if (outputDesc->mRefCount[stream] > 0) {
1331 // decrement usage count of this stream on the output
1332 outputDesc->changeRefCount(stream, -1);
1333 // store time at which the stream was stopped - see isStreamActive()
1334 if (outputDesc->mRefCount[stream] == 0) {
Eric Laurentc722f302014-12-10 11:21:49 -08001335 // Automatically disable the remote submix input when output is stopped on a
1336 // re routing mix of type MIX_TYPE_RECORDERS
1337 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1338 outputDesc->mPolicyMix != NULL &&
1339 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001340 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001341 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1342 outputDesc->mPolicyMix->mRegistrationId);
1343 }
1344
Eric Laurente552edb2014-03-10 17:42:56 -07001345 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001346 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001347 // delay the device switch by twice the latency because stopOutput() is executed when
1348 // the track stop() command is received and at that time the audio track buffer can
1349 // still contain data that needs to be drained. The latency only covers the audio HAL
1350 // and kernel buffers. Also the latency does not always include additional delay in the
1351 // audio path (audio DSP, CODEC ...)
1352 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1353
1354 // force restoring the device selection on other active outputs if it differs from the
1355 // one being selected for this output
1356 for (size_t i = 0; i < mOutputs.size(); i++) {
1357 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001358 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001359 if (curOutput != output &&
1360 desc->isActive() &&
1361 outputDesc->sharesHwModuleWith(desc) &&
1362 (newDevice != desc->device())) {
1363 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001364 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001365 true,
1366 outputDesc->mLatency*2);
1367 }
1368 }
1369 // update the outputs if stopping one with a stream that can affect notification routing
1370 handleNotificationRoutingForStream(stream);
1371 }
1372 return NO_ERROR;
1373 } else {
1374 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1375 return INVALID_OPERATION;
1376 }
1377}
1378
Eric Laurente83b55d2014-11-14 10:06:21 -08001379void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001380 audio_stream_type_t stream __unused,
1381 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001382{
1383 ALOGV("releaseOutput() %d", output);
1384 ssize_t index = mOutputs.indexOfKey(output);
1385 if (index < 0) {
1386 ALOGW("releaseOutput() releasing unknown output %d", output);
1387 return;
1388 }
1389
1390#ifdef AUDIO_POLICY_TEST
1391 int testIndex = testOutputIndex(output);
1392 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001393 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001394 if (outputDesc->isActive()) {
1395 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001396 mOutputs.removeItem(output);
1397 mTestOutputs[testIndex] = 0;
1398 }
1399 return;
1400 }
1401#endif //AUDIO_POLICY_TEST
1402
Eric Laurent1f2f2232014-06-02 12:01:23 -07001403 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001404 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001405 if (desc->mDirectOpenCount <= 0) {
1406 ALOGW("releaseOutput() invalid open count %d for output %d",
1407 desc->mDirectOpenCount, output);
1408 return;
1409 }
1410 if (--desc->mDirectOpenCount == 0) {
1411 closeOutput(output);
1412 // If effects where present on the output, audioflinger moved them to the primary
1413 // output by default: move them back to the appropriate output.
1414 audio_io_handle_t dstOutput = getOutputForEffect();
1415 if (dstOutput != mPrimaryOutput) {
1416 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1417 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001418 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001419 }
1420 }
1421}
1422
1423
Eric Laurentcaf7f482014-11-25 17:50:47 -08001424status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1425 audio_io_handle_t *input,
1426 audio_session_t session,
1427 uint32_t samplingRate,
1428 audio_format_t format,
1429 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001430 audio_input_flags_t flags,
1431 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001432{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001433 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1434 "session %d, flags %#x",
1435 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001436
Eric Laurentcaf7f482014-11-25 17:50:47 -08001437 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001438 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001439 audio_devices_t device;
1440 // handle legacy remote submix case where the address was not always specified
1441 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001442 bool isSoundTrigger = false;
Eric Laurentcaf7f482014-11-25 17:50:47 -08001443 audio_source_t halInputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001444 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001445
1446 if (attr->source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1447 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1448 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1449 address = String8(attr->tags + strlen("addr="));
1450 ssize_t index = mPolicyMixes.indexOfKey(address);
1451 if (index < 0) {
1452 ALOGW("getInputForAttr() no policy for address %s", address.string());
1453 return BAD_VALUE;
1454 }
Eric Laurentc722f302014-12-10 11:21:49 -08001455 if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) {
1456 ALOGW("getInputForAttr() bad policy mix type for address %s", address.string());
1457 return BAD_VALUE;
1458 }
1459 policyMix = &mPolicyMixes[index]->mMix;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001460 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001461 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001462 device = getDeviceAndMixForInputSource(attr->source, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001463 if (device == AUDIO_DEVICE_NONE) {
1464 ALOGW("getInputForAttr() could not find device for source %d", attr->source);
1465 return BAD_VALUE;
1466 }
Eric Laurentc722f302014-12-10 11:21:49 -08001467 if (policyMix != NULL) {
1468 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001469 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1470 // there is an external policy, but this input is attached to a mix of recorders,
1471 // meaning it receives audio injected into the framework, so the recorder doesn't
1472 // know about it and is therefore considered "legacy"
1473 *inputType = API_INPUT_LEGACY;
1474 } else {
1475 // recording a mix of players defined by an external policy, we're rerouting for
1476 // an external policy
1477 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1478 }
Eric Laurentc722f302014-12-10 11:21:49 -08001479 } else if (audio_is_remote_submix_device(device)) {
1480 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001481 *inputType = API_INPUT_MIX_CAPTURE;
1482 } else {
1483 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001484 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001485 // adapt channel selection to input source
1486 switch (attr->source) {
1487 case AUDIO_SOURCE_VOICE_UPLINK:
1488 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1489 break;
1490 case AUDIO_SOURCE_VOICE_DOWNLINK:
1491 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1492 break;
1493 case AUDIO_SOURCE_VOICE_CALL:
1494 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1495 break;
1496 default:
1497 break;
1498 }
1499 if (attr->source == AUDIO_SOURCE_HOTWORD) {
1500 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1501 if (index >= 0) {
1502 *input = mSoundTriggerSessions.valueFor(session);
1503 isSoundTrigger = true;
1504 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1505 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1506 } else {
1507 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1508 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001509 }
1510 }
1511
Eric Laurent275e8e92014-11-30 15:14:47 -08001512 sp<IOProfile> profile = getInputProfile(device, address,
1513 samplingRate, format, channelMask,
1514 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001515 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001516 //retry without flags
1517 audio_input_flags_t log_flags = flags;
1518 flags = AUDIO_INPUT_FLAG_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001519 profile = getInputProfile(device, address,
1520 samplingRate, format, channelMask,
1521 flags);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001522 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001523 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1524 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001525 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001526 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001527 }
Eric Laurente552edb2014-03-10 17:42:56 -07001528 }
1529
1530 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001531 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1532 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001533 }
1534
1535 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1536 config.sample_rate = samplingRate;
1537 config.channel_mask = channelMask;
1538 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001539
Eric Laurentcf2c0212014-07-25 16:20:43 -07001540 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001541 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001542 &config,
1543 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001544 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001545 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001546 flags);
1547
1548 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001549 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001550 (samplingRate != config.sample_rate) ||
1551 (format != config.format) ||
1552 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001553 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001554 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001555 if (*input != AUDIO_IO_HANDLE_NONE) {
1556 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001557 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001558 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001559 }
1560
Eric Laurent1f2f2232014-06-02 12:01:23 -07001561 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001562 inputDesc->mInputSource = attr->source;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001563 inputDesc->mRefCount = 0;
1564 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001565 inputDesc->mSamplingRate = samplingRate;
1566 inputDesc->mFormat = format;
1567 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001568 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001569 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001570 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001571 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001572
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001573 ALOGV("getInputForAttr() returns input type = %d", inputType);
1574
Eric Laurentcaf7f482014-11-25 17:50:47 -08001575 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001576 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001577 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001578}
1579
Eric Laurent4dc68062014-07-28 17:26:49 -07001580status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1581 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001582{
1583 ALOGV("startInput() input %d", input);
1584 ssize_t index = mInputs.indexOfKey(input);
1585 if (index < 0) {
1586 ALOGW("startInput() unknown input %d", input);
1587 return BAD_VALUE;
1588 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001589 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001590
Eric Laurentc722f302014-12-10 11:21:49 -08001591 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001592 if (index < 0) {
1593 ALOGW("startInput() unknown session %d on input %d", session, input);
1594 return BAD_VALUE;
1595 }
1596
Glenn Kasten74a8e252014-07-24 14:09:55 -07001597 // virtual input devices are compatible with other input devices
1598 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1599
1600 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001601 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001602 if (activeInput != 0 && activeInput != input) {
1603
1604 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1605 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001606 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001607 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001608 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurentc722f302014-12-10 11:21:49 -08001609 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1610 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001611 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001612 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001613 return INVALID_OPERATION;
1614 }
1615 }
1616 }
1617
Glenn Kasten74a8e252014-07-24 14:09:55 -07001618 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001619 if (activeInputsCount() == 0) {
1620 SoundTrigger::setCaptureState(true);
1621 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001622 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001623
Eric Laurentc722f302014-12-10 11:21:49 -08001624 // automatically enable the remote submix output when input is started if not
1625 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001626 // For remote submix (a virtual device), we open only one input per capture request.
1627 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001628 String8 address = String8("");
1629 if (inputDesc->mPolicyMix == NULL) {
1630 address = String8("0");
1631 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1632 address = inputDesc->mPolicyMix->mRegistrationId;
1633 }
1634 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001635 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001636 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1637 address);
1638 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001639 }
Eric Laurente552edb2014-03-10 17:42:56 -07001640 }
1641
Eric Laurente552edb2014-03-10 17:42:56 -07001642 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1643
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001644 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001645 return NO_ERROR;
1646}
1647
Eric Laurent4dc68062014-07-28 17:26:49 -07001648status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1649 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001650{
1651 ALOGV("stopInput() input %d", input);
1652 ssize_t index = mInputs.indexOfKey(input);
1653 if (index < 0) {
1654 ALOGW("stopInput() unknown input %d", input);
1655 return BAD_VALUE;
1656 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001657 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001658
Eric Laurentc722f302014-12-10 11:21:49 -08001659 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001660 if (index < 0) {
1661 ALOGW("stopInput() unknown session %d on input %d", session, input);
1662 return BAD_VALUE;
1663 }
1664
Eric Laurente552edb2014-03-10 17:42:56 -07001665 if (inputDesc->mRefCount == 0) {
1666 ALOGW("stopInput() input %d already stopped", input);
1667 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001668 }
1669
1670 inputDesc->mRefCount--;
1671 if (inputDesc->mRefCount == 0) {
1672
Eric Laurentc722f302014-12-10 11:21:49 -08001673 // automatically disable the remote submix output when input is stopped if not
1674 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001675 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001676 String8 address = String8("");
1677 if (inputDesc->mPolicyMix == NULL) {
1678 address = String8("0");
1679 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1680 address = inputDesc->mPolicyMix->mRegistrationId;
1681 }
1682 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001683 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001684 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1685 address);
1686 }
Eric Laurente552edb2014-03-10 17:42:56 -07001687 }
1688
Eric Laurent1c333e22014-05-20 10:48:17 -07001689 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001690
1691 if (activeInputsCount() == 0) {
1692 SoundTrigger::setCaptureState(false);
1693 }
Eric Laurente552edb2014-03-10 17:42:56 -07001694 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001695 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001696}
1697
Eric Laurent4dc68062014-07-28 17:26:49 -07001698void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1699 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001700{
1701 ALOGV("releaseInput() %d", input);
1702 ssize_t index = mInputs.indexOfKey(input);
1703 if (index < 0) {
1704 ALOGW("releaseInput() releasing unknown input %d", input);
1705 return;
1706 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001707 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1708 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001709
Eric Laurentc722f302014-12-10 11:21:49 -08001710 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001711 if (index < 0) {
1712 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1713 return;
1714 }
Eric Laurentc722f302014-12-10 11:21:49 -08001715 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001716 if (inputDesc->mOpenRefCount == 0) {
1717 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1718 return;
1719 }
1720 inputDesc->mOpenRefCount--;
1721 if (inputDesc->mOpenRefCount > 0) {
1722 ALOGV("releaseInput() exit > 0");
1723 return;
1724 }
1725
Eric Laurent05b90f82014-08-27 15:32:29 -07001726 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001727 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001728 ALOGV("releaseInput() exit");
1729}
1730
Eric Laurentd4692962014-05-05 18:13:44 -07001731void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001732 bool patchRemoved = false;
1733
Eric Laurentd4692962014-05-05 18:13:44 -07001734 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001735 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1736 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1737 if (patch_index >= 0) {
1738 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1739 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1740 mAudioPatches.removeItemsAt(patch_index);
1741 patchRemoved = true;
1742 }
Eric Laurentd4692962014-05-05 18:13:44 -07001743 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1744 }
1745 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001746 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001747
1748 if (patchRemoved) {
1749 mpClientInterface->onAudioPatchListUpdate();
1750 }
Eric Laurentd4692962014-05-05 18:13:44 -07001751}
1752
Eric Laurente0720872014-03-11 09:30:41 -07001753void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001754 int indexMin,
1755 int indexMax)
1756{
1757 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1758 if (indexMin < 0 || indexMin >= indexMax) {
1759 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1760 return;
1761 }
1762 mStreams[stream].mIndexMin = indexMin;
1763 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001764 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1765 if (stream == AUDIO_STREAM_MUSIC) {
1766 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1767 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1768 }
Eric Laurente552edb2014-03-10 17:42:56 -07001769}
1770
Eric Laurente0720872014-03-11 09:30:41 -07001771status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001772 int index,
1773 audio_devices_t device)
1774{
1775
1776 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1777 return BAD_VALUE;
1778 }
1779 if (!audio_is_output_device(device)) {
1780 return BAD_VALUE;
1781 }
1782
1783 // Force max volume if stream cannot be muted
1784 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1785
1786 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1787 stream, device, index);
1788
1789 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1790 // clear all device specific values
1791 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1792 mStreams[stream].mIndexCur.clear();
1793 }
1794 mStreams[stream].mIndexCur.add(device, index);
1795
Eric Laurent31551f82014-10-10 18:21:56 -07001796 // update volume on all outputs whose current device is also selected by the same
1797 // strategy as the device specified by the caller
1798 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001799
1800
1801 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1802 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1803 if (stream == AUDIO_STREAM_MUSIC) {
1804 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1805 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1806 }
1807 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1808 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001809 return NO_ERROR;
1810 }
Eric Laurente552edb2014-03-10 17:42:56 -07001811 status_t status = NO_ERROR;
1812 for (size_t i = 0; i < mOutputs.size(); i++) {
1813 audio_devices_t curDevice =
1814 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001815 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001816 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1817 if (volStatus != NO_ERROR) {
1818 status = volStatus;
1819 }
1820 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001821 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1822 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1823 index, mOutputs.keyAt(i), curDevice);
1824 }
Eric Laurente552edb2014-03-10 17:42:56 -07001825 }
1826 return status;
1827}
1828
Eric Laurente0720872014-03-11 09:30:41 -07001829status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001830 int *index,
1831 audio_devices_t device)
1832{
1833 if (index == NULL) {
1834 return BAD_VALUE;
1835 }
1836 if (!audio_is_output_device(device)) {
1837 return BAD_VALUE;
1838 }
1839 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1840 // the strategy the stream belongs to.
1841 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1842 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1843 }
1844 device = getDeviceForVolume(device);
1845
1846 *index = mStreams[stream].getVolumeIndex(device);
1847 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1848 return NO_ERROR;
1849}
1850
Eric Laurente0720872014-03-11 09:30:41 -07001851audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001852 const SortedVector<audio_io_handle_t>& outputs)
1853{
1854 // select one output among several suitable for global effects.
1855 // The priority is as follows:
1856 // 1: An offloaded output. If the effect ends up not being offloadable,
1857 // AudioFlinger will invalidate the track and the offloaded output
1858 // will be closed causing the effect to be moved to a PCM output.
1859 // 2: A deep buffer output
1860 // 3: the first output in the list
1861
1862 if (outputs.size() == 0) {
1863 return 0;
1864 }
1865
1866 audio_io_handle_t outputOffloaded = 0;
1867 audio_io_handle_t outputDeepBuffer = 0;
1868
1869 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001870 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001871 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001872 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1873 outputOffloaded = outputs[i];
1874 }
1875 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1876 outputDeepBuffer = outputs[i];
1877 }
1878 }
1879
1880 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1881 outputOffloaded, outputDeepBuffer);
1882 if (outputOffloaded != 0) {
1883 return outputOffloaded;
1884 }
1885 if (outputDeepBuffer != 0) {
1886 return outputDeepBuffer;
1887 }
1888
1889 return outputs[0];
1890}
1891
Eric Laurente0720872014-03-11 09:30:41 -07001892audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001893{
1894 // apply simple rule where global effects are attached to the same output as MUSIC streams
1895
Eric Laurent3b73df72014-03-11 09:06:29 -07001896 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001897 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1898 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1899
1900 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1901 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1902 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1903
1904 return output;
1905}
1906
Eric Laurente0720872014-03-11 09:30:41 -07001907status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001908 audio_io_handle_t io,
1909 uint32_t strategy,
1910 int session,
1911 int id)
1912{
1913 ssize_t index = mOutputs.indexOfKey(io);
1914 if (index < 0) {
1915 index = mInputs.indexOfKey(io);
1916 if (index < 0) {
1917 ALOGW("registerEffect() unknown io %d", io);
1918 return INVALID_OPERATION;
1919 }
1920 }
1921
1922 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1923 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1924 desc->name, desc->memoryUsage);
1925 return INVALID_OPERATION;
1926 }
1927 mTotalEffectsMemory += desc->memoryUsage;
1928 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1929 desc->name, io, strategy, session, id);
1930 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1931
Eric Laurent1f2f2232014-06-02 12:01:23 -07001932 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1933 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1934 effectDesc->mIo = io;
1935 effectDesc->mStrategy = (routing_strategy)strategy;
1936 effectDesc->mSession = session;
1937 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001938
Eric Laurent1f2f2232014-06-02 12:01:23 -07001939 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001940
1941 return NO_ERROR;
1942}
1943
Eric Laurente0720872014-03-11 09:30:41 -07001944status_t AudioPolicyManager::unregisterEffect(int id)
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
Eric Laurent1f2f2232014-06-02 12:01:23 -07001952 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001953
Eric Laurent1f2f2232014-06-02 12:01:23 -07001954 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001955
Eric Laurent1f2f2232014-06-02 12:01:23 -07001956 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001957 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001958 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1959 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001960 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001961 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001962 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001963 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001964
1965 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001966
1967 return NO_ERROR;
1968}
1969
Eric Laurente0720872014-03-11 09:30:41 -07001970status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001971{
1972 ssize_t index = mEffects.indexOfKey(id);
1973 if (index < 0) {
1974 ALOGW("unregisterEffect() unknown effect ID %d", id);
1975 return INVALID_OPERATION;
1976 }
1977
1978 return setEffectEnabled(mEffects.valueAt(index), enabled);
1979}
1980
Eric Laurent1f2f2232014-06-02 12:01:23 -07001981status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001982{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001983 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001984 ALOGV("setEffectEnabled(%s) effect already %s",
1985 enabled?"true":"false", enabled?"enabled":"disabled");
1986 return INVALID_OPERATION;
1987 }
1988
1989 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001990 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001991 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001992 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001993 return INVALID_OPERATION;
1994 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001995 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001996 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1997 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001998 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001999 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002000 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
2001 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002002 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002003 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002004 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
2005 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002006 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07002007 return NO_ERROR;
2008}
2009
Eric Laurente0720872014-03-11 09:30:41 -07002010bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07002011{
2012 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002013 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
2014 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
2015 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002016 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002017 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07002018 return true;
2019 }
2020 }
2021 return false;
2022}
2023
Eric Laurente0720872014-03-11 09:30:41 -07002024bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002025{
2026 nsecs_t sysTime = systemTime();
2027 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002028 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07002029 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002030 return true;
2031 }
2032 }
2033 return false;
2034}
2035
Eric Laurente0720872014-03-11 09:30:41 -07002036bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07002037 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002038{
2039 nsecs_t sysTime = systemTime();
2040 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002041 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002042 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002043 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurentc722f302014-12-10 11:21:49 -08002044 // do not consider re routing (when the output is going to a dynamic policy)
2045 // as "remote playback"
2046 if (outputDesc->mPolicyMix == NULL) {
Jean-Michel Trivi1767df72014-12-09 18:11:49 -08002047 return true;
2048 }
Eric Laurente552edb2014-03-10 17:42:56 -07002049 }
2050 }
2051 return false;
2052}
2053
Eric Laurente0720872014-03-11 09:30:41 -07002054bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002055{
2056 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002057 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002058 if (inputDescriptor->mRefCount == 0) {
2059 continue;
2060 }
2061 if (inputDescriptor->mInputSource == (int)source) {
Eric Laurente552edb2014-03-10 17:42:56 -07002062 return true;
2063 }
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002064 // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it
2065 // corresponds to an active capture triggered by a hardware hotword recognition
2066 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) &&
2067 (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) {
2068 // FIXME: we should not assume that the first session is the active one and keep
2069 // activity count per session. Same in startInput().
2070 ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0));
2071 if (index >= 0) {
2072 return true;
2073 }
2074 }
Eric Laurente552edb2014-03-10 17:42:56 -07002075 }
2076 return false;
2077}
2078
Eric Laurent275e8e92014-11-30 15:14:47 -08002079// Register a list of custom mixes with their attributes and format.
2080// When a mix is registered, corresponding input and output profiles are
2081// added to the remote submix hw module. The profile contains only the
2082// parameters (sampling rate, format...) specified by the mix.
2083// The corresponding input remote submix device is also connected.
2084//
2085// When a remote submix device is connected, the address is checked to select the
2086// appropriate profile and the corresponding input or output stream is opened.
2087//
2088// When capture starts, getInputForAttr() will:
2089// - 1 look for a mix matching the address passed in attribtutes tags if any
2090// - 2 if none found, getDeviceForInputSource() will:
2091// - 2.1 look for a mix matching the attributes source
2092// - 2.2 if none found, default to device selection by policy rules
2093// At this time, the corresponding output remote submix device is also connected
2094// and active playback use cases can be transferred to this mix if needed when reconnecting
2095// after AudioTracks are invalidated
2096//
2097// When playback starts, getOutputForAttr() will:
2098// - 1 look for a mix matching the address passed in attribtutes tags if any
2099// - 2 if none found, look for a mix matching the attributes usage
2100// - 3 if none found, default to device and output selection by policy rules.
2101
2102status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2103{
2104 sp<HwModule> module;
2105 for (size_t i = 0; i < mHwModules.size(); i++) {
2106 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2107 mHwModules[i]->mHandle != 0) {
2108 module = mHwModules[i];
2109 break;
2110 }
2111 }
2112
2113 if (module == 0) {
2114 return INVALID_OPERATION;
2115 }
2116
2117 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2118
2119 for (size_t i = 0; i < mixes.size(); i++) {
2120 String8 address = mixes[i].mRegistrationId;
2121 ssize_t index = mPolicyMixes.indexOfKey(address);
2122 if (index >= 0) {
2123 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2124 continue;
2125 }
2126 audio_config_t outputConfig = mixes[i].mFormat;
2127 audio_config_t inputConfig = mixes[i].mFormat;
2128 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2129 // stereo and let audio flinger do the channel conversion if needed.
2130 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2131 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2132 module->addOutputProfile(address, &outputConfig,
2133 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2134 module->addInputProfile(address, &inputConfig,
2135 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2136 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2137 policyMix->mMix = mixes[i];
2138 mPolicyMixes.add(address, policyMix);
Eric Laurentc722f302014-12-10 11:21:49 -08002139 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002140 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002141 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2142 address.string());
2143 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002144 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002145 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2146 address.string());
2147 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002148 }
2149 return NO_ERROR;
2150}
2151
2152status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2153{
2154 sp<HwModule> module;
2155 for (size_t i = 0; i < mHwModules.size(); i++) {
2156 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2157 mHwModules[i]->mHandle != 0) {
2158 module = mHwModules[i];
2159 break;
2160 }
2161 }
2162
2163 if (module == 0) {
2164 return INVALID_OPERATION;
2165 }
2166
2167 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2168
2169 for (size_t i = 0; i < mixes.size(); i++) {
2170 String8 address = mixes[i].mRegistrationId;
2171 ssize_t index = mPolicyMixes.indexOfKey(address);
2172 if (index < 0) {
2173 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2174 continue;
2175 }
2176
2177 mPolicyMixes.removeItemsAt(index);
2178
Eric Laurentc722f302014-12-10 11:21:49 -08002179 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2180 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2181 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002182 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002183 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2184 address.string());
2185 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002186
2187 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2188 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2189 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002190 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002191 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2192 address.string());
2193 }
2194 module->removeOutputProfile(address);
2195 module->removeInputProfile(address);
2196 }
2197 return NO_ERROR;
2198}
2199
Eric Laurente552edb2014-03-10 17:42:56 -07002200
Eric Laurente0720872014-03-11 09:30:41 -07002201status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002202{
2203 const size_t SIZE = 256;
2204 char buffer[SIZE];
2205 String8 result;
2206
2207 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2208 result.append(buffer);
2209
2210 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2211 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002212 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2213 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002214 snprintf(buffer, SIZE, " Force use for communications %d\n",
2215 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002216 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002217 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002218 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002219 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07002220 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002221 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07002222 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002223 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002224 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002225 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2226 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2227 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002228
Eric Laurent3a4311c2014-03-17 12:00:47 -07002229 snprintf(buffer, SIZE, " Available output devices:\n");
2230 result.append(buffer);
2231 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002232 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002233 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002234 }
2235 snprintf(buffer, SIZE, "\n Available input devices:\n");
2236 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002237 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002238 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002239 }
Eric Laurente552edb2014-03-10 17:42:56 -07002240
2241 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2242 write(fd, buffer, strlen(buffer));
2243 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002244 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002245 write(fd, buffer, strlen(buffer));
2246 mHwModules[i]->dump(fd);
2247 }
2248
2249 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2250 write(fd, buffer, strlen(buffer));
2251 for (size_t i = 0; i < mOutputs.size(); i++) {
2252 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2253 write(fd, buffer, strlen(buffer));
2254 mOutputs.valueAt(i)->dump(fd);
2255 }
2256
2257 snprintf(buffer, SIZE, "\nInputs dump:\n");
2258 write(fd, buffer, strlen(buffer));
2259 for (size_t i = 0; i < mInputs.size(); i++) {
2260 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2261 write(fd, buffer, strlen(buffer));
2262 mInputs.valueAt(i)->dump(fd);
2263 }
2264
2265 snprintf(buffer, SIZE, "\nStreams dump:\n");
2266 write(fd, buffer, strlen(buffer));
2267 snprintf(buffer, SIZE,
2268 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2269 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002270 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002271 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002272 write(fd, buffer, strlen(buffer));
2273 mStreams[i].dump(fd);
2274 }
2275
2276 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2277 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2278 write(fd, buffer, strlen(buffer));
2279
2280 snprintf(buffer, SIZE, "Registered effects:\n");
2281 write(fd, buffer, strlen(buffer));
2282 for (size_t i = 0; i < mEffects.size(); i++) {
2283 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2284 write(fd, buffer, strlen(buffer));
2285 mEffects.valueAt(i)->dump(fd);
2286 }
2287
Eric Laurent4d416952014-08-10 14:07:09 -07002288 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2289 write(fd, buffer, strlen(buffer));
2290 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2291 mAudioPatches[i]->dump(fd, 2, i);
2292 }
Eric Laurente552edb2014-03-10 17:42:56 -07002293
2294 return NO_ERROR;
2295}
2296
2297// This function checks for the parameters which can be offloaded.
2298// This can be enhanced depending on the capability of the DSP and policy
2299// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002300bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002301{
2302 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002303 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002304 offloadInfo.sample_rate, offloadInfo.channel_mask,
2305 offloadInfo.format,
2306 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2307 offloadInfo.has_video);
2308
2309 // Check if offload has been disabled
2310 char propValue[PROPERTY_VALUE_MAX];
2311 if (property_get("audio.offload.disable", propValue, "0")) {
2312 if (atoi(propValue) != 0) {
2313 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2314 return false;
2315 }
2316 }
2317
2318 // Check if stream type is music, then only allow offload as of now.
2319 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2320 {
2321 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2322 return false;
2323 }
2324
2325 //TODO: enable audio offloading with video when ready
2326 if (offloadInfo.has_video)
2327 {
2328 ALOGV("isOffloadSupported: has_video == true, returning false");
2329 return false;
2330 }
2331
2332 //If duration is less than minimum value defined in property, return false
2333 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2334 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2335 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2336 return false;
2337 }
2338 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2339 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2340 return false;
2341 }
2342
2343 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2344 // creating an offloaded track and tearing it down immediately after start when audioflinger
2345 // detects there is an active non offloadable effect.
2346 // FIXME: We should check the audio session here but we do not have it in this context.
2347 // This may prevent offloading in rare situations where effects are left active by apps
2348 // in the background.
2349 if (isNonOffloadableEffectEnabled()) {
2350 return false;
2351 }
2352
2353 // See if there is a profile to support this.
2354 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002355 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002356 offloadInfo.sample_rate,
2357 offloadInfo.format,
2358 offloadInfo.channel_mask,
2359 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002360 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2361 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002362}
2363
Eric Laurent6a94d692014-05-20 11:18:06 -07002364status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2365 audio_port_type_t type,
2366 unsigned int *num_ports,
2367 struct audio_port *ports,
2368 unsigned int *generation)
2369{
2370 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2371 generation == NULL) {
2372 return BAD_VALUE;
2373 }
2374 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2375 if (ports == NULL) {
2376 *num_ports = 0;
2377 }
2378
2379 size_t portsWritten = 0;
2380 size_t portsMax = *num_ports;
2381 *num_ports = 0;
2382 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2383 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2384 for (size_t i = 0;
2385 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2386 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2387 }
2388 *num_ports += mAvailableOutputDevices.size();
2389 }
2390 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2391 for (size_t i = 0;
2392 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2393 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2394 }
2395 *num_ports += mAvailableInputDevices.size();
2396 }
2397 }
2398 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2399 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2400 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2401 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2402 }
2403 *num_ports += mInputs.size();
2404 }
2405 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002406 size_t numOutputs = 0;
2407 for (size_t i = 0; i < mOutputs.size(); i++) {
2408 if (!mOutputs[i]->isDuplicated()) {
2409 numOutputs++;
2410 if (portsWritten < portsMax) {
2411 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2412 }
2413 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002414 }
Eric Laurent84c70242014-06-23 08:46:27 -07002415 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002416 }
2417 }
2418 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002419 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002420 return NO_ERROR;
2421}
2422
2423status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2424{
2425 return NO_ERROR;
2426}
2427
Eric Laurent1f2f2232014-06-02 12:01:23 -07002428sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002429 audio_port_handle_t id) const
2430{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002431 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002432 for (size_t i = 0; i < mOutputs.size(); i++) {
2433 outputDesc = mOutputs.valueAt(i);
2434 if (outputDesc->mId == id) {
2435 break;
2436 }
2437 }
2438 return outputDesc;
2439}
2440
Eric Laurent1f2f2232014-06-02 12:01:23 -07002441sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002442 audio_port_handle_t id) const
2443{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002444 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002445 for (size_t i = 0; i < mInputs.size(); i++) {
2446 inputDesc = mInputs.valueAt(i);
2447 if (inputDesc->mId == id) {
2448 break;
2449 }
2450 }
2451 return inputDesc;
2452}
2453
Eric Laurent1f2f2232014-06-02 12:01:23 -07002454sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2455 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002456{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002457 sp <HwModule> module;
2458
Eric Laurent6a94d692014-05-20 11:18:06 -07002459 for (size_t i = 0; i < mHwModules.size(); i++) {
2460 if (mHwModules[i]->mHandle == 0) {
2461 continue;
2462 }
2463 if (audio_is_output_device(device)) {
2464 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2465 {
2466 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2467 return mHwModules[i];
2468 }
2469 }
2470 } else {
2471 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2472 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2473 device & ~AUDIO_DEVICE_BIT_IN) {
2474 return mHwModules[i];
2475 }
2476 }
2477 }
2478 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002479 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002480}
2481
Eric Laurent1f2f2232014-06-02 12:01:23 -07002482sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002483{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002484 sp <HwModule> module;
2485
Eric Laurent1afeecb2014-05-14 08:52:28 -07002486 for (size_t i = 0; i < mHwModules.size(); i++)
2487 {
2488 if (strcmp(mHwModules[i]->mName, name) == 0) {
2489 return mHwModules[i];
2490 }
2491 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002492 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002493}
2494
Eric Laurentc2730ba2014-07-20 15:47:07 -07002495audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2496{
2497 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2498 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2499 return devices & mAvailableOutputDevices.types();
2500}
2501
2502audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2503{
2504 audio_module_handle_t primaryHandle =
2505 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2506 audio_devices_t devices = AUDIO_DEVICE_NONE;
2507 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2508 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2509 devices |= mAvailableInputDevices[i]->mDeviceType;
2510 }
2511 }
2512 return devices;
2513}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002514
Eric Laurent6a94d692014-05-20 11:18:06 -07002515status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2516 audio_patch_handle_t *handle,
2517 uid_t uid)
2518{
2519 ALOGV("createAudioPatch()");
2520
2521 if (handle == NULL || patch == NULL) {
2522 return BAD_VALUE;
2523 }
2524 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2525
Eric Laurent874c42872014-08-08 15:13:39 -07002526 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2527 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2528 return BAD_VALUE;
2529 }
2530 // only one source per audio patch supported for now
2531 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002532 return INVALID_OPERATION;
2533 }
Eric Laurent874c42872014-08-08 15:13:39 -07002534
2535 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002536 return INVALID_OPERATION;
2537 }
Eric Laurent874c42872014-08-08 15:13:39 -07002538 for (size_t i = 0; i < patch->num_sinks; i++) {
2539 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2540 return INVALID_OPERATION;
2541 }
2542 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002543
2544 sp<AudioPatch> patchDesc;
2545 ssize_t index = mAudioPatches.indexOfKey(*handle);
2546
Eric Laurent6a94d692014-05-20 11:18:06 -07002547 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2548 patch->sources[0].role,
2549 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002550#if LOG_NDEBUG == 0
2551 for (size_t i = 0; i < patch->num_sinks; i++) {
2552 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2553 patch->sinks[i].role,
2554 patch->sinks[i].type);
2555 }
2556#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002557
2558 if (index >= 0) {
2559 patchDesc = mAudioPatches.valueAt(index);
2560 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2561 mUidCached, patchDesc->mUid, uid);
2562 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2563 return INVALID_OPERATION;
2564 }
2565 } else {
2566 *handle = 0;
2567 }
2568
2569 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002570 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002571 if (outputDesc == NULL) {
2572 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2573 return BAD_VALUE;
2574 }
Eric Laurent84c70242014-06-23 08:46:27 -07002575 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2576 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002577 if (patchDesc != 0) {
2578 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2579 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2580 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2581 return BAD_VALUE;
2582 }
2583 }
Eric Laurent874c42872014-08-08 15:13:39 -07002584 DeviceVector devices;
2585 for (size_t i = 0; i < patch->num_sinks; i++) {
2586 // Only support mix to devices connection
2587 // TODO add support for mix to mix connection
2588 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2589 ALOGV("createAudioPatch() source mix but sink is not a device");
2590 return INVALID_OPERATION;
2591 }
2592 sp<DeviceDescriptor> devDesc =
2593 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2594 if (devDesc == 0) {
2595 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2596 return BAD_VALUE;
2597 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002598
Eric Laurent874c42872014-08-08 15:13:39 -07002599 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002600 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002601 patch->sources[0].sample_rate,
2602 NULL, // updatedSamplingRate
2603 patch->sources[0].format,
2604 patch->sources[0].channel_mask,
2605 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2606 ALOGV("createAudioPatch() profile not supported for device %08x",
2607 devDesc->mDeviceType);
2608 return INVALID_OPERATION;
2609 }
2610 devices.add(devDesc);
2611 }
2612 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002613 return INVALID_OPERATION;
2614 }
Eric Laurent874c42872014-08-08 15:13:39 -07002615
Eric Laurent6a94d692014-05-20 11:18:06 -07002616 // TODO: reconfigure output format and channels here
2617 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002618 devices.types(), outputDesc->mIoHandle);
2619 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002620 index = mAudioPatches.indexOfKey(*handle);
2621 if (index >= 0) {
2622 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2623 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2624 }
2625 patchDesc = mAudioPatches.valueAt(index);
2626 patchDesc->mUid = uid;
2627 ALOGV("createAudioPatch() success");
2628 } else {
2629 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2630 return INVALID_OPERATION;
2631 }
2632 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2633 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2634 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002635 // only one sink supported when connecting an input device to a mix
2636 if (patch->num_sinks > 1) {
2637 return INVALID_OPERATION;
2638 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002639 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002640 if (inputDesc == NULL) {
2641 return BAD_VALUE;
2642 }
2643 if (patchDesc != 0) {
2644 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2645 return BAD_VALUE;
2646 }
2647 }
2648 sp<DeviceDescriptor> devDesc =
2649 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2650 if (devDesc == 0) {
2651 return BAD_VALUE;
2652 }
2653
Eric Laurent84c70242014-06-23 08:46:27 -07002654 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002655 devDesc->mAddress,
2656 patch->sinks[0].sample_rate,
2657 NULL, /*updatedSampleRate*/
2658 patch->sinks[0].format,
2659 patch->sinks[0].channel_mask,
2660 // FIXME for the parameter type,
2661 // and the NONE
2662 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002663 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002664 return INVALID_OPERATION;
2665 }
2666 // TODO: reconfigure output format and channels here
2667 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002668 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002669 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002670 index = mAudioPatches.indexOfKey(*handle);
2671 if (index >= 0) {
2672 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2673 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2674 }
2675 patchDesc = mAudioPatches.valueAt(index);
2676 patchDesc->mUid = uid;
2677 ALOGV("createAudioPatch() success");
2678 } else {
2679 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2680 return INVALID_OPERATION;
2681 }
2682 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2683 // device to device connection
2684 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002685 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002686 return BAD_VALUE;
2687 }
2688 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002689 sp<DeviceDescriptor> srcDeviceDesc =
2690 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002691 if (srcDeviceDesc == 0) {
2692 return BAD_VALUE;
2693 }
Eric Laurent874c42872014-08-08 15:13:39 -07002694
Eric Laurent6a94d692014-05-20 11:18:06 -07002695 //update source and sink with our own data as the data passed in the patch may
2696 // be incomplete.
2697 struct audio_patch newPatch = *patch;
2698 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002699
Eric Laurent874c42872014-08-08 15:13:39 -07002700 for (size_t i = 0; i < patch->num_sinks; i++) {
2701 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2702 ALOGV("createAudioPatch() source device but one sink is not a device");
2703 return INVALID_OPERATION;
2704 }
2705
2706 sp<DeviceDescriptor> sinkDeviceDesc =
2707 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2708 if (sinkDeviceDesc == 0) {
2709 return BAD_VALUE;
2710 }
2711 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2712
2713 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2714 // only one sink supported when connected devices across HW modules
2715 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002716 return INVALID_OPERATION;
2717 }
Eric Laurent874c42872014-08-08 15:13:39 -07002718 SortedVector<audio_io_handle_t> outputs =
2719 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2720 mOutputs);
2721 // if the sink device is reachable via an opened output stream, request to go via
2722 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002723 audio_io_handle_t output = selectOutput(outputs,
2724 AUDIO_OUTPUT_FLAG_NONE,
2725 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002726 if (output != AUDIO_IO_HANDLE_NONE) {
2727 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2728 if (outputDesc->isDuplicated()) {
2729 return INVALID_OPERATION;
2730 }
2731 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2732 newPatch.num_sources = 2;
2733 }
Eric Laurent83b88082014-06-20 18:31:16 -07002734 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002735 }
2736 // TODO: check from routing capabilities in config file and other conflicting patches
2737
2738 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2739 if (index >= 0) {
2740 afPatchHandle = patchDesc->mAfPatchHandle;
2741 }
2742
2743 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2744 &afPatchHandle,
2745 0);
2746 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2747 status, afPatchHandle);
2748 if (status == NO_ERROR) {
2749 if (index < 0) {
2750 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2751 &newPatch, uid);
2752 addAudioPatch(patchDesc->mHandle, patchDesc);
2753 } else {
2754 patchDesc->mPatch = newPatch;
2755 }
2756 patchDesc->mAfPatchHandle = afPatchHandle;
2757 *handle = patchDesc->mHandle;
2758 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002759 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002760 } else {
2761 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2762 status);
2763 return INVALID_OPERATION;
2764 }
2765 } else {
2766 return BAD_VALUE;
2767 }
2768 } else {
2769 return BAD_VALUE;
2770 }
2771 return NO_ERROR;
2772}
2773
2774status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2775 uid_t uid)
2776{
2777 ALOGV("releaseAudioPatch() patch %d", handle);
2778
2779 ssize_t index = mAudioPatches.indexOfKey(handle);
2780
2781 if (index < 0) {
2782 return BAD_VALUE;
2783 }
2784 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2785 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2786 mUidCached, patchDesc->mUid, uid);
2787 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2788 return INVALID_OPERATION;
2789 }
2790
2791 struct audio_patch *patch = &patchDesc->mPatch;
2792 patchDesc->mUid = mUidCached;
2793 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002794 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002795 if (outputDesc == NULL) {
2796 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2797 return BAD_VALUE;
2798 }
2799
2800 setOutputDevice(outputDesc->mIoHandle,
2801 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2802 true,
2803 0,
2804 NULL);
2805 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2806 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002807 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002808 if (inputDesc == NULL) {
2809 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2810 return BAD_VALUE;
2811 }
2812 setInputDevice(inputDesc->mIoHandle,
2813 getNewInputDevice(inputDesc->mIoHandle),
2814 true,
2815 NULL);
2816 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2817 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2818 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2819 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2820 status, patchDesc->mAfPatchHandle);
2821 removeAudioPatch(patchDesc->mHandle);
2822 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002823 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002824 } else {
2825 return BAD_VALUE;
2826 }
2827 } else {
2828 return BAD_VALUE;
2829 }
2830 return NO_ERROR;
2831}
2832
2833status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2834 struct audio_patch *patches,
2835 unsigned int *generation)
2836{
2837 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2838 generation == NULL) {
2839 return BAD_VALUE;
2840 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002841 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002842 *num_patches, patches, mAudioPatches.size());
2843 if (patches == NULL) {
2844 *num_patches = 0;
2845 }
2846
2847 size_t patchesWritten = 0;
2848 size_t patchesMax = *num_patches;
2849 for (size_t i = 0;
2850 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2851 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2852 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002853 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002854 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2855 }
2856 *num_patches = mAudioPatches.size();
2857
2858 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002859 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002860 return NO_ERROR;
2861}
2862
Eric Laurente1715a42014-05-20 11:30:42 -07002863status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002864{
Eric Laurente1715a42014-05-20 11:30:42 -07002865 ALOGV("setAudioPortConfig()");
2866
2867 if (config == NULL) {
2868 return BAD_VALUE;
2869 }
2870 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2871 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002872 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2873 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002874 }
2875
Eric Laurenta121f902014-06-03 13:32:54 -07002876 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002877 if (config->type == AUDIO_PORT_TYPE_MIX) {
2878 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002879 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002880 if (outputDesc == NULL) {
2881 return BAD_VALUE;
2882 }
Eric Laurent84c70242014-06-23 08:46:27 -07002883 ALOG_ASSERT(!outputDesc->isDuplicated(),
2884 "setAudioPortConfig() called on duplicated output %d",
2885 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002886 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002887 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002888 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002889 if (inputDesc == NULL) {
2890 return BAD_VALUE;
2891 }
Eric Laurenta121f902014-06-03 13:32:54 -07002892 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002893 } else {
2894 return BAD_VALUE;
2895 }
2896 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2897 sp<DeviceDescriptor> deviceDesc;
2898 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2899 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2900 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2901 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2902 } else {
2903 return BAD_VALUE;
2904 }
2905 if (deviceDesc == NULL) {
2906 return BAD_VALUE;
2907 }
Eric Laurenta121f902014-06-03 13:32:54 -07002908 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002909 } else {
2910 return BAD_VALUE;
2911 }
2912
Eric Laurenta121f902014-06-03 13:32:54 -07002913 struct audio_port_config backupConfig;
2914 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2915 if (status == NO_ERROR) {
2916 struct audio_port_config newConfig;
2917 audioPortConfig->toAudioPortConfig(&newConfig, config);
2918 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002919 }
Eric Laurenta121f902014-06-03 13:32:54 -07002920 if (status != NO_ERROR) {
2921 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002922 }
Eric Laurente1715a42014-05-20 11:30:42 -07002923
2924 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002925}
2926
2927void AudioPolicyManager::clearAudioPatches(uid_t uid)
2928{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002929 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002930 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2931 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002932 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002933 }
2934 }
2935}
2936
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002937status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2938 audio_io_handle_t *ioHandle,
2939 audio_devices_t *device)
2940{
2941 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2942 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002943 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002944
2945 mSoundTriggerSessions.add(*session, *ioHandle);
2946
2947 return NO_ERROR;
2948}
2949
2950status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2951{
2952 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2953 if (index < 0) {
2954 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2955 return BAD_VALUE;
2956 }
2957
2958 mSoundTriggerSessions.removeItem(session);
2959 return NO_ERROR;
2960}
2961
Eric Laurent6a94d692014-05-20 11:18:06 -07002962status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2963 const sp<AudioPatch>& patch)
2964{
2965 ssize_t index = mAudioPatches.indexOfKey(handle);
2966
2967 if (index >= 0) {
2968 ALOGW("addAudioPatch() patch %d already in", handle);
2969 return ALREADY_EXISTS;
2970 }
2971 mAudioPatches.add(handle, patch);
2972 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2973 "sink handle %d",
2974 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2975 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2976 return NO_ERROR;
2977}
2978
2979status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2980{
2981 ssize_t index = mAudioPatches.indexOfKey(handle);
2982
2983 if (index < 0) {
2984 ALOGW("removeAudioPatch() patch %d not in", handle);
2985 return ALREADY_EXISTS;
2986 }
2987 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2988 mAudioPatches.valueAt(index)->mAfPatchHandle);
2989 mAudioPatches.removeItemsAt(index);
2990 return NO_ERROR;
2991}
2992
Eric Laurente552edb2014-03-10 17:42:56 -07002993// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002994// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002995// ----------------------------------------------------------------------------
2996
Eric Laurent3a4311c2014-03-17 12:00:47 -07002997uint32_t AudioPolicyManager::nextUniqueId()
2998{
2999 return android_atomic_inc(&mNextUniqueId);
3000}
3001
Eric Laurent6a94d692014-05-20 11:18:06 -07003002uint32_t AudioPolicyManager::nextAudioPortGeneration()
3003{
3004 return android_atomic_inc(&mAudioPortGeneration);
3005}
3006
Eric Laurente0720872014-03-11 09:30:41 -07003007AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003008 :
3009#ifdef AUDIO_POLICY_TEST
3010 Thread(false),
3011#endif //AUDIO_POLICY_TEST
3012 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07003013 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07003014 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
3015 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003016 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07003017 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003018 mAudioPortGeneration(1),
3019 mBeaconMuteRefCount(0),
3020 mBeaconPlayingRefCount(0),
3021 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003022{
Eric Laurent6a94d692014-05-20 11:18:06 -07003023 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07003024 mpClientInterface = clientInterface;
3025
Eric Laurent3b73df72014-03-11 09:06:29 -07003026 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
3027 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003028 }
3029
Eric Laurent1afeecb2014-05-14 08:52:28 -07003030 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07003031 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
3032 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
3033 ALOGE("could not load audio policy configuration file, setting defaults");
3034 defaultAudioPolicyConfig();
3035 }
3036 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003037 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003038
3039 // must be done after reading the policy
3040 initializeVolumeCurves();
3041
3042 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003043 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3044 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003045 for (size_t i = 0; i < mHwModules.size(); i++) {
3046 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3047 if (mHwModules[i]->mHandle == 0) {
3048 ALOGW("could not open HW module %s", mHwModules[i]->mName);
3049 continue;
3050 }
3051 // open all output streams needed to access attached devices
3052 // except for direct output streams that are only opened when they are actually
3053 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003054 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003055 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3056 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003057 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003058
Eric Laurent3a4311c2014-03-17 12:00:47 -07003059 if (outProfile->mSupportedDevices.isEmpty()) {
3060 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3061 continue;
3062 }
3063
Eric Laurentd78f1532014-09-16 16:38:20 -07003064 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3065 continue;
3066 }
Eric Laurent83b88082014-06-20 18:31:16 -07003067 audio_devices_t profileType = outProfile->mSupportedDevices.types();
3068 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3069 profileType = mDefaultOutputDevice->mDeviceType;
3070 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07003071 // chose first device present in mSupportedDevices also part of
3072 // outputDeviceTypes
3073 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3074 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3075 if ((profileType & outputDeviceTypes) != 0) {
3076 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003077 }
Eric Laurente552edb2014-03-10 17:42:56 -07003078 }
3079 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003080 if ((profileType & outputDeviceTypes) == 0) {
3081 continue;
3082 }
3083 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3084
3085 outputDesc->mDevice = profileType;
3086 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3087 config.sample_rate = outputDesc->mSamplingRate;
3088 config.channel_mask = outputDesc->mChannelMask;
3089 config.format = outputDesc->mFormat;
3090 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3091 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3092 &output,
3093 &config,
3094 &outputDesc->mDevice,
3095 String8(""),
3096 &outputDesc->mLatency,
3097 outputDesc->mFlags);
3098
3099 if (status != NO_ERROR) {
3100 ALOGW("Cannot open output stream for device %08x on hw module %s",
3101 outputDesc->mDevice,
3102 mHwModules[i]->mName);
3103 } else {
3104 outputDesc->mSamplingRate = config.sample_rate;
3105 outputDesc->mChannelMask = config.channel_mask;
3106 outputDesc->mFormat = config.format;
3107
3108 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3109 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3110 ssize_t index =
3111 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3112 // give a valid ID to an attached device once confirmed it is reachable
3113 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3114 mAvailableOutputDevices[index]->mId = nextUniqueId();
3115 mAvailableOutputDevices[index]->mModule = mHwModules[i];
3116 }
3117 }
3118 if (mPrimaryOutput == 0 &&
3119 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3120 mPrimaryOutput = output;
3121 }
3122 addOutput(output, outputDesc);
3123 setOutputDevice(output,
3124 outputDesc->mDevice,
3125 true);
3126 }
Eric Laurente552edb2014-03-10 17:42:56 -07003127 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003128 // open input streams needed to access attached devices to validate
3129 // mAvailableInputDevices list
3130 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3131 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003132 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003133
Eric Laurent3a4311c2014-03-17 12:00:47 -07003134 if (inProfile->mSupportedDevices.isEmpty()) {
3135 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3136 continue;
3137 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003138 // chose first device present in mSupportedDevices also part of
3139 // inputDeviceTypes
3140 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3141 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3142 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3143 if (profileType & inputDeviceTypes) {
3144 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003145 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003146 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003147 if ((profileType & inputDeviceTypes) == 0) {
3148 continue;
3149 }
3150 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3151
3152 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3153 inputDesc->mDevice = profileType;
3154
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003155 // find the address
3156 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3157 // the inputs vector must be of size 1, but we don't want to crash here
3158 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3159 : String8("");
3160 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3161 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3162
Eric Laurentd78f1532014-09-16 16:38:20 -07003163 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3164 config.sample_rate = inputDesc->mSamplingRate;
3165 config.channel_mask = inputDesc->mChannelMask;
3166 config.format = inputDesc->mFormat;
3167 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3168 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3169 &input,
3170 &config,
3171 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003172 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003173 AUDIO_SOURCE_MIC,
3174 AUDIO_INPUT_FLAG_NONE);
3175
3176 if (status == NO_ERROR) {
3177 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3178 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3179 ssize_t index =
3180 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3181 // give a valid ID to an attached device once confirmed it is reachable
3182 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3183 mAvailableInputDevices[index]->mId = nextUniqueId();
3184 mAvailableInputDevices[index]->mModule = mHwModules[i];
3185 }
3186 }
3187 mpClientInterface->closeInput(input);
3188 } else {
3189 ALOGW("Cannot open input stream for device %08x on hw module %s",
3190 inputDesc->mDevice,
3191 mHwModules[i]->mName);
3192 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003193 }
3194 }
3195 // make sure all attached devices have been allocated a unique ID
3196 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3197 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003198 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003199 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3200 continue;
3201 }
3202 i++;
3203 }
3204 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3205 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003206 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003207 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3208 continue;
3209 }
3210 i++;
3211 }
3212 // make sure default device is reachable
3213 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003214 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003215 }
Eric Laurente552edb2014-03-10 17:42:56 -07003216
3217 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3218
3219 updateDevicesAndOutputs();
3220
3221#ifdef AUDIO_POLICY_TEST
3222 if (mPrimaryOutput != 0) {
3223 AudioParameter outputCmd = AudioParameter();
3224 outputCmd.addInt(String8("set_id"), 0);
3225 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3226
3227 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3228 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003229 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3230 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003231 mTestLatencyMs = 0;
3232 mCurOutput = 0;
3233 mDirectOutput = false;
3234 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3235 mTestOutputs[i] = 0;
3236 }
3237
3238 const size_t SIZE = 256;
3239 char buffer[SIZE];
3240 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3241 run(buffer, ANDROID_PRIORITY_AUDIO);
3242 }
3243#endif //AUDIO_POLICY_TEST
3244}
3245
Eric Laurente0720872014-03-11 09:30:41 -07003246AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003247{
3248#ifdef AUDIO_POLICY_TEST
3249 exit();
3250#endif //AUDIO_POLICY_TEST
3251 for (size_t i = 0; i < mOutputs.size(); i++) {
3252 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003253 }
3254 for (size_t i = 0; i < mInputs.size(); i++) {
3255 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003256 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003257 mAvailableOutputDevices.clear();
3258 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003259 mOutputs.clear();
3260 mInputs.clear();
3261 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003262}
3263
Eric Laurente0720872014-03-11 09:30:41 -07003264status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003265{
3266 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3267}
3268
3269#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003270bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003271{
3272 ALOGV("entering threadLoop()");
3273 while (!exitPending())
3274 {
3275 String8 command;
3276 int valueInt;
3277 String8 value;
3278
3279 Mutex::Autolock _l(mLock);
3280 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3281
3282 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3283 AudioParameter param = AudioParameter(command);
3284
3285 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3286 valueInt != 0) {
3287 ALOGV("Test command %s received", command.string());
3288 String8 target;
3289 if (param.get(String8("target"), target) != NO_ERROR) {
3290 target = "Manager";
3291 }
3292 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3293 param.remove(String8("test_cmd_policy_output"));
3294 mCurOutput = valueInt;
3295 }
3296 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3297 param.remove(String8("test_cmd_policy_direct"));
3298 if (value == "false") {
3299 mDirectOutput = false;
3300 } else if (value == "true") {
3301 mDirectOutput = true;
3302 }
3303 }
3304 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3305 param.remove(String8("test_cmd_policy_input"));
3306 mTestInput = valueInt;
3307 }
3308
3309 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3310 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003311 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003312 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003313 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003314 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003315 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003316 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003317 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003318 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003319 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003320 if (target == "Manager") {
3321 mTestFormat = format;
3322 } else if (mTestOutputs[mCurOutput] != 0) {
3323 AudioParameter outputParam = AudioParameter();
3324 outputParam.addInt(String8("format"), format);
3325 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3326 }
3327 }
3328 }
3329 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3330 param.remove(String8("test_cmd_policy_channels"));
3331 int channels = 0;
3332
3333 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003334 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003335 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003336 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003337 }
3338 if (channels != 0) {
3339 if (target == "Manager") {
3340 mTestChannels = channels;
3341 } else if (mTestOutputs[mCurOutput] != 0) {
3342 AudioParameter outputParam = AudioParameter();
3343 outputParam.addInt(String8("channels"), channels);
3344 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3345 }
3346 }
3347 }
3348 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3349 param.remove(String8("test_cmd_policy_sampleRate"));
3350 if (valueInt >= 0 && valueInt <= 96000) {
3351 int samplingRate = valueInt;
3352 if (target == "Manager") {
3353 mTestSamplingRate = samplingRate;
3354 } else if (mTestOutputs[mCurOutput] != 0) {
3355 AudioParameter outputParam = AudioParameter();
3356 outputParam.addInt(String8("sampling_rate"), samplingRate);
3357 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3358 }
3359 }
3360 }
3361
3362 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3363 param.remove(String8("test_cmd_policy_reopen"));
3364
Eric Laurent1f2f2232014-06-02 12:01:23 -07003365 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003366 mpClientInterface->closeOutput(mPrimaryOutput);
3367
3368 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3369
Eric Laurente552edb2014-03-10 17:42:56 -07003370 mOutputs.removeItem(mPrimaryOutput);
3371
Eric Laurent1f2f2232014-06-02 12:01:23 -07003372 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003373 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003374 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3375 config.sample_rate = outputDesc->mSamplingRate;
3376 config.channel_mask = outputDesc->mChannelMask;
3377 config.format = outputDesc->mFormat;
3378 status_t status = mpClientInterface->openOutput(moduleHandle,
3379 &mPrimaryOutput,
3380 &config,
3381 &outputDesc->mDevice,
3382 String8(""),
3383 &outputDesc->mLatency,
3384 outputDesc->mFlags);
3385 if (status != NO_ERROR) {
3386 ALOGE("Failed to reopen hardware output stream, "
3387 "samplingRate: %d, format %d, channels %d",
3388 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003389 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003390 outputDesc->mSamplingRate = config.sample_rate;
3391 outputDesc->mChannelMask = config.channel_mask;
3392 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003393 AudioParameter outputCmd = AudioParameter();
3394 outputCmd.addInt(String8("set_id"), 0);
3395 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3396 addOutput(mPrimaryOutput, outputDesc);
3397 }
3398 }
3399
3400
3401 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3402 }
3403 }
3404 return false;
3405}
3406
Eric Laurente0720872014-03-11 09:30:41 -07003407void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003408{
3409 {
3410 AutoMutex _l(mLock);
3411 requestExit();
3412 mWaitWorkCV.signal();
3413 }
3414 requestExitAndWait();
3415}
3416
Eric Laurente0720872014-03-11 09:30:41 -07003417int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003418{
3419 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3420 if (output == mTestOutputs[i]) return i;
3421 }
3422 return 0;
3423}
3424#endif //AUDIO_POLICY_TEST
3425
3426// ---
3427
Eric Laurent1f2f2232014-06-02 12:01:23 -07003428void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003429{
Eric Laurent1c333e22014-05-20 10:48:17 -07003430 outputDesc->mIoHandle = output;
3431 outputDesc->mId = nextUniqueId();
3432 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003433 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003434}
3435
Eric Laurent1f2f2232014-06-02 12:01:23 -07003436void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003437{
Eric Laurent1c333e22014-05-20 10:48:17 -07003438 inputDesc->mIoHandle = input;
3439 inputDesc->mId = nextUniqueId();
3440 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003441 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003442}
Eric Laurente552edb2014-03-10 17:42:56 -07003443
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003444void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003445 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003446 const String8 address /*in*/,
3447 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003448 sp<DeviceDescriptor> devDesc =
3449 desc->mProfile->mSupportedDevices.getDevice(device, address);
3450 if (devDesc != 0) {
3451 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3452 desc->mIoHandle, address.string());
3453 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003454 }
3455}
3456
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003457status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003458 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003459 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003460 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003461{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003462 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003463 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003464 // erase all current sample rates, formats and channel masks
3465 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003466
Eric Laurent3b73df72014-03-11 09:06:29 -07003467 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003468 // first list already open outputs that can be routed to this device
3469 for (size_t i = 0; i < mOutputs.size(); i++) {
3470 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003471 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003472 if (!deviceDistinguishesOnAddress(device)) {
3473 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3474 outputs.add(mOutputs.keyAt(i));
3475 } else {
3476 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003477 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003478 }
Eric Laurente552edb2014-03-10 17:42:56 -07003479 }
3480 }
3481 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003482 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003483 for (size_t i = 0; i < mHwModules.size(); i++)
3484 {
3485 if (mHwModules[i]->mHandle == 0) {
3486 continue;
3487 }
3488 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3489 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003490 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3491 if (profile->mSupportedDevices.types() & device) {
3492 if (!deviceDistinguishesOnAddress(device) ||
3493 address == profile->mSupportedDevices[0]->mAddress) {
3494 profiles.add(profile);
3495 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3496 }
Eric Laurente552edb2014-03-10 17:42:56 -07003497 }
3498 }
3499 }
3500
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003501 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3502
Eric Laurente552edb2014-03-10 17:42:56 -07003503 if (profiles.isEmpty() && outputs.isEmpty()) {
3504 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3505 return BAD_VALUE;
3506 }
3507
3508 // open outputs for matching profiles if needed. Direct outputs are also opened to
3509 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3510 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003511 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003512
3513 // nothing to do if one output is already opened for this profile
3514 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003515 for (j = 0; j < outputs.size(); j++) {
3516 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003517 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003518 // matching profile: save the sample rates, format and channel masks supported
3519 // by the profile in our device descriptor
3520 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003521 break;
3522 }
3523 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003524 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003525 continue;
3526 }
3527
Eric Laurent83b88082014-06-20 18:31:16 -07003528 ALOGV("opening output for device %08x with params %s profile %p",
3529 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003530 desc = new AudioOutputDescriptor(profile);
3531 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003532 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3533 config.sample_rate = desc->mSamplingRate;
3534 config.channel_mask = desc->mChannelMask;
3535 config.format = desc->mFormat;
3536 config.offload_info.sample_rate = desc->mSamplingRate;
3537 config.offload_info.channel_mask = desc->mChannelMask;
3538 config.offload_info.format = desc->mFormat;
3539 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3540 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3541 &output,
3542 &config,
3543 &desc->mDevice,
3544 address,
3545 &desc->mLatency,
3546 desc->mFlags);
3547 if (status == NO_ERROR) {
3548 desc->mSamplingRate = config.sample_rate;
3549 desc->mChannelMask = config.channel_mask;
3550 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003551
Eric Laurentd4692962014-05-05 18:13:44 -07003552 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003553 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003554 char *param = audio_device_address_to_parameter(device, address);
3555 mpClientInterface->setParameters(output, String8(param));
3556 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003557 }
3558
Eric Laurentd4692962014-05-05 18:13:44 -07003559 // Here is where we step through and resolve any "dynamic" fields
3560 String8 reply;
3561 char *value;
3562 if (profile->mSamplingRates[0] == 0) {
3563 reply = mpClientInterface->getParameters(output,
3564 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003565 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003566 reply.string());
3567 value = strpbrk((char *)reply.string(), "=");
3568 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003569 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003570 }
Eric Laurentd4692962014-05-05 18:13:44 -07003571 }
3572 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3573 reply = mpClientInterface->getParameters(output,
3574 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003575 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003576 reply.string());
3577 value = strpbrk((char *)reply.string(), "=");
3578 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003579 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003580 }
Eric Laurentd4692962014-05-05 18:13:44 -07003581 }
3582 if (profile->mChannelMasks[0] == 0) {
3583 reply = mpClientInterface->getParameters(output,
3584 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003585 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003586 reply.string());
3587 value = strpbrk((char *)reply.string(), "=");
3588 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003589 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003590 }
Eric Laurentd4692962014-05-05 18:13:44 -07003591 }
3592 if (((profile->mSamplingRates[0] == 0) &&
3593 (profile->mSamplingRates.size() < 2)) ||
3594 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3595 (profile->mFormats.size() < 2)) ||
3596 ((profile->mChannelMasks[0] == 0) &&
3597 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003598 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003599 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003600 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003601 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3602 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003603 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003604 config.sample_rate = profile->pickSamplingRate();
3605 config.channel_mask = profile->pickChannelMask();
3606 config.format = profile->pickFormat();
3607 config.offload_info.sample_rate = config.sample_rate;
3608 config.offload_info.channel_mask = config.channel_mask;
3609 config.offload_info.format = config.format;
3610 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3611 &output,
3612 &config,
3613 &desc->mDevice,
3614 address,
3615 &desc->mLatency,
3616 desc->mFlags);
3617 if (status == NO_ERROR) {
3618 desc->mSamplingRate = config.sample_rate;
3619 desc->mChannelMask = config.channel_mask;
3620 desc->mFormat = config.format;
3621 } else {
3622 output = AUDIO_IO_HANDLE_NONE;
3623 }
Eric Laurentd4692962014-05-05 18:13:44 -07003624 }
3625
Eric Laurentcf2c0212014-07-25 16:20:43 -07003626 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003627 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003628 if (deviceDistinguishesOnAddress(device) && address != "0") {
3629 ssize_t index = mPolicyMixes.indexOfKey(address);
3630 if (index >= 0) {
3631 mPolicyMixes[index]->mOutput = desc;
Eric Laurentc722f302014-12-10 11:21:49 -08003632 desc->mPolicyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08003633 } else {
3634 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3635 address.string());
3636 }
Eric Laurentc722f302014-12-10 11:21:49 -08003637 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3638 // no duplicated output for direct outputs and
3639 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003640 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003641
Eric Laurentd4692962014-05-05 18:13:44 -07003642 // set initial stream volume for device
3643 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003644
Eric Laurentd4692962014-05-05 18:13:44 -07003645 //TODO: configure audio effect output stage here
3646
3647 // open a duplicating output thread for the new output and the primary output
3648 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3649 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003650 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003651 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003652 sp<AudioOutputDescriptor> dupOutputDesc =
3653 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003654 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3655 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3656 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3657 dupOutputDesc->mFormat = desc->mFormat;
3658 dupOutputDesc->mChannelMask = desc->mChannelMask;
3659 dupOutputDesc->mLatency = desc->mLatency;
3660 addOutput(duplicatedOutput, dupOutputDesc);
3661 applyStreamVolumes(duplicatedOutput, device, 0, true);
3662 } else {
3663 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3664 mPrimaryOutput, output);
3665 mpClientInterface->closeOutput(output);
3666 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003667 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003668 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003669 }
Eric Laurente552edb2014-03-10 17:42:56 -07003670 }
3671 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003672 } else {
3673 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003674 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003675 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003676 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003677 profiles.removeAt(profile_index);
3678 profile_index--;
3679 } else {
3680 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003681 devDesc->importAudioPort(profile);
3682
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003683 if (deviceDistinguishesOnAddress(device)) {
3684 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3685 device, address.string());
3686 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3687 NULL/*patch handle*/, address.string());
3688 }
Eric Laurente552edb2014-03-10 17:42:56 -07003689 ALOGV("checkOutputsForDevice(): adding output %d", output);
3690 }
3691 }
3692
3693 if (profiles.isEmpty()) {
3694 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3695 return BAD_VALUE;
3696 }
Eric Laurentd4692962014-05-05 18:13:44 -07003697 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003698 // check if one opened output is not needed any more after disconnecting one device
3699 for (size_t i = 0; i < mOutputs.size(); i++) {
3700 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003701 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003702 // exact match on device
3703 if (deviceDistinguishesOnAddress(device) &&
3704 (desc->mProfile->mSupportedDevices.types() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003705 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08003706 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003707 & mAvailableOutputDevices.types())) {
3708 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3709 mOutputs.keyAt(i));
3710 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003711 }
Eric Laurente552edb2014-03-10 17:42:56 -07003712 }
3713 }
Eric Laurentd4692962014-05-05 18:13:44 -07003714 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003715 for (size_t i = 0; i < mHwModules.size(); i++)
3716 {
3717 if (mHwModules[i]->mHandle == 0) {
3718 continue;
3719 }
3720 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3721 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003722 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003723 if (profile->mSupportedDevices.types() & device) {
3724 ALOGV("checkOutputsForDevice(): "
3725 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003726 if (profile->mSamplingRates[0] == 0) {
3727 profile->mSamplingRates.clear();
3728 profile->mSamplingRates.add(0);
3729 }
3730 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3731 profile->mFormats.clear();
3732 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3733 }
3734 if (profile->mChannelMasks[0] == 0) {
3735 profile->mChannelMasks.clear();
3736 profile->mChannelMasks.add(0);
3737 }
3738 }
3739 }
3740 }
3741 }
3742 return NO_ERROR;
3743}
3744
Eric Laurentd4692962014-05-05 18:13:44 -07003745status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3746 audio_policy_dev_state_t state,
3747 SortedVector<audio_io_handle_t>& inputs,
3748 const String8 address)
3749{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003750 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003751 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3752 // first list already open inputs that can be routed to this device
3753 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3754 desc = mInputs.valueAt(input_index);
3755 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3756 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3757 inputs.add(mInputs.keyAt(input_index));
3758 }
3759 }
3760
3761 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003762 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003763 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3764 {
3765 if (mHwModules[module_idx]->mHandle == 0) {
3766 continue;
3767 }
3768 for (size_t profile_index = 0;
3769 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3770 profile_index++)
3771 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003772 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3773
3774 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3775 if (!deviceDistinguishesOnAddress(device) ||
3776 address == profile->mSupportedDevices[0]->mAddress) {
3777 profiles.add(profile);
3778 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3779 profile_index, module_idx);
3780 }
Eric Laurentd4692962014-05-05 18:13:44 -07003781 }
3782 }
3783 }
3784
3785 if (profiles.isEmpty() && inputs.isEmpty()) {
3786 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3787 return BAD_VALUE;
3788 }
3789
3790 // open inputs for matching profiles if needed. Direct inputs are also opened to
3791 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3792 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3793
Eric Laurent1c333e22014-05-20 10:48:17 -07003794 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003795 // nothing to do if one input is already opened for this profile
3796 size_t input_index;
3797 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3798 desc = mInputs.valueAt(input_index);
3799 if (desc->mProfile == profile) {
3800 break;
3801 }
3802 }
3803 if (input_index != mInputs.size()) {
3804 continue;
3805 }
3806
3807 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3808 desc = new AudioInputDescriptor(profile);
3809 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003810 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3811 config.sample_rate = desc->mSamplingRate;
3812 config.channel_mask = desc->mChannelMask;
3813 config.format = desc->mFormat;
3814 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3815 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3816 &input,
3817 &config,
3818 &desc->mDevice,
3819 address,
3820 AUDIO_SOURCE_MIC,
3821 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003822
Eric Laurentcf2c0212014-07-25 16:20:43 -07003823 if (status == NO_ERROR) {
3824 desc->mSamplingRate = config.sample_rate;
3825 desc->mChannelMask = config.channel_mask;
3826 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003827
Eric Laurentd4692962014-05-05 18:13:44 -07003828 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003829 char *param = audio_device_address_to_parameter(device, address);
3830 mpClientInterface->setParameters(input, String8(param));
3831 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003832 }
3833
3834 // Here is where we step through and resolve any "dynamic" fields
3835 String8 reply;
3836 char *value;
3837 if (profile->mSamplingRates[0] == 0) {
3838 reply = mpClientInterface->getParameters(input,
3839 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3840 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3841 reply.string());
3842 value = strpbrk((char *)reply.string(), "=");
3843 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003844 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003845 }
3846 }
3847 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3848 reply = mpClientInterface->getParameters(input,
3849 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3850 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3851 value = strpbrk((char *)reply.string(), "=");
3852 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003853 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003854 }
3855 }
3856 if (profile->mChannelMasks[0] == 0) {
3857 reply = mpClientInterface->getParameters(input,
3858 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3859 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3860 reply.string());
3861 value = strpbrk((char *)reply.string(), "=");
3862 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003863 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003864 }
3865 }
3866 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3867 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3868 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3869 ALOGW("checkInputsForDevice() direct input missing param");
3870 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003871 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003872 }
3873
3874 if (input != 0) {
3875 addInput(input, desc);
3876 }
3877 } // endif input != 0
3878
Eric Laurentcf2c0212014-07-25 16:20:43 -07003879 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003880 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003881 profiles.removeAt(profile_index);
3882 profile_index--;
3883 } else {
3884 inputs.add(input);
3885 ALOGV("checkInputsForDevice(): adding input %d", input);
3886 }
3887 } // end scan profiles
3888
3889 if (profiles.isEmpty()) {
3890 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3891 return BAD_VALUE;
3892 }
3893 } else {
3894 // Disconnect
3895 // check if one opened input is not needed any more after disconnecting one device
3896 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3897 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003898 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3899 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003900 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3901 mInputs.keyAt(input_index));
3902 inputs.add(mInputs.keyAt(input_index));
3903 }
3904 }
3905 // Clear any profiles associated with the disconnected device.
3906 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3907 if (mHwModules[module_index]->mHandle == 0) {
3908 continue;
3909 }
3910 for (size_t profile_index = 0;
3911 profile_index < mHwModules[module_index]->mInputProfiles.size();
3912 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003913 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003914 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003915 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003916 profile_index, module_index);
3917 if (profile->mSamplingRates[0] == 0) {
3918 profile->mSamplingRates.clear();
3919 profile->mSamplingRates.add(0);
3920 }
3921 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3922 profile->mFormats.clear();
3923 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3924 }
3925 if (profile->mChannelMasks[0] == 0) {
3926 profile->mChannelMasks.clear();
3927 profile->mChannelMasks.add(0);
3928 }
3929 }
3930 }
3931 }
3932 } // end disconnect
3933
3934 return NO_ERROR;
3935}
3936
3937
Eric Laurente0720872014-03-11 09:30:41 -07003938void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003939{
3940 ALOGV("closeOutput(%d)", output);
3941
Eric Laurent1f2f2232014-06-02 12:01:23 -07003942 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003943 if (outputDesc == NULL) {
3944 ALOGW("closeOutput() unknown output %d", output);
3945 return;
3946 }
3947
Eric Laurent275e8e92014-11-30 15:14:47 -08003948 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3949 if (mPolicyMixes[i]->mOutput == outputDesc) {
3950 mPolicyMixes[i]->mOutput.clear();
3951 }
3952 }
3953
Eric Laurente552edb2014-03-10 17:42:56 -07003954 // look for duplicated outputs connected to the output being removed.
3955 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003956 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003957 if (dupOutputDesc->isDuplicated() &&
3958 (dupOutputDesc->mOutput1 == outputDesc ||
3959 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003960 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003961 if (dupOutputDesc->mOutput1 == outputDesc) {
3962 outputDesc2 = dupOutputDesc->mOutput2;
3963 } else {
3964 outputDesc2 = dupOutputDesc->mOutput1;
3965 }
3966 // As all active tracks on duplicated output will be deleted,
3967 // and as they were also referenced on the other output, the reference
3968 // count for their stream type must be adjusted accordingly on
3969 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003970 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003971 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003972 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003973 }
3974 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3975 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3976
3977 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003978 mOutputs.removeItem(duplicatedOutput);
3979 }
3980 }
3981
Eric Laurent05b90f82014-08-27 15:32:29 -07003982 nextAudioPortGeneration();
3983
3984 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3985 if (index >= 0) {
3986 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3987 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3988 mAudioPatches.removeItemsAt(index);
3989 mpClientInterface->onAudioPatchListUpdate();
3990 }
3991
Eric Laurente552edb2014-03-10 17:42:56 -07003992 AudioParameter param;
3993 param.add(String8("closing"), String8("true"));
3994 mpClientInterface->setParameters(output, param.toString());
3995
3996 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003997 mOutputs.removeItem(output);
3998 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003999}
4000
4001void AudioPolicyManager::closeInput(audio_io_handle_t input)
4002{
4003 ALOGV("closeInput(%d)", input);
4004
4005 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4006 if (inputDesc == NULL) {
4007 ALOGW("closeInput() unknown input %d", input);
4008 return;
4009 }
4010
Eric Laurent6a94d692014-05-20 11:18:06 -07004011 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004012
4013 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4014 if (index >= 0) {
4015 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4016 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4017 mAudioPatches.removeItemsAt(index);
4018 mpClientInterface->onAudioPatchListUpdate();
4019 }
4020
4021 mpClientInterface->closeInput(input);
4022 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004023}
4024
Eric Laurente0720872014-03-11 09:30:41 -07004025SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07004026 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004027{
4028 SortedVector<audio_io_handle_t> outputs;
4029
4030 ALOGVV("getOutputsForDevice() device %04x", device);
4031 for (size_t i = 0; i < openOutputs.size(); i++) {
4032 ALOGVV("output %d isDuplicated=%d device=%04x",
4033 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4034 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4035 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4036 outputs.add(openOutputs.keyAt(i));
4037 }
4038 }
4039 return outputs;
4040}
4041
Eric Laurente0720872014-03-11 09:30:41 -07004042bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07004043 SortedVector<audio_io_handle_t>& outputs2)
4044{
4045 if (outputs1.size() != outputs2.size()) {
4046 return false;
4047 }
4048 for (size_t i = 0; i < outputs1.size(); i++) {
4049 if (outputs1[i] != outputs2[i]) {
4050 return false;
4051 }
4052 }
4053 return true;
4054}
4055
Eric Laurente0720872014-03-11 09:30:41 -07004056void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004057{
4058 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4059 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4060 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4061 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4062
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004063 // also take into account external policy-related changes: add all outputs which are
4064 // associated with policies in the "before" and "after" output vectors
4065 ALOGVV("checkOutputForStrategy(): policy related outputs");
4066 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
4067 const sp<AudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
4068 if (desc != 0 && desc->mPolicyMix != NULL) {
4069 srcOutputs.add(desc->mIoHandle);
4070 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4071 }
4072 }
4073 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
4074 const sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4075 if (desc != 0 && desc->mPolicyMix != NULL) {
4076 dstOutputs.add(desc->mIoHandle);
4077 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4078 }
4079 }
4080
Eric Laurente552edb2014-03-10 17:42:56 -07004081 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4082 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4083 strategy, srcOutputs[0], dstOutputs[0]);
4084 // mute strategy while moving tracks from one output to another
4085 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004086 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004087 if (desc->isStrategyActive(strategy)) {
4088 setStrategyMute(strategy, true, srcOutputs[i]);
4089 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4090 }
4091 }
4092
4093 // Move effects associated to this strategy from previous output to new output
4094 if (strategy == STRATEGY_MEDIA) {
4095 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4096 SortedVector<audio_io_handle_t> moved;
4097 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004098 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4099 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4100 effectDesc->mIo != fxOutput) {
4101 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004102 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4103 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004104 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004105 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004106 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004107 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004108 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004109 }
4110 }
4111 }
4112 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004113 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004114 if (i == AUDIO_STREAM_PATCH) {
4115 continue;
4116 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004117 if (getStrategy((audio_stream_type_t)i) == strategy) {
4118 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004119 }
4120 }
4121 }
4122}
4123
Eric Laurente0720872014-03-11 09:30:41 -07004124void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004125{
Jon Eklund966095e2014-09-09 15:39:49 -05004126 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4127 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004128 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004129 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4130 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004131 checkOutputForStrategy(STRATEGY_SONIFICATION);
4132 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004133 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004134 checkOutputForStrategy(STRATEGY_MEDIA);
4135 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004136 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004137}
4138
Eric Laurente0720872014-03-11 09:30:41 -07004139audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004140{
Eric Laurente552edb2014-03-10 17:42:56 -07004141 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004142 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004143 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4144 return mOutputs.keyAt(i);
4145 }
4146 }
4147
4148 return 0;
4149}
4150
Eric Laurente0720872014-03-11 09:30:41 -07004151void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004152{
Eric Laurente552edb2014-03-10 17:42:56 -07004153 audio_io_handle_t a2dpOutput = getA2dpOutput();
4154 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004155 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004156 return;
4157 }
4158
Eric Laurent3a4311c2014-03-17 12:00:47 -07004159 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004160 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4161 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4162 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004163 // suspend A2DP output if:
4164 // (NOT already suspended) &&
4165 // ((SCO device is connected &&
4166 // (forced usage for communication || for record is SCO))) ||
4167 // (phone state is ringing || in call)
4168 //
4169 // restore A2DP output if:
4170 // (Already suspended) &&
4171 // ((SCO device is NOT connected ||
4172 // (forced usage NOT for communication && NOT for record is SCO))) &&
4173 // (phone state is NOT ringing && NOT in call)
4174 //
4175 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004176 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004177 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4178 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4179 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4180 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004181
4182 mpClientInterface->restoreOutput(a2dpOutput);
4183 mA2dpSuspended = false;
4184 }
4185 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004186 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004187 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4188 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4189 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4190 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004191
4192 mpClientInterface->suspendOutput(a2dpOutput);
4193 mA2dpSuspended = true;
4194 }
4195 }
4196}
4197
Eric Laurent1c333e22014-05-20 10:48:17 -07004198audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004199{
4200 audio_devices_t device = AUDIO_DEVICE_NONE;
4201
Eric Laurent1f2f2232014-06-02 12:01:23 -07004202 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004203
4204 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4205 if (index >= 0) {
4206 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4207 if (patchDesc->mUid != mUidCached) {
4208 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4209 outputDesc->device(), outputDesc->mPatchHandle);
4210 return outputDesc->device();
4211 }
4212 }
4213
Eric Laurente552edb2014-03-10 17:42:56 -07004214 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004215 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004216 // use device for strategy enforced audible
4217 // 2: we are in call or the strategy phone is active on the output:
4218 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004219 // 3: the strategy for enforced audible is active but not enforced on the output:
4220 // use the device for strategy enforced audible
4221 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004222 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004223 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004224 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004225 // 6: the strategy accessibility is active on the output:
4226 // use device for strategy accessibility
4227 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004228 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004229 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004230 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004231 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004232 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004233 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4234 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004235 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4236 } else if (isInCall() ||
4237 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4238 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004239 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4240 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004241 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4242 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4243 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4244 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004245 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4246 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004247 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4248 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4249 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4250 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004251 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4252 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004253 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4254 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004255 }
4256
Eric Laurent1c333e22014-05-20 10:48:17 -07004257 ALOGV("getNewOutputDevice() selected device %x", device);
4258 return device;
4259}
4260
4261audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4262{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004263 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004264
4265 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4266 if (index >= 0) {
4267 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4268 if (patchDesc->mUid != mUidCached) {
4269 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4270 inputDesc->mDevice, inputDesc->mPatchHandle);
4271 return inputDesc->mDevice;
4272 }
4273 }
4274
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004275 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07004276
4277 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004278 return device;
4279}
4280
Eric Laurente0720872014-03-11 09:30:41 -07004281uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004282 return (uint32_t)getStrategy(stream);
4283}
4284
Eric Laurente0720872014-03-11 09:30:41 -07004285audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004286 // By checking the range of stream before calling getStrategy, we avoid
4287 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4288 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004289 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004290 return AUDIO_DEVICE_NONE;
4291 }
4292 audio_devices_t devices;
4293 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4294 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4295 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4296 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004297 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004298 if (outputDesc->isStrategyActive(strategy)) {
4299 devices = outputDesc->device();
4300 break;
4301 }
Eric Laurente552edb2014-03-10 17:42:56 -07004302 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004303
4304 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4305 and doesn't really need to.*/
4306 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4307 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4308 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4309 }
4310
Eric Laurente552edb2014-03-10 17:42:56 -07004311 return devices;
4312}
4313
Eric Laurente0720872014-03-11 09:30:41 -07004314AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004315 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004316
4317 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4318
Eric Laurente552edb2014-03-10 17:42:56 -07004319 // stream to strategy mapping
4320 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004321 case AUDIO_STREAM_VOICE_CALL:
4322 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004323 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004324 case AUDIO_STREAM_RING:
4325 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004326 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004327 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004328 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004329 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004330 return STRATEGY_DTMF;
4331 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004332 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004333 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004334 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4335 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004336 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004337 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004338 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004339 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004340 case AUDIO_STREAM_TTS:
4341 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004342 case AUDIO_STREAM_ACCESSIBILITY:
4343 return STRATEGY_ACCESSIBILITY;
4344 case AUDIO_STREAM_REROUTING:
4345 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004346 }
4347}
4348
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004349uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4350 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004351 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4352 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4353 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004354 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4355 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4356 }
4357
4358 // usage to strategy mapping
4359 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004360 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4361 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4362 return (uint32_t) STRATEGY_SONIFICATION;
4363 }
4364 if (isInCall()) {
4365 return (uint32_t) STRATEGY_PHONE;
4366 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004367 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004368
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004369 case AUDIO_USAGE_MEDIA:
4370 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004371 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4372 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4373 return (uint32_t) STRATEGY_MEDIA;
4374
4375 case AUDIO_USAGE_VOICE_COMMUNICATION:
4376 return (uint32_t) STRATEGY_PHONE;
4377
4378 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4379 return (uint32_t) STRATEGY_DTMF;
4380
4381 case AUDIO_USAGE_ALARM:
4382 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4383 return (uint32_t) STRATEGY_SONIFICATION;
4384
4385 case AUDIO_USAGE_NOTIFICATION:
4386 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4387 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4388 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4389 case AUDIO_USAGE_NOTIFICATION_EVENT:
4390 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4391
4392 case AUDIO_USAGE_UNKNOWN:
4393 default:
4394 return (uint32_t) STRATEGY_MEDIA;
4395 }
4396}
4397
Eric Laurente0720872014-03-11 09:30:41 -07004398void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004399 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004400 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004401 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4402 updateDevicesAndOutputs();
4403 break;
4404 default:
4405 break;
4406 }
4407}
4408
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004409bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4410 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4411 if (s == (size_t) streamToIgnore) {
4412 continue;
4413 }
4414 for (size_t i = 0; i < mOutputs.size(); i++) {
4415 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4416 if (outputDesc->mRefCount[s] != 0) {
4417 return true;
4418 }
4419 }
4420 }
4421 return false;
4422}
4423
4424uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4425 switch(event) {
4426 case STARTING_OUTPUT:
4427 mBeaconMuteRefCount++;
4428 break;
4429 case STOPPING_OUTPUT:
4430 if (mBeaconMuteRefCount > 0) {
4431 mBeaconMuteRefCount--;
4432 }
4433 break;
4434 case STARTING_BEACON:
4435 mBeaconPlayingRefCount++;
4436 break;
4437 case STOPPING_BEACON:
4438 if (mBeaconPlayingRefCount > 0) {
4439 mBeaconPlayingRefCount--;
4440 }
4441 break;
4442 }
4443
4444 if (mBeaconMuteRefCount > 0) {
4445 // any playback causes beacon to be muted
4446 return setBeaconMute(true);
4447 } else {
4448 // no other playback: unmute when beacon starts playing, mute when it stops
4449 return setBeaconMute(mBeaconPlayingRefCount == 0);
4450 }
4451}
4452
4453uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4454 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4455 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4456 // keep track of muted state to avoid repeating mute/unmute operations
4457 if (mBeaconMuted != mute) {
4458 // mute/unmute AUDIO_STREAM_TTS on all outputs
4459 ALOGV("\t muting %d", mute);
4460 uint32_t maxLatency = 0;
4461 for (size_t i = 0; i < mOutputs.size(); i++) {
4462 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4463 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4464 desc->mIoHandle,
4465 0 /*delay*/, AUDIO_DEVICE_NONE);
4466 const uint32_t latency = desc->latency() * 2;
4467 if (latency > maxLatency) {
4468 maxLatency = latency;
4469 }
4470 }
4471 mBeaconMuted = mute;
4472 return maxLatency;
4473 }
4474 return 0;
4475}
4476
Eric Laurente0720872014-03-11 09:30:41 -07004477audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004478 bool fromCache)
4479{
4480 uint32_t device = AUDIO_DEVICE_NONE;
4481
4482 if (fromCache) {
4483 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4484 strategy, mDeviceForStrategy[strategy]);
4485 return mDeviceForStrategy[strategy];
4486 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004487 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004488 switch (strategy) {
4489
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004490 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4491 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4492 if (!device) {
4493 ALOGE("getDeviceForStrategy() no device found for "\
4494 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4495 }
4496 break;
4497
Eric Laurente552edb2014-03-10 17:42:56 -07004498 case STRATEGY_SONIFICATION_RESPECTFUL:
4499 if (isInCall()) {
4500 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004501 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004502 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4503 // while media is playing on a remote device, use the the sonification behavior.
4504 // Note that we test this usecase before testing if media is playing because
4505 // the isStreamActive() method only informs about the activity of a stream, not
4506 // if it's for local playback. Note also that we use the same delay between both tests
4507 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004508 //user "safe" speaker if available instead of normal speaker to avoid triggering
4509 //other acoustic safety mechanisms for notification
4510 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4511 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004512 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004513 // while media is playing (or has recently played), use the same device
4514 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4515 } else {
4516 // when media is not playing anymore, fall back on the sonification behavior
4517 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004518 //user "safe" speaker if available instead of normal speaker to avoid triggering
4519 //other acoustic safety mechanisms for notification
4520 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4521 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004522 }
4523
4524 break;
4525
4526 case STRATEGY_DTMF:
4527 if (!isInCall()) {
4528 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4529 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4530 break;
4531 }
4532 // when in call, DTMF and PHONE strategies follow the same rules
4533 // FALL THROUGH
4534
4535 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004536 // Force use of only devices on primary output if:
4537 // - in call AND
4538 // - cannot route from voice call RX OR
4539 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4540 if (mPhoneState == AUDIO_MODE_IN_CALL) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004541 audio_devices_t txDevice =
4542 getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -07004543 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4544 if (((mAvailableInputDevices.types() &
4545 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4546 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004547 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004548 AUDIO_DEVICE_API_VERSION_3_0))) {
4549 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4550 }
4551 }
Eric Laurente552edb2014-03-10 17:42:56 -07004552 // for phone strategy, we first consider the forced use and then the available devices by order
4553 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004554 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4555 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004556 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004557 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004558 if (device) break;
4559 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004560 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004561 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004562 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004563 if (device) break;
4564 // if SCO device is requested but no SCO device is available, fall back to default case
4565 // FALL THROUGH
4566
4567 default: // FORCE_NONE
4568 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004569 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004570 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004571 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004572 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004573 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004574 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004575 if (device) break;
4576 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004577 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004578 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004579 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004580 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004581 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4582 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004583 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004584 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004585 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004586 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004587 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004588 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004589 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004590 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004591 if (device) break;
4592 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004593 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004594 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004595 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004596 if (device == AUDIO_DEVICE_NONE) {
4597 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4598 }
4599 break;
4600
Eric Laurent3b73df72014-03-11 09:06:29 -07004601 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004602 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4603 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004604 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004605 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004606 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004607 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004608 if (device) break;
4609 }
Eric Laurentcd71a692014-12-16 12:01:12 -08004610 if (!isInCall()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004611 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004612 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004613 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004614 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004615 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004616 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004617 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004618 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004619 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004620 if (device) break;
4621 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004622 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4623 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004624 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004625 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004626 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004627 if (device == AUDIO_DEVICE_NONE) {
4628 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4629 }
4630 break;
4631 }
4632 break;
4633
4634 case STRATEGY_SONIFICATION:
4635
4636 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4637 // handleIncallSonification().
4638 if (isInCall()) {
4639 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4640 break;
4641 }
4642 // FALL THROUGH
4643
4644 case STRATEGY_ENFORCED_AUDIBLE:
4645 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4646 // except:
4647 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4648 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4649
4650 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004651 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004652 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004653 if (device == AUDIO_DEVICE_NONE) {
4654 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4655 }
4656 }
4657 // The second device used for sonification is the same as the device used by media strategy
4658 // FALL THROUGH
4659
Eric Laurent223fd5c2014-11-11 13:43:36 -08004660 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4661 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004662 if (strategy == STRATEGY_ACCESSIBILITY) {
4663 // do not route accessibility prompts to a digital output currently configured with a
4664 // compressed format as they would likely not be mixed and dropped.
4665 for (size_t i = 0; i < mOutputs.size(); i++) {
4666 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4667 audio_devices_t devices = desc->device() &
4668 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4669 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4670 devices != AUDIO_DEVICE_NONE) {
4671 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4672 }
4673 }
4674 }
4675 // FALL THROUGH
4676
Eric Laurent223fd5c2014-11-11 13:43:36 -08004677 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004678 case STRATEGY_MEDIA: {
4679 uint32_t device2 = AUDIO_DEVICE_NONE;
4680 if (strategy != STRATEGY_SONIFICATION) {
4681 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004682 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4683 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4684 }
Eric Laurente552edb2014-03-10 17:42:56 -07004685 }
4686 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004687 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004688 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004689 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004690 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004691 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004692 }
4693 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004694 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004695 }
4696 }
Hochi Huang327cb702014-09-21 09:47:31 +08004697 if ((device2 == AUDIO_DEVICE_NONE) &&
4698 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4699 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4700 }
Eric Laurente552edb2014-03-10 17:42:56 -07004701 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004702 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004703 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004704 if ((device2 == AUDIO_DEVICE_NONE)) {
4705 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4706 }
Eric Laurente552edb2014-03-10 17:42:56 -07004707 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004708 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004709 }
4710 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004711 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004712 }
4713 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004714 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004715 }
4716 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004717 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004718 }
4719 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4720 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004721 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004722 }
4723 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004724 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004725 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004726 }
4727 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004728 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004729 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004730 int device3 = AUDIO_DEVICE_NONE;
4731 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004732 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004733 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4734 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004735 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004736 }
Eric Laurente552edb2014-03-10 17:42:56 -07004737
Jungshik Jang839e4f32014-06-26 17:23:40 +09004738 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004739 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4740 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4741 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004742
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004743 // If hdmi system audio mode is on, remove speaker out of output list.
4744 if ((strategy == STRATEGY_MEDIA) &&
4745 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4746 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4747 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4748 }
4749
Eric Laurente552edb2014-03-10 17:42:56 -07004750 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004751 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004752 if (device == AUDIO_DEVICE_NONE) {
4753 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4754 }
4755 } break;
4756
4757 default:
4758 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4759 break;
4760 }
4761
4762 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4763 return device;
4764}
4765
Eric Laurente0720872014-03-11 09:30:41 -07004766void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004767{
4768 for (int i = 0; i < NUM_STRATEGIES; i++) {
4769 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4770 }
4771 mPreviousOutputs = mOutputs;
4772}
4773
Eric Laurent1f2f2232014-06-02 12:01:23 -07004774uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004775 audio_devices_t prevDevice,
4776 uint32_t delayMs)
4777{
4778 // mute/unmute strategies using an incompatible device combination
4779 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4780 // if unmuting, unmute only after the specified delay
4781 if (outputDesc->isDuplicated()) {
4782 return 0;
4783 }
4784
4785 uint32_t muteWaitMs = 0;
4786 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004787 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004788
4789 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4790 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004791 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004792 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4793 bool doMute = false;
4794
4795 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4796 doMute = true;
4797 outputDesc->mStrategyMutedByDevice[i] = true;
4798 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4799 doMute = true;
4800 outputDesc->mStrategyMutedByDevice[i] = false;
4801 }
Eric Laurent99401132014-05-07 19:48:15 -07004802 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004803 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004804 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004805 // skip output if it does not share any device with current output
4806 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4807 == AUDIO_DEVICE_NONE) {
4808 continue;
4809 }
4810 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4811 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4812 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4813 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4814 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004815 if (mute) {
4816 // FIXME: should not need to double latency if volume could be applied
4817 // immediately by the audioflinger mixer. We must account for the delay
4818 // between now and the next time the audioflinger thread for this output
4819 // will process a buffer (which corresponds to one buffer size,
4820 // usually 1/2 or 1/4 of the latency).
4821 if (muteWaitMs < desc->latency() * 2) {
4822 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004823 }
4824 }
4825 }
4826 }
4827 }
4828 }
4829
Eric Laurent99401132014-05-07 19:48:15 -07004830 // temporary mute output if device selection changes to avoid volume bursts due to
4831 // different per device volumes
4832 if (outputDesc->isActive() && (device != prevDevice)) {
4833 if (muteWaitMs < outputDesc->latency() * 2) {
4834 muteWaitMs = outputDesc->latency() * 2;
4835 }
4836 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4837 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004838 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004839 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004840 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004841 muteWaitMs *2, device);
4842 }
4843 }
4844 }
4845
Eric Laurente552edb2014-03-10 17:42:56 -07004846 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4847 if (muteWaitMs > delayMs) {
4848 muteWaitMs -= delayMs;
4849 usleep(muteWaitMs * 1000);
4850 return muteWaitMs;
4851 }
4852 return 0;
4853}
4854
Eric Laurente0720872014-03-11 09:30:41 -07004855uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004856 audio_devices_t device,
4857 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004858 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004859 audio_patch_handle_t *patchHandle,
4860 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004861{
4862 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004863 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004864 AudioParameter param;
4865 uint32_t muteWaitMs;
4866
4867 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004868 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4869 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004870 return muteWaitMs;
4871 }
4872 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4873 // output profile
4874 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004875 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004876 return 0;
4877 }
4878
4879 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004880 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004881
4882 audio_devices_t prevDevice = outputDesc->mDevice;
4883
4884 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4885
4886 if (device != AUDIO_DEVICE_NONE) {
4887 outputDesc->mDevice = device;
4888 }
4889 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4890
4891 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004892 // the requested device is AUDIO_DEVICE_NONE
4893 // OR the requested device is the same as current device
4894 // AND force is not specified
4895 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004896 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004897 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4898 outputDesc->mPatchHandle != 0) {
4899 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4900 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004901 return muteWaitMs;
4902 }
4903
4904 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004905
Eric Laurente552edb2014-03-10 17:42:56 -07004906 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004907 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004908 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004909 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004910 DeviceVector deviceList = (address == NULL) ?
4911 mAvailableOutputDevices.getDevicesFromType(device)
4912 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004913 if (!deviceList.isEmpty()) {
4914 struct audio_patch patch;
4915 outputDesc->toAudioPortConfig(&patch.sources[0]);
4916 patch.num_sources = 1;
4917 patch.num_sinks = 0;
4918 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4919 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004920 patch.num_sinks++;
4921 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004922 ssize_t index;
4923 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4924 index = mAudioPatches.indexOfKey(*patchHandle);
4925 } else {
4926 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4927 }
4928 sp< AudioPatch> patchDesc;
4929 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4930 if (index >= 0) {
4931 patchDesc = mAudioPatches.valueAt(index);
4932 afPatchHandle = patchDesc->mAfPatchHandle;
4933 }
4934
Eric Laurent1c333e22014-05-20 10:48:17 -07004935 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 &afPatchHandle,
4937 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004938 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4939 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004940 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004941 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004942 if (index < 0) {
4943 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4944 &patch, mUidCached);
4945 addAudioPatch(patchDesc->mHandle, patchDesc);
4946 } else {
4947 patchDesc->mPatch = patch;
4948 }
4949 patchDesc->mAfPatchHandle = afPatchHandle;
4950 patchDesc->mUid = mUidCached;
4951 if (patchHandle) {
4952 *patchHandle = patchDesc->mHandle;
4953 }
4954 outputDesc->mPatchHandle = patchDesc->mHandle;
4955 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004956 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004957 }
4958 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004959
4960 // inform all input as well
4961 for (size_t i = 0; i < mInputs.size(); i++) {
4962 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4963 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4964 AudioParameter inputCmd = AudioParameter();
4965 ALOGV("%s: inform input %d of device:%d", __func__,
4966 inputDescriptor->mIoHandle, device);
4967 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4968 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4969 inputCmd.toString(),
4970 delayMs);
4971 }
4972 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004973 }
Eric Laurente552edb2014-03-10 17:42:56 -07004974
4975 // update stream volumes according to new device
4976 applyStreamVolumes(output, device, delayMs);
4977
4978 return muteWaitMs;
4979}
4980
Eric Laurent1c333e22014-05-20 10:48:17 -07004981status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 int delayMs,
4983 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004984{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004985 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 ssize_t index;
4987 if (patchHandle) {
4988 index = mAudioPatches.indexOfKey(*patchHandle);
4989 } else {
4990 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4991 }
4992 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004993 return INVALID_OPERATION;
4994 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004995 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4996 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004997 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4998 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004999 removeAudioPatch(patchDesc->mHandle);
5000 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005001 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005002 return status;
5003}
5004
5005status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5006 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005007 bool force,
5008 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005009{
5010 status_t status = NO_ERROR;
5011
Eric Laurent1f2f2232014-06-02 12:01:23 -07005012 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005013 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5014 inputDesc->mDevice = device;
5015
5016 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5017 if (!deviceList.isEmpty()) {
5018 struct audio_patch patch;
5019 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005020 // AUDIO_SOURCE_HOTWORD is for internal use only:
5021 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005022 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
5023 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005024 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5025 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005026 patch.num_sinks = 1;
5027 //only one input device for now
5028 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005029 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005030 ssize_t index;
5031 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5032 index = mAudioPatches.indexOfKey(*patchHandle);
5033 } else {
5034 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5035 }
5036 sp< AudioPatch> patchDesc;
5037 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5038 if (index >= 0) {
5039 patchDesc = mAudioPatches.valueAt(index);
5040 afPatchHandle = patchDesc->mAfPatchHandle;
5041 }
5042
Eric Laurent1c333e22014-05-20 10:48:17 -07005043 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005044 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005045 0);
5046 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005047 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005048 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005049 if (index < 0) {
5050 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5051 &patch, mUidCached);
5052 addAudioPatch(patchDesc->mHandle, patchDesc);
5053 } else {
5054 patchDesc->mPatch = patch;
5055 }
5056 patchDesc->mAfPatchHandle = afPatchHandle;
5057 patchDesc->mUid = mUidCached;
5058 if (patchHandle) {
5059 *patchHandle = patchDesc->mHandle;
5060 }
5061 inputDesc->mPatchHandle = patchDesc->mHandle;
5062 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005063 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005064 }
5065 }
5066 }
5067 return status;
5068}
5069
Eric Laurent6a94d692014-05-20 11:18:06 -07005070status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5071 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005072{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005073 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005074 ssize_t index;
5075 if (patchHandle) {
5076 index = mAudioPatches.indexOfKey(*patchHandle);
5077 } else {
5078 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5079 }
5080 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005081 return INVALID_OPERATION;
5082 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005083 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5084 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005085 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5086 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005087 removeAudioPatch(patchDesc->mHandle);
5088 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005089 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005090 return status;
5091}
5092
5093sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08005094 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07005095 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005096 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005097 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07005098 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005099{
5100 // Choose an input profile based on the requested capture parameters: select the first available
5101 // profile supporting all requested parameters.
5102
5103 for (size_t i = 0; i < mHwModules.size(); i++)
5104 {
5105 if (mHwModules[i]->mHandle == 0) {
5106 continue;
5107 }
5108 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5109 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005110 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005111 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005112 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005113 &samplingRate /*updatedSamplingRate*/,
5114 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005115
Eric Laurente552edb2014-03-10 17:42:56 -07005116 return profile;
5117 }
5118 }
5119 }
5120 return NULL;
5121}
5122
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005123
5124audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
Eric Laurentc722f302014-12-10 11:21:49 -08005125 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005126{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005127 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5128 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005129
5130 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5131 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5132 continue;
5133 }
5134 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5135 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5136 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5137 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5138 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5139 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurentc722f302014-12-10 11:21:49 -08005140 if (policyMix != NULL) {
5141 *policyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005142 }
5143 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5144 }
5145 break;
5146 }
5147 }
5148 }
5149
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005150 return getDeviceForInputSource(inputSource);
5151}
5152
5153audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5154{
5155 uint32_t device = AUDIO_DEVICE_NONE;
5156 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5157 ~AUDIO_DEVICE_BIT_IN;
5158
Eric Laurente552edb2014-03-10 17:42:56 -07005159 switch (inputSource) {
5160 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005161 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005162 device = AUDIO_DEVICE_IN_VOICE_CALL;
5163 break;
5164 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005165 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005166
5167 case AUDIO_SOURCE_DEFAULT:
5168 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005169 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5170 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentdc136ff2014-12-16 12:24:18 -08005171 } else if ((mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO) &&
5172 (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET)) {
5173 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005174 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5175 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5176 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5177 device = AUDIO_DEVICE_IN_USB_DEVICE;
5178 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5179 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005180 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005181 break;
5182
5183 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5184 // Allow only use of devices on primary input if in call and HAL does not support routing
5185 // to voice call path.
5186 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5187 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5188 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5189 }
5190
5191 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5192 case AUDIO_POLICY_FORCE_BT_SCO:
5193 // if SCO device is requested but no SCO device is available, fall back to default case
5194 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5195 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5196 break;
5197 }
5198 // FALL THROUGH
5199
5200 default: // FORCE_NONE
5201 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5202 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5203 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5204 device = AUDIO_DEVICE_IN_USB_DEVICE;
5205 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5206 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5207 }
5208 break;
5209
5210 case AUDIO_POLICY_FORCE_SPEAKER:
5211 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5212 device = AUDIO_DEVICE_IN_BACK_MIC;
5213 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5214 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5215 }
5216 break;
5217 }
5218 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005219
Eric Laurente552edb2014-03-10 17:42:56 -07005220 case AUDIO_SOURCE_VOICE_RECOGNITION:
5221 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005222 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005223 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005224 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005225 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005226 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005227 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5228 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005229 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005230 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5231 }
5232 break;
5233 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005234 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005235 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005236 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005237 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5238 }
5239 break;
5240 case AUDIO_SOURCE_VOICE_DOWNLINK:
5241 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005242 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005243 device = AUDIO_DEVICE_IN_VOICE_CALL;
5244 }
5245 break;
5246 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005247 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005248 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5249 }
5250 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005251 case AUDIO_SOURCE_FM_TUNER:
5252 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5253 device = AUDIO_DEVICE_IN_FM_TUNER;
5254 }
5255 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005256 default:
5257 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5258 break;
5259 }
5260 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5261 return device;
5262}
5263
Eric Laurente0720872014-03-11 09:30:41 -07005264bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005265{
5266 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5267 device &= ~AUDIO_DEVICE_BIT_IN;
5268 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5269 return true;
5270 }
5271 return false;
5272}
5273
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005274bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005275 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005276}
5277
Eric Laurente0720872014-03-11 09:30:41 -07005278audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005279{
5280 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005281 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005282 if ((input_descriptor->mRefCount > 0)
5283 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5284 return mInputs.keyAt(i);
5285 }
5286 }
5287 return 0;
5288}
5289
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005290uint32_t AudioPolicyManager::activeInputsCount() const
5291{
5292 uint32_t count = 0;
5293 for (size_t i = 0; i < mInputs.size(); i++) {
5294 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5295 if (desc->mRefCount > 0) {
Eric Laurenta34c9ce2014-12-19 11:16:32 -08005296 count++;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005297 }
5298 }
5299 return count;
5300}
5301
Eric Laurente552edb2014-03-10 17:42:56 -07005302
Eric Laurente0720872014-03-11 09:30:41 -07005303audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005304{
5305 if (device == AUDIO_DEVICE_NONE) {
5306 // this happens when forcing a route update and no track is active on an output.
5307 // In this case the returned category is not important.
5308 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005309 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005310 // Multiple device selection is either:
5311 // - speaker + one other device: give priority to speaker in this case.
5312 // - one A2DP device + another device: happens with duplicated output. In this case
5313 // retain the device on the A2DP output as the other must not correspond to an active
5314 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005315 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005316 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5317 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005318 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5319 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5320 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5321 device = AUDIO_DEVICE_OUT_AUX_LINE;
5322 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5323 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005324 } else {
5325 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5326 }
5327 }
5328
Jon Eklund11c9fb12014-06-23 14:47:03 -05005329 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5330 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5331 device = AUDIO_DEVICE_OUT_SPEAKER;
5332
Eric Laurent3b73df72014-03-11 09:06:29 -07005333 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005334 "getDeviceForVolume() invalid device combination: %08x",
5335 device);
5336
5337 return device;
5338}
5339
Eric Laurente0720872014-03-11 09:30:41 -07005340AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005341{
5342 switch(getDeviceForVolume(device)) {
5343 case AUDIO_DEVICE_OUT_EARPIECE:
5344 return DEVICE_CATEGORY_EARPIECE;
5345 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5346 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5347 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5348 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5349 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5350 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5351 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005352 case AUDIO_DEVICE_OUT_LINE:
5353 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5354 /*USB? Remote submix?*/
5355 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005356 case AUDIO_DEVICE_OUT_SPEAKER:
5357 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5358 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005359 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5360 case AUDIO_DEVICE_OUT_USB_DEVICE:
5361 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5362 default:
5363 return DEVICE_CATEGORY_SPEAKER;
5364 }
5365}
5366
Eric Laurent223fd5c2014-11-11 13:43:36 -08005367/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005368float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005369 int indexInUi)
5370{
5371 device_category deviceCategory = getDeviceCategory(device);
5372 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5373
5374 // the volume index in the UI is relative to the min and max volume indices for this stream type
5375 int nbSteps = 1 + curve[VOLMAX].mIndex -
5376 curve[VOLMIN].mIndex;
5377 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5378 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5379
5380 // find what part of the curve this index volume belongs to, or if it's out of bounds
5381 int segment = 0;
5382 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5383 return 0.0f;
5384 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5385 segment = 0;
5386 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5387 segment = 1;
5388 } else if (volIdx <= curve[VOLMAX].mIndex) {
5389 segment = 2;
5390 } else { // out of bounds
5391 return 1.0f;
5392 }
5393
5394 // linear interpolation in the attenuation table in dB
5395 float decibels = curve[segment].mDBAttenuation +
5396 ((float)(volIdx - curve[segment].mIndex)) *
5397 ( (curve[segment+1].mDBAttenuation -
5398 curve[segment].mDBAttenuation) /
5399 ((float)(curve[segment+1].mIndex -
5400 curve[segment].mIndex)) );
5401
5402 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5403
5404 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5405 curve[segment].mIndex, volIdx,
5406 curve[segment+1].mIndex,
5407 curve[segment].mDBAttenuation,
5408 decibels,
5409 curve[segment+1].mDBAttenuation,
5410 amplification);
5411
5412 return amplification;
5413}
5414
Eric Laurente0720872014-03-11 09:30:41 -07005415const AudioPolicyManager::VolumeCurvePoint
5416 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005417 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5418};
5419
Eric Laurente0720872014-03-11 09:30:41 -07005420const AudioPolicyManager::VolumeCurvePoint
5421 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005422 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5423};
5424
Eric Laurente0720872014-03-11 09:30:41 -07005425const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005426 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5427 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5428};
5429
5430const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005431 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005432 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5433};
5434
Eric Laurente0720872014-03-11 09:30:41 -07005435const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005436 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005437 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005438};
5439
5440const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005441 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005442 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5443};
5444
Eric Laurente0720872014-03-11 09:30:41 -07005445const AudioPolicyManager::VolumeCurvePoint
5446 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005447 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5448};
5449
5450// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5451// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5452// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5453// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5454
Eric Laurente0720872014-03-11 09:30:41 -07005455const AudioPolicyManager::VolumeCurvePoint
5456 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005457 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5458};
5459
Eric Laurente0720872014-03-11 09:30:41 -07005460const AudioPolicyManager::VolumeCurvePoint
5461 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005462 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5463};
5464
Eric Laurente0720872014-03-11 09:30:41 -07005465const AudioPolicyManager::VolumeCurvePoint
5466 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005467 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5468};
5469
Eric Laurente0720872014-03-11 09:30:41 -07005470const AudioPolicyManager::VolumeCurvePoint
5471 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005472 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5473};
5474
Eric Laurente0720872014-03-11 09:30:41 -07005475const AudioPolicyManager::VolumeCurvePoint
5476 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005477 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5478};
5479
Eric Laurente0720872014-03-11 09:30:41 -07005480const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005481 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5482 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5483};
5484
5485const AudioPolicyManager::VolumeCurvePoint
5486 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5487 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5488};
5489
5490const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005491 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5492 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5493};
5494
5495const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005496 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5497 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005498 { // AUDIO_STREAM_VOICE_CALL
5499 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5500 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005501 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5502 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005503 },
5504 { // AUDIO_STREAM_SYSTEM
5505 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5506 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005507 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5508 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005509 },
5510 { // AUDIO_STREAM_RING
5511 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5512 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005513 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5514 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005515 },
5516 { // AUDIO_STREAM_MUSIC
5517 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5518 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005519 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5520 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005521 },
5522 { // AUDIO_STREAM_ALARM
5523 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5524 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005525 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5526 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005527 },
5528 { // AUDIO_STREAM_NOTIFICATION
5529 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5530 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005531 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5532 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005533 },
5534 { // AUDIO_STREAM_BLUETOOTH_SCO
5535 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5536 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005537 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5538 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005539 },
5540 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5541 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5542 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005543 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5544 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005545 },
5546 { // AUDIO_STREAM_DTMF
5547 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5548 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005549 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5550 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005551 },
5552 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005553 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5554 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5555 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5556 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5557 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005558 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005559 { // AUDIO_STREAM_ACCESSIBILITY
5560 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5561 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5562 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5563 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5564 },
5565 { // AUDIO_STREAM_REROUTING
5566 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5567 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5568 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5569 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5570 },
5571 { // AUDIO_STREAM_PATCH
5572 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5573 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5574 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5575 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5576 },
Eric Laurente552edb2014-03-10 17:42:56 -07005577};
5578
Eric Laurente0720872014-03-11 09:30:41 -07005579void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005580{
5581 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5582 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5583 mStreams[i].mVolumeCurve[j] =
5584 sVolumeProfiles[i][j];
5585 }
5586 }
5587
5588 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5589 if (mSpeakerDrcEnabled) {
5590 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5591 sDefaultSystemVolumeCurveDrc;
5592 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5593 sSpeakerSonificationVolumeCurveDrc;
5594 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5595 sSpeakerSonificationVolumeCurveDrc;
5596 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5597 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005598 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5599 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005600 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5601 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005602 }
5603}
5604
Eric Laurente0720872014-03-11 09:30:41 -07005605float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005606 int index,
5607 audio_io_handle_t output,
5608 audio_devices_t device)
5609{
5610 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005611 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005612 StreamDescriptor &streamDesc = mStreams[stream];
5613
5614 if (device == AUDIO_DEVICE_NONE) {
5615 device = outputDesc->device();
5616 }
5617
Eric Laurente552edb2014-03-10 17:42:56 -07005618 volume = volIndexToAmpl(device, streamDesc, index);
5619
5620 // if a headset is connected, apply the following rules to ring tones and notifications
5621 // to avoid sound level bursts in user's ears:
5622 // - always attenuate ring tones and notifications volume by 6dB
5623 // - if music is playing, always limit the volume to current music volume,
5624 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005625 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005626 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5627 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5628 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5629 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5630 ((stream_strategy == STRATEGY_SONIFICATION)
5631 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005632 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005633 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005634 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005635 streamDesc.mCanBeMuted) {
5636 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5637 // when the phone is ringing we must consider that music could have been paused just before
5638 // by the music application and behave as if music was active if the last music track was
5639 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005640 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005641 mLimitRingtoneVolume) {
5642 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005643 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5644 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005645 output,
5646 musicDevice);
5647 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5648 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5649 if (volume > minVol) {
5650 volume = minVol;
5651 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5652 }
5653 }
5654 }
5655
5656 return volume;
5657}
5658
Eric Laurente0720872014-03-11 09:30:41 -07005659status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005660 int index,
5661 audio_io_handle_t output,
5662 audio_devices_t device,
5663 int delayMs,
5664 bool force)
5665{
5666
5667 // do not change actual stream volume if the stream is muted
5668 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5669 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5670 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5671 return NO_ERROR;
5672 }
5673
5674 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005675 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5676 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5677 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5678 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005679 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005680 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005681 return INVALID_OPERATION;
5682 }
5683
5684 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005685 // unit gain if rerouting to external policy
5686 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5687 ssize_t index = mOutputs.indexOfKey(output);
5688 if (index >= 0) {
5689 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurentc722f302014-12-10 11:21:49 -08005690 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005691 ALOGV("max gain when rerouting for output=%d", output);
5692 volume = 1.0f;
5693 }
5694 }
5695
5696 }
Eric Laurente552edb2014-03-10 17:42:56 -07005697 // We actually change the volume if:
5698 // - the float value returned by computeVolume() changed
5699 // - the force flag is set
5700 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5701 force) {
5702 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5703 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5704 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5705 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005706 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5707 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005708 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005709 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005710 }
5711
Eric Laurent3b73df72014-03-11 09:06:29 -07005712 if (stream == AUDIO_STREAM_VOICE_CALL ||
5713 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005714 float voiceVolume;
5715 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005716 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005717 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5718 } else {
5719 voiceVolume = 1.0;
5720 }
5721
5722 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5723 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5724 mLastVoiceVolume = voiceVolume;
5725 }
5726 }
5727
5728 return NO_ERROR;
5729}
5730
Eric Laurente0720872014-03-11 09:30:41 -07005731void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005732 audio_devices_t device,
5733 int delayMs,
5734 bool force)
5735{
5736 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5737
Eric Laurent3b73df72014-03-11 09:06:29 -07005738 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005739 if (stream == AUDIO_STREAM_PATCH) {
5740 continue;
5741 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005742 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005743 mStreams[stream].getVolumeIndex(device),
5744 output,
5745 device,
5746 delayMs,
5747 force);
5748 }
5749}
5750
Eric Laurente0720872014-03-11 09:30:41 -07005751void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005752 bool on,
5753 audio_io_handle_t output,
5754 int delayMs,
5755 audio_devices_t device)
5756{
5757 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005758 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005759 if (stream == AUDIO_STREAM_PATCH) {
5760 continue;
5761 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005762 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5763 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005764 }
5765 }
5766}
5767
Eric Laurente0720872014-03-11 09:30:41 -07005768void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005769 bool on,
5770 audio_io_handle_t output,
5771 int delayMs,
5772 audio_devices_t device)
5773{
5774 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005775 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005776 if (device == AUDIO_DEVICE_NONE) {
5777 device = outputDesc->device();
5778 }
5779
5780 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5781 stream, on, output, outputDesc->mMuteCount[stream], device);
5782
5783 if (on) {
5784 if (outputDesc->mMuteCount[stream] == 0) {
5785 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005786 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5787 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005788 checkAndSetVolume(stream, 0, output, device, delayMs);
5789 }
5790 }
5791 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5792 outputDesc->mMuteCount[stream]++;
5793 } else {
5794 if (outputDesc->mMuteCount[stream] == 0) {
5795 ALOGV("setStreamMute() unmuting non muted stream!");
5796 return;
5797 }
5798 if (--outputDesc->mMuteCount[stream] == 0) {
5799 checkAndSetVolume(stream,
5800 streamDesc.getVolumeIndex(device),
5801 output,
5802 device,
5803 delayMs);
5804 }
5805 }
5806}
5807
Eric Laurente0720872014-03-11 09:30:41 -07005808void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005809 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005810{
5811 // if the stream pertains to sonification strategy and we are in call we must
5812 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5813 // in the device used for phone strategy and play the tone if the selected device does not
5814 // interfere with the device used for phone strategy
5815 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5816 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005817 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005818 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5819 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005820 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005821 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5822 stream, starting, outputDesc->mDevice, stateChange);
5823 if (outputDesc->mRefCount[stream]) {
5824 int muteCount = 1;
5825 if (stateChange) {
5826 muteCount = outputDesc->mRefCount[stream];
5827 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005828 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005829 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5830 for (int i = 0; i < muteCount; i++) {
5831 setStreamMute(stream, starting, mPrimaryOutput);
5832 }
5833 } else {
5834 ALOGV("handleIncallSonification() high visibility");
5835 if (outputDesc->device() &
5836 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5837 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5838 for (int i = 0; i < muteCount; i++) {
5839 setStreamMute(stream, starting, mPrimaryOutput);
5840 }
5841 }
5842 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005843 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5844 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005845 } else {
5846 mpClientInterface->stopTone();
5847 }
5848 }
5849 }
5850 }
5851}
5852
Eric Laurente0720872014-03-11 09:30:41 -07005853bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005854{
5855 return isStateInCall(mPhoneState);
5856}
5857
Eric Laurente0720872014-03-11 09:30:41 -07005858bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005859 return ((state == AUDIO_MODE_IN_CALL) ||
5860 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005861}
5862
Eric Laurente0720872014-03-11 09:30:41 -07005863uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005864{
5865 return MAX_EFFECTS_CPU_LOAD;
5866}
5867
Eric Laurente0720872014-03-11 09:30:41 -07005868uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005869{
5870 return MAX_EFFECTS_MEMORY;
5871}
5872
Eric Laurent6a94d692014-05-20 11:18:06 -07005873
Eric Laurente552edb2014-03-10 17:42:56 -07005874// --- AudioOutputDescriptor class implementation
5875
Eric Laurente0720872014-03-11 09:30:41 -07005876AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005877 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005878 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurentc722f302014-12-10 11:21:49 -08005879 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
Eric Laurent275e8e92014-11-30 15:14:47 -08005880 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005881 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5882{
5883 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005884 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005885 mRefCount[i] = 0;
5886 mCurVolume[i] = -1.0;
5887 mMuteCount[i] = 0;
5888 mStopTime[i] = 0;
5889 }
5890 for (int i = 0; i < NUM_STRATEGIES; i++) {
5891 mStrategyMutedByDevice[i] = false;
5892 }
5893 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005894 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005895 mSamplingRate = profile->pickSamplingRate();
5896 mFormat = profile->pickFormat();
5897 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005898 if (profile->mGains.size() > 0) {
5899 profile->mGains[0]->getDefaultConfig(&mGain);
5900 }
Eric Laurente552edb2014-03-10 17:42:56 -07005901 }
5902}
5903
Eric Laurente0720872014-03-11 09:30:41 -07005904audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005905{
5906 if (isDuplicated()) {
5907 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5908 } else {
5909 return mDevice;
5910 }
5911}
5912
Eric Laurente0720872014-03-11 09:30:41 -07005913uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005914{
5915 if (isDuplicated()) {
5916 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5917 } else {
5918 return mLatency;
5919 }
5920}
5921
Eric Laurente0720872014-03-11 09:30:41 -07005922bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005923 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005924{
5925 if (isDuplicated()) {
5926 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5927 } else if (outputDesc->isDuplicated()){
5928 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5929 } else {
5930 return (mProfile->mModule == outputDesc->mProfile->mModule);
5931 }
5932}
5933
Eric Laurente0720872014-03-11 09:30:41 -07005934void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005935 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005936{
5937 // forward usage count change to attached outputs
5938 if (isDuplicated()) {
5939 mOutput1->changeRefCount(stream, delta);
5940 mOutput2->changeRefCount(stream, delta);
5941 }
5942 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005943 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5944 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005945 mRefCount[stream] = 0;
5946 return;
5947 }
5948 mRefCount[stream] += delta;
5949 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5950}
5951
Eric Laurente0720872014-03-11 09:30:41 -07005952audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005953{
5954 if (isDuplicated()) {
5955 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5956 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005957 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005958 }
5959}
5960
Eric Laurente0720872014-03-11 09:30:41 -07005961bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005962{
5963 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5964}
5965
Eric Laurente0720872014-03-11 09:30:41 -07005966bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005967 uint32_t inPastMs,
5968 nsecs_t sysTime) const
5969{
5970 if ((sysTime == 0) && (inPastMs != 0)) {
5971 sysTime = systemTime();
5972 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005973 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005974 if (i == AUDIO_STREAM_PATCH) {
5975 continue;
5976 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005977 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005978 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005979 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005980 return true;
5981 }
5982 }
5983 return false;
5984}
5985
Eric Laurente0720872014-03-11 09:30:41 -07005986bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005987 uint32_t inPastMs,
5988 nsecs_t sysTime) const
5989{
5990 if (mRefCount[stream] != 0) {
5991 return true;
5992 }
5993 if (inPastMs == 0) {
5994 return false;
5995 }
5996 if (sysTime == 0) {
5997 sysTime = systemTime();
5998 }
5999 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
6000 return true;
6001 }
6002 return false;
6003}
6004
Eric Laurent1c333e22014-05-20 10:48:17 -07006005void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006006 struct audio_port_config *dstConfig,
6007 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006008{
Eric Laurent84c70242014-06-23 08:46:27 -07006009 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
6010
Eric Laurent1f2f2232014-06-02 12:01:23 -07006011 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6012 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6013 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006014 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006015 }
6016 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6017
Eric Laurent6a94d692014-05-20 11:18:06 -07006018 dstConfig->id = mId;
6019 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
6020 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07006021 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6022 dstConfig->ext.mix.handle = mIoHandle;
6023 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07006024}
6025
6026void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
6027 struct audio_port *port) const
6028{
Eric Laurent84c70242014-06-23 08:46:27 -07006029 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07006030 mProfile->toAudioPort(port);
6031 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006032 toAudioPortConfig(&port->active_config);
6033 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006034 port->ext.mix.handle = mIoHandle;
6035 port->ext.mix.latency_class =
6036 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
6037}
Eric Laurente552edb2014-03-10 17:42:56 -07006038
Eric Laurente0720872014-03-11 09:30:41 -07006039status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006040{
6041 const size_t SIZE = 256;
6042 char buffer[SIZE];
6043 String8 result;
6044
Eric Laurent4d416952014-08-10 14:07:09 -07006045 snprintf(buffer, SIZE, " ID: %d\n", mId);
6046 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006047 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6048 result.append(buffer);
6049 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
6050 result.append(buffer);
6051 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6052 result.append(buffer);
6053 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
6054 result.append(buffer);
6055 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
6056 result.append(buffer);
6057 snprintf(buffer, SIZE, " Devices %08x\n", device());
6058 result.append(buffer);
6059 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
6060 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07006061 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6062 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
6063 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07006064 result.append(buffer);
6065 }
6066 write(fd, result.string(), result.size());
6067
6068 return NO_ERROR;
6069}
6070
6071// --- AudioInputDescriptor class implementation
6072
Eric Laurent1c333e22014-05-20 10:48:17 -07006073AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006074 : mId(0), mIoHandle(0),
Eric Laurentc722f302014-12-10 11:21:49 -08006075 mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006076 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07006077{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006078 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006079 mSamplingRate = profile->pickSamplingRate();
6080 mFormat = profile->pickFormat();
6081 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07006082 if (profile->mGains.size() > 0) {
6083 profile->mGains[0]->getDefaultConfig(&mGain);
6084 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006085 }
Eric Laurente552edb2014-03-10 17:42:56 -07006086}
6087
Eric Laurent1c333e22014-05-20 10:48:17 -07006088void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006089 struct audio_port_config *dstConfig,
6090 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006091{
Eric Laurent84c70242014-06-23 08:46:27 -07006092 ALOG_ASSERT(mProfile != 0,
6093 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07006094 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6095 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6096 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006097 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006098 }
6099
6100 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6101
Eric Laurent6a94d692014-05-20 11:18:06 -07006102 dstConfig->id = mId;
6103 dstConfig->role = AUDIO_PORT_ROLE_SINK;
6104 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07006105 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6106 dstConfig->ext.mix.handle = mIoHandle;
6107 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07006108}
6109
6110void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6111 struct audio_port *port) const
6112{
Eric Laurent84c70242014-06-23 08:46:27 -07006113 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6114
Eric Laurent1c333e22014-05-20 10:48:17 -07006115 mProfile->toAudioPort(port);
6116 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006117 toAudioPortConfig(&port->active_config);
6118 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006119 port->ext.mix.handle = mIoHandle;
6120 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6121}
6122
Eric Laurente0720872014-03-11 09:30:41 -07006123status_t AudioPolicyManager::AudioInputDescriptor::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
Eric Laurent4d416952014-08-10 14:07:09 -07006129 snprintf(buffer, SIZE, " ID: %d\n", mId);
6130 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006131 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6132 result.append(buffer);
6133 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6134 result.append(buffer);
6135 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6136 result.append(buffer);
6137 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6138 result.append(buffer);
6139 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6140 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006141 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6142 result.append(buffer);
6143
Eric Laurente552edb2014-03-10 17:42:56 -07006144 write(fd, result.string(), result.size());
6145
6146 return NO_ERROR;
6147}
6148
6149// --- StreamDescriptor class implementation
6150
Eric Laurente0720872014-03-11 09:30:41 -07006151AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006152 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6153{
6154 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6155}
6156
Eric Laurente0720872014-03-11 09:30:41 -07006157int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006158{
Eric Laurente0720872014-03-11 09:30:41 -07006159 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006160 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6161 if (mIndexCur.indexOfKey(device) < 0) {
6162 device = AUDIO_DEVICE_OUT_DEFAULT;
6163 }
6164 return mIndexCur.valueFor(device);
6165}
6166
Eric Laurente0720872014-03-11 09:30:41 -07006167void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006168{
6169 const size_t SIZE = 256;
6170 char buffer[SIZE];
6171 String8 result;
6172
6173 snprintf(buffer, SIZE, "%s %02d %02d ",
6174 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6175 result.append(buffer);
6176 for (size_t i = 0; i < mIndexCur.size(); i++) {
6177 snprintf(buffer, SIZE, "%04x : %02d, ",
6178 mIndexCur.keyAt(i),
6179 mIndexCur.valueAt(i));
6180 result.append(buffer);
6181 }
6182 result.append("\n");
6183
6184 write(fd, result.string(), result.size());
6185}
6186
6187// --- EffectDescriptor class implementation
6188
Eric Laurente0720872014-03-11 09:30:41 -07006189status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006190{
6191 const size_t SIZE = 256;
6192 char buffer[SIZE];
6193 String8 result;
6194
6195 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6196 result.append(buffer);
6197 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6198 result.append(buffer);
6199 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6200 result.append(buffer);
6201 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6202 result.append(buffer);
6203 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6204 result.append(buffer);
6205 write(fd, result.string(), result.size());
6206
6207 return NO_ERROR;
6208}
6209
Eric Laurent1c333e22014-05-20 10:48:17 -07006210// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006211
Eric Laurente0720872014-03-11 09:30:41 -07006212AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006213 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6214 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006215{
6216}
6217
Eric Laurente0720872014-03-11 09:30:41 -07006218AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006219{
6220 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006221 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006222 }
6223 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006224 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006225 }
6226 free((void *)mName);
6227}
6228
Eric Laurent1afeecb2014-05-14 08:52:28 -07006229status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6230{
6231 cnode *node = root->first_child;
6232
6233 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6234
6235 while (node) {
6236 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6237 profile->loadSamplingRates((char *)node->value);
6238 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6239 profile->loadFormats((char *)node->value);
6240 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6241 profile->loadInChannels((char *)node->value);
6242 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6243 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6244 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006245 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6246 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006247 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6248 profile->loadGains(node);
6249 }
6250 node = node->next;
6251 }
6252 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6253 "loadInput() invalid supported devices");
6254 ALOGW_IF(profile->mChannelMasks.size() == 0,
6255 "loadInput() invalid supported channel masks");
6256 ALOGW_IF(profile->mSamplingRates.size() == 0,
6257 "loadInput() invalid supported sampling rates");
6258 ALOGW_IF(profile->mFormats.size() == 0,
6259 "loadInput() invalid supported formats");
6260 if (!profile->mSupportedDevices.isEmpty() &&
6261 (profile->mChannelMasks.size() != 0) &&
6262 (profile->mSamplingRates.size() != 0) &&
6263 (profile->mFormats.size() != 0)) {
6264
6265 ALOGV("loadInput() adding input Supported Devices %04x",
6266 profile->mSupportedDevices.types());
6267
6268 mInputProfiles.add(profile);
6269 return NO_ERROR;
6270 } else {
6271 return BAD_VALUE;
6272 }
6273}
6274
6275status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6276{
6277 cnode *node = root->first_child;
6278
6279 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6280
6281 while (node) {
6282 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6283 profile->loadSamplingRates((char *)node->value);
6284 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6285 profile->loadFormats((char *)node->value);
6286 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6287 profile->loadOutChannels((char *)node->value);
6288 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6289 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6290 mDeclaredDevices);
6291 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006292 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006293 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6294 profile->loadGains(node);
6295 }
6296 node = node->next;
6297 }
6298 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6299 "loadOutput() invalid supported devices");
6300 ALOGW_IF(profile->mChannelMasks.size() == 0,
6301 "loadOutput() invalid supported channel masks");
6302 ALOGW_IF(profile->mSamplingRates.size() == 0,
6303 "loadOutput() invalid supported sampling rates");
6304 ALOGW_IF(profile->mFormats.size() == 0,
6305 "loadOutput() invalid supported formats");
6306 if (!profile->mSupportedDevices.isEmpty() &&
6307 (profile->mChannelMasks.size() != 0) &&
6308 (profile->mSamplingRates.size() != 0) &&
6309 (profile->mFormats.size() != 0)) {
6310
6311 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6312 profile->mSupportedDevices.types(), profile->mFlags);
6313
6314 mOutputProfiles.add(profile);
6315 return NO_ERROR;
6316 } else {
6317 return BAD_VALUE;
6318 }
6319}
6320
6321status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6322{
6323 cnode *node = root->first_child;
6324
6325 audio_devices_t type = AUDIO_DEVICE_NONE;
6326 while (node) {
6327 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6328 type = parseDeviceNames((char *)node->value);
6329 break;
6330 }
6331 node = node->next;
6332 }
6333 if (type == AUDIO_DEVICE_NONE ||
6334 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6335 ALOGW("loadDevice() bad type %08x", type);
6336 return BAD_VALUE;
6337 }
6338 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6339 deviceDesc->mModule = this;
6340
6341 node = root->first_child;
6342 while (node) {
6343 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6344 deviceDesc->mAddress = String8((char *)node->value);
6345 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6346 if (audio_is_input_device(type)) {
6347 deviceDesc->loadInChannels((char *)node->value);
6348 } else {
6349 deviceDesc->loadOutChannels((char *)node->value);
6350 }
6351 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6352 deviceDesc->loadGains(node);
6353 }
6354 node = node->next;
6355 }
6356
6357 ALOGV("loadDevice() adding device name %s type %08x address %s",
6358 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6359
6360 mDeclaredDevices.add(deviceDesc);
6361
6362 return NO_ERROR;
6363}
6364
Eric Laurent275e8e92014-11-30 15:14:47 -08006365status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6366 audio_devices_t device, String8 address)
6367{
6368 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6369
6370 profile->mSamplingRates.add(config->sample_rate);
6371 profile->mChannelMasks.add(config->channel_mask);
6372 profile->mFormats.add(config->format);
6373
6374 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6375 devDesc->mAddress = address;
6376 profile->mSupportedDevices.add(devDesc);
6377
6378 mOutputProfiles.add(profile);
6379
6380 return NO_ERROR;
6381}
6382
6383status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6384{
6385 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6386 if (mOutputProfiles[i]->mName == name) {
6387 mOutputProfiles.removeAt(i);
6388 break;
6389 }
6390 }
6391
6392 return NO_ERROR;
6393}
6394
6395status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6396 audio_devices_t device, String8 address)
6397{
6398 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6399
6400 profile->mSamplingRates.add(config->sample_rate);
6401 profile->mChannelMasks.add(config->channel_mask);
6402 profile->mFormats.add(config->format);
6403
6404 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6405 devDesc->mAddress = address;
6406 profile->mSupportedDevices.add(devDesc);
6407
6408 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6409
6410 mInputProfiles.add(profile);
6411
6412 return NO_ERROR;
6413}
6414
6415status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6416{
6417 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6418 if (mInputProfiles[i]->mName == name) {
6419 mInputProfiles.removeAt(i);
6420 break;
6421 }
6422 }
6423
6424 return NO_ERROR;
6425}
6426
6427
Eric Laurente0720872014-03-11 09:30:41 -07006428void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006429{
6430 const size_t SIZE = 256;
6431 char buffer[SIZE];
6432 String8 result;
6433
6434 snprintf(buffer, SIZE, " - name: %s\n", mName);
6435 result.append(buffer);
6436 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6437 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006438 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6439 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006440 write(fd, result.string(), result.size());
6441 if (mOutputProfiles.size()) {
6442 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6443 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006444 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006445 write(fd, buffer, strlen(buffer));
6446 mOutputProfiles[i]->dump(fd);
6447 }
6448 }
6449 if (mInputProfiles.size()) {
6450 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6451 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006452 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006453 write(fd, buffer, strlen(buffer));
6454 mInputProfiles[i]->dump(fd);
6455 }
6456 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006457 if (mDeclaredDevices.size()) {
6458 write(fd, " - devices:\n", strlen(" - devices:\n"));
6459 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6460 mDeclaredDevices[i]->dump(fd, 4, i);
6461 }
6462 }
Eric Laurente552edb2014-03-10 17:42:56 -07006463}
6464
Eric Laurent1c333e22014-05-20 10:48:17 -07006465// --- AudioPort class implementation
6466
Eric Laurenta121f902014-06-03 13:32:54 -07006467
6468AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6469 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006470 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006471{
6472 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6473 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6474}
6475
Eric Laurent1c333e22014-05-20 10:48:17 -07006476void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6477{
6478 port->role = mRole;
6479 port->type = mType;
6480 unsigned int i;
6481 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006482 if (mSamplingRates[i] != 0) {
6483 port->sample_rates[i] = mSamplingRates[i];
6484 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006485 }
6486 port->num_sample_rates = i;
6487 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006488 if (mChannelMasks[i] != 0) {
6489 port->channel_masks[i] = mChannelMasks[i];
6490 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006491 }
6492 port->num_channel_masks = i;
6493 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006494 if (mFormats[i] != 0) {
6495 port->formats[i] = mFormats[i];
6496 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006497 }
6498 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006499
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006500 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006501
6502 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6503 port->gains[i] = mGains[i]->mGain;
6504 }
6505 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006506}
6507
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006508void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6509 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6510 const uint32_t rate = port->mSamplingRates.itemAt(k);
6511 if (rate != 0) { // skip "dynamic" rates
6512 bool hasRate = false;
6513 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6514 if (rate == mSamplingRates.itemAt(l)) {
6515 hasRate = true;
6516 break;
6517 }
6518 }
6519 if (!hasRate) { // never import a sampling rate twice
6520 mSamplingRates.add(rate);
6521 }
6522 }
6523 }
6524 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6525 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6526 if (mask != 0) { // skip "dynamic" masks
6527 bool hasMask = false;
6528 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6529 if (mask == mChannelMasks.itemAt(l)) {
6530 hasMask = true;
6531 break;
6532 }
6533 }
6534 if (!hasMask) { // never import a channel mask twice
6535 mChannelMasks.add(mask);
6536 }
6537 }
6538 }
6539 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6540 const audio_format_t format = port->mFormats.itemAt(k);
6541 if (format != 0) { // skip "dynamic" formats
6542 bool hasFormat = false;
6543 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6544 if (format == mFormats.itemAt(l)) {
6545 hasFormat = true;
6546 break;
6547 }
6548 }
6549 if (!hasFormat) { // never import a channel mask twice
6550 mFormats.add(format);
6551 }
6552 }
6553 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006554 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6555 sp<AudioGain> gain = port->mGains.itemAt(k);
6556 if (gain != 0) {
6557 bool hasGain = false;
6558 for (size_t l = 0 ; l < mGains.size() ; l++) {
6559 if (gain == mGains.itemAt(l)) {
6560 hasGain = true;
6561 break;
6562 }
6563 }
6564 if (!hasGain) { // never import a gain twice
6565 mGains.add(gain);
6566 }
6567 }
6568 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006569}
6570
6571void AudioPolicyManager::AudioPort::clearCapabilities() {
6572 mChannelMasks.clear();
6573 mFormats.clear();
6574 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006575 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006576}
Eric Laurent1c333e22014-05-20 10:48:17 -07006577
6578void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6579{
6580 char *str = strtok(name, "|");
6581
6582 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6583 // rates should be read from the output stream after it is opened for the first time
6584 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6585 mSamplingRates.add(0);
6586 return;
6587 }
6588
6589 while (str != NULL) {
6590 uint32_t rate = atoi(str);
6591 if (rate != 0) {
6592 ALOGV("loadSamplingRates() adding rate %d", rate);
6593 mSamplingRates.add(rate);
6594 }
6595 str = strtok(NULL, "|");
6596 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006597}
6598
6599void AudioPolicyManager::AudioPort::loadFormats(char *name)
6600{
6601 char *str = strtok(name, "|");
6602
6603 // by convention, "0' in the first entry in mFormats indicates the supported formats
6604 // should be read from the output stream after it is opened for the first time
6605 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6606 mFormats.add(AUDIO_FORMAT_DEFAULT);
6607 return;
6608 }
6609
6610 while (str != NULL) {
6611 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6612 ARRAY_SIZE(sFormatNameToEnumTable),
6613 str);
6614 if (format != AUDIO_FORMAT_DEFAULT) {
6615 mFormats.add(format);
6616 }
6617 str = strtok(NULL, "|");
6618 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006619}
6620
6621void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6622{
6623 const char *str = strtok(name, "|");
6624
6625 ALOGV("loadInChannels() %s", name);
6626
6627 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6628 mChannelMasks.add(0);
6629 return;
6630 }
6631
6632 while (str != NULL) {
6633 audio_channel_mask_t channelMask =
6634 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6635 ARRAY_SIZE(sInChannelsNameToEnumTable),
6636 str);
6637 if (channelMask != 0) {
6638 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6639 mChannelMasks.add(channelMask);
6640 }
6641 str = strtok(NULL, "|");
6642 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006643}
6644
6645void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6646{
6647 const char *str = strtok(name, "|");
6648
6649 ALOGV("loadOutChannels() %s", name);
6650
6651 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6652 // masks should be read from the output stream after it is opened for the first time
6653 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6654 mChannelMasks.add(0);
6655 return;
6656 }
6657
6658 while (str != NULL) {
6659 audio_channel_mask_t channelMask =
6660 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6661 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6662 str);
6663 if (channelMask != 0) {
6664 mChannelMasks.add(channelMask);
6665 }
6666 str = strtok(NULL, "|");
6667 }
6668 return;
6669}
6670
Eric Laurent1afeecb2014-05-14 08:52:28 -07006671audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6672{
6673 const char *str = strtok(name, "|");
6674
6675 ALOGV("loadGainMode() %s", name);
6676 audio_gain_mode_t mode = 0;
6677 while (str != NULL) {
6678 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6679 ARRAY_SIZE(sGainModeNameToEnumTable),
6680 str);
6681 str = strtok(NULL, "|");
6682 }
6683 return mode;
6684}
6685
Eric Laurenta121f902014-06-03 13:32:54 -07006686void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006687{
6688 cnode *node = root->first_child;
6689
Eric Laurenta121f902014-06-03 13:32:54 -07006690 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006691
6692 while (node) {
6693 if (strcmp(node->name, GAIN_MODE) == 0) {
6694 gain->mGain.mode = loadGainMode((char *)node->value);
6695 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006696 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006697 gain->mGain.channel_mask =
6698 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6699 ARRAY_SIZE(sInChannelsNameToEnumTable),
6700 (char *)node->value);
6701 } else {
6702 gain->mGain.channel_mask =
6703 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6704 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6705 (char *)node->value);
6706 }
6707 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6708 gain->mGain.min_value = atoi((char *)node->value);
6709 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6710 gain->mGain.max_value = atoi((char *)node->value);
6711 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6712 gain->mGain.default_value = atoi((char *)node->value);
6713 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6714 gain->mGain.step_value = atoi((char *)node->value);
6715 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6716 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6717 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6718 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6719 }
6720 node = node->next;
6721 }
6722
6723 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6724 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6725
6726 if (gain->mGain.mode == 0) {
6727 return;
6728 }
6729 mGains.add(gain);
6730}
6731
6732void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6733{
6734 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006735 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006736 while (node) {
6737 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006738 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006739 node = node->next;
6740 }
6741}
6742
Glenn Kastencbd48022014-07-24 13:46:44 -07006743status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006744{
Eric Laurent0daea392014-12-04 19:14:54 -08006745 if (mSamplingRates.isEmpty()) {
6746 return NO_ERROR;
6747 }
6748
Eric Laurenta121f902014-06-03 13:32:54 -07006749 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6750 if (mSamplingRates[i] == samplingRate) {
6751 return NO_ERROR;
6752 }
6753 }
6754 return BAD_VALUE;
6755}
6756
Glenn Kastencbd48022014-07-24 13:46:44 -07006757status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6758 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006759{
Eric Laurent0daea392014-12-04 19:14:54 -08006760 if (mSamplingRates.isEmpty()) {
6761 return NO_ERROR;
6762 }
6763
Glenn Kastencbd48022014-07-24 13:46:44 -07006764 // Search for the closest supported sampling rate that is above (preferred)
6765 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6766 // The sampling rates do not need to be sorted in ascending order.
6767 ssize_t maxBelow = -1;
6768 ssize_t minAbove = -1;
6769 uint32_t candidate;
6770 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6771 candidate = mSamplingRates[i];
6772 if (candidate == samplingRate) {
6773 if (updatedSamplingRate != NULL) {
6774 *updatedSamplingRate = candidate;
6775 }
6776 return NO_ERROR;
6777 }
6778 // candidate < desired
6779 if (candidate < samplingRate) {
6780 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6781 maxBelow = i;
6782 }
6783 // candidate > desired
6784 } else {
6785 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6786 minAbove = i;
6787 }
6788 }
6789 }
6790 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6791 // TODO Move these assumptions out.
6792 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6793 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6794 // due to approximation by an int32_t of the
6795 // phase increments
6796 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6797 if (minAbove >= 0) {
6798 candidate = mSamplingRates[minAbove];
6799 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6800 if (updatedSamplingRate != NULL) {
6801 *updatedSamplingRate = candidate;
6802 }
6803 return NO_ERROR;
6804 }
6805 }
6806 // But if we have to up-sample from a lower sampling rate, that's OK.
6807 if (maxBelow >= 0) {
6808 candidate = mSamplingRates[maxBelow];
6809 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6810 if (updatedSamplingRate != NULL) {
6811 *updatedSamplingRate = candidate;
6812 }
6813 return NO_ERROR;
6814 }
6815 }
6816 // leave updatedSamplingRate unmodified
6817 return BAD_VALUE;
6818}
6819
6820status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6821{
Eric Laurent0daea392014-12-04 19:14:54 -08006822 if (mChannelMasks.isEmpty()) {
6823 return NO_ERROR;
6824 }
6825
Glenn Kastencbd48022014-07-24 13:46:44 -07006826 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006827 if (mChannelMasks[i] == channelMask) {
6828 return NO_ERROR;
6829 }
6830 }
6831 return BAD_VALUE;
6832}
6833
Glenn Kastencbd48022014-07-24 13:46:44 -07006834status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6835 const
6836{
Eric Laurent0daea392014-12-04 19:14:54 -08006837 if (mChannelMasks.isEmpty()) {
6838 return NO_ERROR;
6839 }
6840
Glenn Kastencbd48022014-07-24 13:46:44 -07006841 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6842 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6843 // FIXME Does not handle multi-channel automatic conversions yet
6844 audio_channel_mask_t supported = mChannelMasks[i];
6845 if (supported == channelMask) {
6846 return NO_ERROR;
6847 }
6848 if (isRecordThread) {
6849 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6850 // FIXME Abstract this out to a table.
6851 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6852 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6853 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6854 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6855 return NO_ERROR;
6856 }
6857 }
6858 }
6859 return BAD_VALUE;
6860}
6861
Eric Laurenta121f902014-06-03 13:32:54 -07006862status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6863{
Eric Laurent0daea392014-12-04 19:14:54 -08006864 if (mFormats.isEmpty()) {
6865 return NO_ERROR;
6866 }
6867
Eric Laurenta121f902014-06-03 13:32:54 -07006868 for (size_t i = 0; i < mFormats.size(); i ++) {
6869 if (mFormats[i] == format) {
6870 return NO_ERROR;
6871 }
6872 }
6873 return BAD_VALUE;
6874}
6875
Eric Laurent1e693b52014-07-09 15:03:28 -07006876
6877uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6878{
6879 // special case for uninitialized dynamic profile
6880 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6881 return 0;
6882 }
6883
Eric Laurent828bcff2014-09-07 12:26:06 -07006884 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6885 // channel count / sampling rate combination chosen will be supported by the connected
6886 // sink
6887 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6888 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6889 uint32_t samplingRate = UINT_MAX;
6890 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6891 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6892 samplingRate = mSamplingRates[i];
6893 }
6894 }
6895 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6896 }
6897
Eric Laurent1e693b52014-07-09 15:03:28 -07006898 uint32_t samplingRate = 0;
6899 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6900
6901 // For mixed output and inputs, use max mixer sampling rates. Do not
6902 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006903 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006904 maxRate = UINT_MAX;
6905 }
6906 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6907 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6908 samplingRate = mSamplingRates[i];
6909 }
6910 }
6911 return samplingRate;
6912}
6913
6914audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6915{
6916 // special case for uninitialized dynamic profile
6917 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6918 return AUDIO_CHANNEL_NONE;
6919 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006920 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006921
6922 // For direct outputs, pick minimum channel count: this helps ensuring that the
6923 // channel count / sampling rate combination chosen will be supported by the connected
6924 // sink
6925 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6926 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6927 uint32_t channelCount = UINT_MAX;
6928 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6929 uint32_t cnlCount;
6930 if (mUseInChannelMask) {
6931 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6932 } else {
6933 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6934 }
6935 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6936 channelMask = mChannelMasks[i];
6937 channelCount = cnlCount;
6938 }
6939 }
6940 return channelMask;
6941 }
6942
Eric Laurent1e693b52014-07-09 15:03:28 -07006943 uint32_t channelCount = 0;
6944 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6945
6946 // For mixed output and inputs, use max mixer channel count. Do not
6947 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006948 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006949 maxCount = UINT_MAX;
6950 }
6951 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6952 uint32_t cnlCount;
6953 if (mUseInChannelMask) {
6954 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6955 } else {
6956 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6957 }
6958 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6959 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006960 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006961 }
6962 }
6963 return channelMask;
6964}
6965
Andy Hung9a605382014-07-28 16:16:31 -07006966/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006967const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6968 AUDIO_FORMAT_DEFAULT,
6969 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006970 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006971 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006972 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006973 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006974};
6975
6976int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6977 audio_format_t format2)
6978{
6979 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6980 // compressed format and better than any PCM format. This is by design of pickFormat()
6981 if (!audio_is_linear_pcm(format1)) {
6982 if (!audio_is_linear_pcm(format2)) {
6983 return 0;
6984 }
6985 return 1;
6986 }
6987 if (!audio_is_linear_pcm(format2)) {
6988 return -1;
6989 }
6990
6991 int index1 = -1, index2 = -1;
6992 for (size_t i = 0;
6993 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6994 i ++) {
6995 if (sPcmFormatCompareTable[i] == format1) {
6996 index1 = i;
6997 }
6998 if (sPcmFormatCompareTable[i] == format2) {
6999 index2 = i;
7000 }
7001 }
7002 // format1 not found => index1 < 0 => format2 > format1
7003 // format2 not found => index2 < 0 => format2 < format1
7004 return index1 - index2;
7005}
7006
7007audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
7008{
7009 // special case for uninitialized dynamic profile
7010 if (mFormats.size() == 1 && mFormats[0] == 0) {
7011 return AUDIO_FORMAT_DEFAULT;
7012 }
7013
7014 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07007015 audio_format_t bestFormat =
7016 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
7017 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07007018 // For mixed output and inputs, use best mixer output format. Do not
7019 // limit format otherwise
7020 if ((mType != AUDIO_PORT_TYPE_MIX) ||
7021 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07007022 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007023 bestFormat = AUDIO_FORMAT_INVALID;
7024 }
7025
7026 for (size_t i = 0; i < mFormats.size(); i ++) {
7027 if ((compareFormats(mFormats[i], format) > 0) &&
7028 (compareFormats(mFormats[i], bestFormat) <= 0)) {
7029 format = mFormats[i];
7030 }
7031 }
7032 return format;
7033}
7034
Eric Laurenta121f902014-06-03 13:32:54 -07007035status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
7036 int index) const
7037{
7038 if (index < 0 || (size_t)index >= mGains.size()) {
7039 return BAD_VALUE;
7040 }
7041 return mGains[index]->checkConfig(gainConfig);
7042}
7043
Eric Laurent1afeecb2014-05-14 08:52:28 -07007044void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
7045{
7046 const size_t SIZE = 256;
7047 char buffer[SIZE];
7048 String8 result;
7049
7050 if (mName.size() != 0) {
7051 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
7052 result.append(buffer);
7053 }
7054
7055 if (mSamplingRates.size() != 0) {
7056 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
7057 result.append(buffer);
7058 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007059 if (i == 0 && mSamplingRates[i] == 0) {
7060 snprintf(buffer, SIZE, "Dynamic");
7061 } else {
7062 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7063 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007064 result.append(buffer);
7065 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7066 }
7067 result.append("\n");
7068 }
7069
7070 if (mChannelMasks.size() != 0) {
7071 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7072 result.append(buffer);
7073 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007074 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7075
7076 if (i == 0 && mChannelMasks[i] == 0) {
7077 snprintf(buffer, SIZE, "Dynamic");
7078 } else {
7079 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7080 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007081 result.append(buffer);
7082 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7083 }
7084 result.append("\n");
7085 }
7086
7087 if (mFormats.size() != 0) {
7088 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7089 result.append(buffer);
7090 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007091 const char *formatStr = enumToString(sFormatNameToEnumTable,
7092 ARRAY_SIZE(sFormatNameToEnumTable),
7093 mFormats[i]);
7094 if (i == 0 && strcmp(formatStr, "") == 0) {
7095 snprintf(buffer, SIZE, "Dynamic");
7096 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07007097 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07007098 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007099 result.append(buffer);
7100 result.append(i == (mFormats.size() - 1) ? "" : ", ");
7101 }
7102 result.append("\n");
7103 }
7104 write(fd, result.string(), result.size());
7105 if (mGains.size() != 0) {
7106 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7107 write(fd, buffer, strlen(buffer) + 1);
7108 result.append(buffer);
7109 for (size_t i = 0; i < mGains.size(); i++) {
7110 mGains[i]->dump(fd, spaces + 2, i);
7111 }
7112 }
7113}
7114
7115// --- AudioGain class implementation
7116
Eric Laurenta121f902014-06-03 13:32:54 -07007117AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07007118{
Eric Laurenta121f902014-06-03 13:32:54 -07007119 mIndex = index;
7120 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007121 memset(&mGain, 0, sizeof(struct audio_gain));
7122}
7123
Eric Laurenta121f902014-06-03 13:32:54 -07007124void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7125{
7126 config->index = mIndex;
7127 config->mode = mGain.mode;
7128 config->channel_mask = mGain.channel_mask;
7129 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7130 config->values[0] = mGain.default_value;
7131 } else {
7132 uint32_t numValues;
7133 if (mUseInChannelMask) {
7134 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7135 } else {
7136 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7137 }
7138 for (size_t i = 0; i < numValues; i++) {
7139 config->values[i] = mGain.default_value;
7140 }
7141 }
7142 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7143 config->ramp_duration_ms = mGain.min_ramp_ms;
7144 }
7145}
7146
7147status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7148{
7149 if ((config->mode & ~mGain.mode) != 0) {
7150 return BAD_VALUE;
7151 }
7152 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7153 if ((config->values[0] < mGain.min_value) ||
7154 (config->values[0] > mGain.max_value)) {
7155 return BAD_VALUE;
7156 }
7157 } else {
7158 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7159 return BAD_VALUE;
7160 }
7161 uint32_t numValues;
7162 if (mUseInChannelMask) {
7163 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7164 } else {
7165 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7166 }
7167 for (size_t i = 0; i < numValues; i++) {
7168 if ((config->values[i] < mGain.min_value) ||
7169 (config->values[i] > mGain.max_value)) {
7170 return BAD_VALUE;
7171 }
7172 }
7173 }
7174 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7175 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7176 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7177 return BAD_VALUE;
7178 }
7179 }
7180 return NO_ERROR;
7181}
7182
Eric Laurent1afeecb2014-05-14 08:52:28 -07007183void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7184{
7185 const size_t SIZE = 256;
7186 char buffer[SIZE];
7187 String8 result;
7188
7189 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7190 result.append(buffer);
7191 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7192 result.append(buffer);
7193 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7194 result.append(buffer);
7195 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7196 result.append(buffer);
7197 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7198 result.append(buffer);
7199 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7200 result.append(buffer);
7201 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7202 result.append(buffer);
7203 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7204 result.append(buffer);
7205 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7206 result.append(buffer);
7207
7208 write(fd, result.string(), result.size());
7209}
7210
Eric Laurent1f2f2232014-06-02 12:01:23 -07007211// --- AudioPortConfig class implementation
7212
7213AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7214{
7215 mSamplingRate = 0;
7216 mChannelMask = AUDIO_CHANNEL_NONE;
7217 mFormat = AUDIO_FORMAT_INVALID;
7218 mGain.index = -1;
7219}
7220
Eric Laurenta121f902014-06-03 13:32:54 -07007221status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7222 const struct audio_port_config *config,
7223 struct audio_port_config *backupConfig)
7224{
7225 struct audio_port_config localBackupConfig;
7226 status_t status = NO_ERROR;
7227
7228 localBackupConfig.config_mask = config->config_mask;
7229 toAudioPortConfig(&localBackupConfig);
7230
Marco Nelissen961ec212014-08-25 15:58:39 -07007231 sp<AudioPort> audioport = getAudioPort();
7232 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007233 status = NO_INIT;
7234 goto exit;
7235 }
7236 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007237 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007238 if (status != NO_ERROR) {
7239 goto exit;
7240 }
7241 mSamplingRate = config->sample_rate;
7242 }
7243 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007244 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007245 if (status != NO_ERROR) {
7246 goto exit;
7247 }
7248 mChannelMask = config->channel_mask;
7249 }
7250 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007251 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007252 if (status != NO_ERROR) {
7253 goto exit;
7254 }
7255 mFormat = config->format;
7256 }
7257 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007258 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007259 if (status != NO_ERROR) {
7260 goto exit;
7261 }
7262 mGain = config->gain;
7263 }
7264
7265exit:
7266 if (status != NO_ERROR) {
7267 applyAudioPortConfig(&localBackupConfig);
7268 }
7269 if (backupConfig != NULL) {
7270 *backupConfig = localBackupConfig;
7271 }
7272 return status;
7273}
7274
Eric Laurent1f2f2232014-06-02 12:01:23 -07007275void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7276 struct audio_port_config *dstConfig,
7277 const struct audio_port_config *srcConfig) const
7278{
7279 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7280 dstConfig->sample_rate = mSamplingRate;
7281 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7282 dstConfig->sample_rate = srcConfig->sample_rate;
7283 }
7284 } else {
7285 dstConfig->sample_rate = 0;
7286 }
7287 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7288 dstConfig->channel_mask = mChannelMask;
7289 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7290 dstConfig->channel_mask = srcConfig->channel_mask;
7291 }
7292 } else {
7293 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7294 }
7295 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7296 dstConfig->format = mFormat;
7297 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7298 dstConfig->format = srcConfig->format;
7299 }
7300 } else {
7301 dstConfig->format = AUDIO_FORMAT_INVALID;
7302 }
7303 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7304 dstConfig->gain = mGain;
7305 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7306 dstConfig->gain = srcConfig->gain;
7307 }
7308 } else {
7309 dstConfig->gain.index = -1;
7310 }
7311 if (dstConfig->gain.index != -1) {
7312 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7313 } else {
7314 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7315 }
7316}
7317
Eric Laurent1c333e22014-05-20 10:48:17 -07007318// --- IOProfile class implementation
7319
Eric Laurent1afeecb2014-05-14 08:52:28 -07007320AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007321 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007322 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007323{
7324}
7325
Eric Laurente0720872014-03-11 09:30:41 -07007326AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007327{
7328}
7329
7330// checks if the IO profile is compatible with specified parameters.
7331// Sampling rate, format and channel mask must be specified in order to
7332// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007333bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007334 String8 address,
7335 uint32_t samplingRate,
7336 uint32_t *updatedSamplingRate,
7337 audio_format_t format,
7338 audio_channel_mask_t channelMask,
7339 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007340{
Glenn Kastencbd48022014-07-24 13:46:44 -07007341 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7342 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7343 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007344
Eric Laurent275e8e92014-11-30 15:14:47 -08007345 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007346 return false;
7347 }
7348
7349 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007350 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007351 }
7352 uint32_t myUpdatedSamplingRate = samplingRate;
7353 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007354 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007355 }
7356 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7357 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007358 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007359 }
7360
7361 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7362 return false;
7363 }
7364
7365 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7366 checkExactChannelMask(channelMask) != NO_ERROR)) {
7367 return false;
7368 }
7369 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7370 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7371 return false;
7372 }
7373
7374 if (isPlaybackThread && (mFlags & flags) != flags) {
7375 return false;
7376 }
7377 // The only input flag that is allowed to be different is the fast flag.
7378 // An existing fast stream is compatible with a normal track request.
7379 // An existing normal stream is compatible with a fast track request,
7380 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007381 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007382 ~AUDIO_INPUT_FLAG_FAST)) {
7383 return false;
7384 }
7385
7386 if (updatedSamplingRate != NULL) {
7387 *updatedSamplingRate = myUpdatedSamplingRate;
7388 }
7389 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007390}
7391
Eric Laurente0720872014-03-11 09:30:41 -07007392void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007393{
7394 const size_t SIZE = 256;
7395 char buffer[SIZE];
7396 String8 result;
7397
Eric Laurent1afeecb2014-05-14 08:52:28 -07007398 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007399
Eric Laurente552edb2014-03-10 17:42:56 -07007400 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7401 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007402 snprintf(buffer, SIZE, " - devices:\n");
7403 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007404 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007405 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7406 mSupportedDevices[i]->dump(fd, 6, i);
7407 }
Eric Laurente552edb2014-03-10 17:42:56 -07007408}
7409
Eric Laurentd4692962014-05-05 18:13:44 -07007410void AudioPolicyManager::IOProfile::log()
7411{
7412 const size_t SIZE = 256;
7413 char buffer[SIZE];
7414 String8 result;
7415
7416 ALOGV(" - sampling rates: ");
7417 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7418 ALOGV(" %d", mSamplingRates[i]);
7419 }
7420
7421 ALOGV(" - channel masks: ");
7422 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7423 ALOGV(" 0x%04x", mChannelMasks[i]);
7424 }
7425
7426 ALOGV(" - formats: ");
7427 for (size_t i = 0; i < mFormats.size(); i++) {
7428 ALOGV(" 0x%08x", mFormats[i]);
7429 }
7430
7431 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7432 ALOGV(" - flags: 0x%04x\n", mFlags);
7433}
7434
7435
Eric Laurent3a4311c2014-03-17 12:00:47 -07007436// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007437
Eric Laurent1f2f2232014-06-02 12:01:23 -07007438
7439AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7440 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7441 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7442 AUDIO_PORT_ROLE_SOURCE,
7443 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007444 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007445{
Eric Laurenta121f902014-06-03 13:32:54 -07007446 if (mGains.size() > 0) {
7447 mGains[0]->getDefaultConfig(&mGain);
7448 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07007449}
7450
Eric Laurent3a4311c2014-03-17 12:00:47 -07007451bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007452{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007453 // Devices are considered equal if they:
7454 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7455 // - have the same address or one device does not specify the address
7456 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007457 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007458 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007459 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007460 mChannelMask == other->mChannelMask);
7461}
7462
7463void AudioPolicyManager::DeviceVector::refreshTypes()
7464{
Eric Laurent1c333e22014-05-20 10:48:17 -07007465 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007466 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007467 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007468 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007469 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007470}
7471
7472ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7473{
7474 for(size_t i = 0; i < size(); i++) {
7475 if (item->equals(itemAt(i))) {
7476 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007477 }
7478 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007479 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007480}
7481
Eric Laurent3a4311c2014-03-17 12:00:47 -07007482ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007483{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007484 ssize_t ret = indexOf(item);
7485
7486 if (ret < 0) {
7487 ret = SortedVector::add(item);
7488 if (ret >= 0) {
7489 refreshTypes();
7490 }
7491 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007492 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007493 ret = -1;
7494 }
7495 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007496}
7497
Eric Laurent3a4311c2014-03-17 12:00:47 -07007498ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7499{
7500 size_t i;
7501 ssize_t ret = indexOf(item);
7502
7503 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007504 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007505 } else {
7506 ret = SortedVector::removeAt(ret);
7507 if (ret >= 0) {
7508 refreshTypes();
7509 }
7510 }
7511 return ret;
7512}
7513
7514void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7515{
7516 DeviceVector deviceList;
7517
7518 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7519 types &= ~role_bit;
7520
7521 while (types) {
7522 uint32_t i = 31 - __builtin_clz(types);
7523 uint32_t type = 1 << i;
7524 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007525 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007526 }
7527}
7528
Eric Laurent1afeecb2014-05-14 08:52:28 -07007529void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7530 const DeviceVector& declaredDevices)
7531{
7532 char *devName = strtok(name, "|");
7533 while (devName != NULL) {
7534 if (strlen(devName) != 0) {
7535 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7536 ARRAY_SIZE(sDeviceNameToEnumTable),
7537 devName);
7538 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007539 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007540 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7541 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007542 dev->mAddress = String8("0");
7543 }
7544 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007545 } else {
7546 sp<DeviceDescriptor> deviceDesc =
7547 declaredDevices.getDeviceFromName(String8(devName));
7548 if (deviceDesc != 0) {
7549 add(deviceDesc);
7550 }
7551 }
7552 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007553 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007554 }
7555}
7556
Eric Laurent1c333e22014-05-20 10:48:17 -07007557sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7558 audio_devices_t type, String8 address) const
7559{
7560 sp<DeviceDescriptor> device;
7561 for (size_t i = 0; i < size(); i++) {
7562 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007563 if (address == "" || itemAt(i)->mAddress == address) {
7564 device = itemAt(i);
7565 if (itemAt(i)->mAddress == address) {
7566 break;
7567 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007568 }
7569 }
7570 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007571 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007572 type, address.string(), device.get());
7573 return device;
7574}
7575
Eric Laurent6a94d692014-05-20 11:18:06 -07007576sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7577 audio_port_handle_t id) const
7578{
7579 sp<DeviceDescriptor> device;
7580 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007581 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007582 if (itemAt(i)->mId == id) {
7583 device = itemAt(i);
7584 break;
7585 }
7586 }
7587 return device;
7588}
7589
Eric Laurent1c333e22014-05-20 10:48:17 -07007590AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7591 audio_devices_t type) const
7592{
7593 DeviceVector devices;
7594 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7595 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7596 devices.add(itemAt(i));
7597 type &= ~itemAt(i)->mDeviceType;
7598 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7599 itemAt(i)->mDeviceType, itemAt(i).get());
7600 }
7601 }
7602 return devices;
7603}
7604
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007605AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7606 audio_devices_t type, String8 address) const
7607{
7608 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007609 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007610 if (itemAt(i)->mDeviceType == type) {
7611 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007612 devices.add(itemAt(i));
7613 }
7614 }
7615 }
7616 return devices;
7617}
7618
Eric Laurent1afeecb2014-05-14 08:52:28 -07007619sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7620 const String8& name) const
7621{
7622 sp<DeviceDescriptor> device;
7623 for (size_t i = 0; i < size(); i++) {
7624 if (itemAt(i)->mName == name) {
7625 device = itemAt(i);
7626 break;
7627 }
7628 }
7629 return device;
7630}
7631
Eric Laurent6a94d692014-05-20 11:18:06 -07007632void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7633 struct audio_port_config *dstConfig,
7634 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007635{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007636 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7637 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007638 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007639 }
7640
7641 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7642
Eric Laurent6a94d692014-05-20 11:18:06 -07007643 dstConfig->id = mId;
7644 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007645 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007646 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007647 dstConfig->ext.device.type = mDeviceType;
7648 dstConfig->ext.device.hw_module = mModule->mHandle;
7649 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007650}
7651
7652void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7653{
Eric Laurent83b88082014-06-20 18:31:16 -07007654 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007655 AudioPort::toAudioPort(port);
7656 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007657 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007658 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007659 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007660 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7661}
7662
Eric Laurent1afeecb2014-05-14 08:52:28 -07007663status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007664{
7665 const size_t SIZE = 256;
7666 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007667 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007668
Eric Laurent1afeecb2014-05-14 08:52:28 -07007669 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7670 result.append(buffer);
7671 if (mId != 0) {
7672 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7673 result.append(buffer);
7674 }
7675 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7676 enumToString(sDeviceNameToEnumTable,
7677 ARRAY_SIZE(sDeviceNameToEnumTable),
7678 mDeviceType));
7679 result.append(buffer);
7680 if (mAddress.size() != 0) {
7681 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7682 result.append(buffer);
7683 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007684 write(fd, result.string(), result.size());
7685 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007686
7687 return NO_ERROR;
7688}
7689
Eric Laurent4d416952014-08-10 14:07:09 -07007690status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7691{
7692 const size_t SIZE = 256;
7693 char buffer[SIZE];
7694 String8 result;
7695
7696
7697 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7698 result.append(buffer);
7699 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7700 result.append(buffer);
7701 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7702 result.append(buffer);
7703 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7704 result.append(buffer);
7705 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7706 result.append(buffer);
7707 for (size_t i = 0; i < mPatch.num_sources; i++) {
7708 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7709 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7710 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7711 ARRAY_SIZE(sDeviceNameToEnumTable),
7712 mPatch.sources[i].ext.device.type));
7713 } else {
7714 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7715 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7716 }
7717 result.append(buffer);
7718 }
7719 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7720 result.append(buffer);
7721 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7722 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7723 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7724 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7725 ARRAY_SIZE(sDeviceNameToEnumTable),
7726 mPatch.sinks[i].ext.device.type));
7727 } else {
7728 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7729 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7730 }
7731 result.append(buffer);
7732 }
7733
7734 write(fd, result.string(), result.size());
7735 return NO_ERROR;
7736}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007737
7738// --- audio_policy.conf file parsing
7739
Eric Laurent5dbe4712014-09-19 19:04:57 -07007740uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007741{
7742 uint32_t flag = 0;
7743
7744 // it is OK to cast name to non const here as we are not going to use it after
7745 // strtok() modifies it
7746 char *flagName = strtok(name, "|");
7747 while (flagName != NULL) {
7748 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007749 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7750 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007751 flagName);
7752 }
7753 flagName = strtok(NULL, "|");
7754 }
7755 //force direct flag if offload flag is set: offloading implies a direct output stream
7756 // and all common behaviors are driven by checking only the direct flag
7757 // this should normally be set appropriately in the policy configuration file
7758 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7759 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7760 }
7761
Eric Laurent5dbe4712014-09-19 19:04:57 -07007762 return flag;
7763}
7764
7765uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7766{
7767 uint32_t flag = 0;
7768
7769 // it is OK to cast name to non const here as we are not going to use it after
7770 // strtok() modifies it
7771 char *flagName = strtok(name, "|");
7772 while (flagName != NULL) {
7773 if (strlen(flagName) != 0) {
7774 flag |= stringToEnum(sInputFlagNameToEnumTable,
7775 ARRAY_SIZE(sInputFlagNameToEnumTable),
7776 flagName);
7777 }
7778 flagName = strtok(NULL, "|");
7779 }
7780 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007781}
7782
Eric Laurente0720872014-03-11 09:30:41 -07007783audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007784{
7785 uint32_t device = 0;
7786
7787 char *devName = strtok(name, "|");
7788 while (devName != NULL) {
7789 if (strlen(devName) != 0) {
7790 device |= stringToEnum(sDeviceNameToEnumTable,
7791 ARRAY_SIZE(sDeviceNameToEnumTable),
7792 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007793 }
Eric Laurente552edb2014-03-10 17:42:56 -07007794 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007795 }
Eric Laurente552edb2014-03-10 17:42:56 -07007796 return device;
7797}
7798
Eric Laurente0720872014-03-11 09:30:41 -07007799void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007800{
Eric Laurente552edb2014-03-10 17:42:56 -07007801 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007802 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007803 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007804
Eric Laurent1afeecb2014-05-14 08:52:28 -07007805 node = config_find(root, DEVICES_TAG);
7806 if (node != NULL) {
7807 node = node->first_child;
7808 while (node) {
7809 ALOGV("loadHwModule() loading device %s", node->name);
7810 status_t tmpStatus = module->loadDevice(node);
7811 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7812 status = tmpStatus;
7813 }
7814 node = node->next;
7815 }
7816 }
7817 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007818 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007819 node = node->first_child;
7820 while (node) {
7821 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007822 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007823 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7824 status = tmpStatus;
7825 }
7826 node = node->next;
7827 }
7828 }
7829 node = config_find(root, INPUTS_TAG);
7830 if (node != NULL) {
7831 node = node->first_child;
7832 while (node) {
7833 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007834 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007835 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7836 status = tmpStatus;
7837 }
7838 node = node->next;
7839 }
7840 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007841 loadGlobalConfig(root, module);
7842
Eric Laurente552edb2014-03-10 17:42:56 -07007843 if (status == NO_ERROR) {
7844 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007845 }
7846}
7847
Eric Laurente0720872014-03-11 09:30:41 -07007848void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007849{
7850 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7851 if (node == NULL) {
7852 return;
7853 }
7854
7855 node = node->first_child;
7856 while (node) {
7857 ALOGV("loadHwModules() loading module %s", node->name);
7858 loadHwModule(node);
7859 node = node->next;
7860 }
7861}
7862
Eric Laurent1f2f2232014-06-02 12:01:23 -07007863void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007864{
7865 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007866
Eric Laurente552edb2014-03-10 17:42:56 -07007867 if (node == NULL) {
7868 return;
7869 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007870 DeviceVector declaredDevices;
7871 if (module != NULL) {
7872 declaredDevices = module->mDeclaredDevices;
7873 }
7874
Eric Laurente552edb2014-03-10 17:42:56 -07007875 node = node->first_child;
7876 while (node) {
7877 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007878 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7879 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007880 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7881 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007882 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007883 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007884 ARRAY_SIZE(sDeviceNameToEnumTable),
7885 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007886 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007887 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007888 } else {
7889 ALOGW("loadGlobalConfig() default device not specified");
7890 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007891 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007892 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007893 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7894 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007895 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007896 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7897 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7898 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007899 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7900 uint32_t major, minor;
7901 sscanf((char *)node->value, "%u.%u", &major, &minor);
7902 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7903 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7904 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007905 }
7906 node = node->next;
7907 }
7908}
7909
Eric Laurente0720872014-03-11 09:30:41 -07007910status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007911{
7912 cnode *root;
7913 char *data;
7914
7915 data = (char *)load_file(path, NULL);
7916 if (data == NULL) {
7917 return -ENODEV;
7918 }
7919 root = config_node("", "");
7920 config_load(root, data);
7921
Eric Laurente552edb2014-03-10 17:42:56 -07007922 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007923 // legacy audio_policy.conf files have one global_configuration section
7924 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007925 config_free(root);
7926 free(root);
7927 free(data);
7928
7929 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7930
7931 return NO_ERROR;
7932}
7933
Eric Laurente0720872014-03-11 09:30:41 -07007934void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007935{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007936 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007937 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007938 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7939 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007940 mAvailableOutputDevices.add(mDefaultOutputDevice);
7941 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007942
7943 module = new HwModule("primary");
7944
Eric Laurent1afeecb2014-05-14 08:52:28 -07007945 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007946 profile->mSamplingRates.add(44100);
7947 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7948 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007949 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007950 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7951 module->mOutputProfiles.add(profile);
7952
Eric Laurent1afeecb2014-05-14 08:52:28 -07007953 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007954 profile->mSamplingRates.add(8000);
7955 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7956 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007957 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007958 module->mInputProfiles.add(profile);
7959
7960 mHwModules.add(module);
7961}
7962
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007963audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7964{
7965 // flags to stream type mapping
7966 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7967 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7968 }
7969 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7970 return AUDIO_STREAM_BLUETOOTH_SCO;
7971 }
7972
7973 // usage to stream type mapping
7974 switch (attr->usage) {
7975 case AUDIO_USAGE_MEDIA:
7976 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007977 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7978 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007979 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007980 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7981 return AUDIO_STREAM_ALARM;
7982 }
7983 if (isStreamActive(AUDIO_STREAM_RING)) {
7984 return AUDIO_STREAM_RING;
7985 }
7986 if (isInCall()) {
7987 return AUDIO_STREAM_VOICE_CALL;
7988 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08007989 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007990 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7991 return AUDIO_STREAM_SYSTEM;
7992 case AUDIO_USAGE_VOICE_COMMUNICATION:
7993 return AUDIO_STREAM_VOICE_CALL;
7994
7995 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7996 return AUDIO_STREAM_DTMF;
7997
7998 case AUDIO_USAGE_ALARM:
7999 return AUDIO_STREAM_ALARM;
8000 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8001 return AUDIO_STREAM_RING;
8002
8003 case AUDIO_USAGE_NOTIFICATION:
8004 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8005 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8006 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8007 case AUDIO_USAGE_NOTIFICATION_EVENT:
8008 return AUDIO_STREAM_NOTIFICATION;
8009
8010 case AUDIO_USAGE_UNKNOWN:
8011 default:
8012 return AUDIO_STREAM_MUSIC;
8013 }
8014}
Eric Laurente83b55d2014-11-14 10:06:21 -08008015
8016bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
8017 // has flags that map to a strategy?
8018 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8019 return true;
8020 }
8021
8022 // has known usage?
8023 switch (paa->usage) {
8024 case AUDIO_USAGE_UNKNOWN:
8025 case AUDIO_USAGE_MEDIA:
8026 case AUDIO_USAGE_VOICE_COMMUNICATION:
8027 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8028 case AUDIO_USAGE_ALARM:
8029 case AUDIO_USAGE_NOTIFICATION:
8030 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8031 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8032 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8033 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8034 case AUDIO_USAGE_NOTIFICATION_EVENT:
8035 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8036 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8037 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8038 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008039 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08008040 break;
8041 default:
8042 return false;
8043 }
8044 return true;
8045}
8046
Eric Laurente552edb2014-03-10 17:42:56 -07008047}; // namespace android