blob: be7158ffe8c544339922b67747fe23a6e9f8514e [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 Laurente552edb2014-03-10 17:42:56 -07002058 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07002059 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07002060 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
2061 && (inputDescriptor->mRefCount > 0)) {
2062 return true;
2063 }
2064 }
2065 return false;
2066}
2067
Eric Laurent275e8e92014-11-30 15:14:47 -08002068// Register a list of custom mixes with their attributes and format.
2069// When a mix is registered, corresponding input and output profiles are
2070// added to the remote submix hw module. The profile contains only the
2071// parameters (sampling rate, format...) specified by the mix.
2072// The corresponding input remote submix device is also connected.
2073//
2074// When a remote submix device is connected, the address is checked to select the
2075// appropriate profile and the corresponding input or output stream is opened.
2076//
2077// When capture starts, getInputForAttr() will:
2078// - 1 look for a mix matching the address passed in attribtutes tags if any
2079// - 2 if none found, getDeviceForInputSource() will:
2080// - 2.1 look for a mix matching the attributes source
2081// - 2.2 if none found, default to device selection by policy rules
2082// At this time, the corresponding output remote submix device is also connected
2083// and active playback use cases can be transferred to this mix if needed when reconnecting
2084// after AudioTracks are invalidated
2085//
2086// When playback starts, getOutputForAttr() will:
2087// - 1 look for a mix matching the address passed in attribtutes tags if any
2088// - 2 if none found, look for a mix matching the attributes usage
2089// - 3 if none found, default to device and output selection by policy rules.
2090
2091status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2092{
2093 sp<HwModule> module;
2094 for (size_t i = 0; i < mHwModules.size(); i++) {
2095 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2096 mHwModules[i]->mHandle != 0) {
2097 module = mHwModules[i];
2098 break;
2099 }
2100 }
2101
2102 if (module == 0) {
2103 return INVALID_OPERATION;
2104 }
2105
2106 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2107
2108 for (size_t i = 0; i < mixes.size(); i++) {
2109 String8 address = mixes[i].mRegistrationId;
2110 ssize_t index = mPolicyMixes.indexOfKey(address);
2111 if (index >= 0) {
2112 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2113 continue;
2114 }
2115 audio_config_t outputConfig = mixes[i].mFormat;
2116 audio_config_t inputConfig = mixes[i].mFormat;
2117 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2118 // stereo and let audio flinger do the channel conversion if needed.
2119 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2120 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2121 module->addOutputProfile(address, &outputConfig,
2122 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2123 module->addInputProfile(address, &inputConfig,
2124 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2125 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2126 policyMix->mMix = mixes[i];
2127 mPolicyMixes.add(address, policyMix);
Eric Laurentc722f302014-12-10 11:21:49 -08002128 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002129 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002130 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2131 address.string());
2132 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002133 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002134 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2135 address.string());
2136 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002137 }
2138 return NO_ERROR;
2139}
2140
2141status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2142{
2143 sp<HwModule> module;
2144 for (size_t i = 0; i < mHwModules.size(); i++) {
2145 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2146 mHwModules[i]->mHandle != 0) {
2147 module = mHwModules[i];
2148 break;
2149 }
2150 }
2151
2152 if (module == 0) {
2153 return INVALID_OPERATION;
2154 }
2155
2156 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2157
2158 for (size_t i = 0; i < mixes.size(); i++) {
2159 String8 address = mixes[i].mRegistrationId;
2160 ssize_t index = mPolicyMixes.indexOfKey(address);
2161 if (index < 0) {
2162 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2163 continue;
2164 }
2165
2166 mPolicyMixes.removeItemsAt(index);
2167
Eric Laurentc722f302014-12-10 11:21:49 -08002168 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2169 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2170 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002171 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002172 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2173 address.string());
2174 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002175
2176 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2177 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2178 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002179 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002180 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2181 address.string());
2182 }
2183 module->removeOutputProfile(address);
2184 module->removeInputProfile(address);
2185 }
2186 return NO_ERROR;
2187}
2188
Eric Laurente552edb2014-03-10 17:42:56 -07002189
Eric Laurente0720872014-03-11 09:30:41 -07002190status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002191{
2192 const size_t SIZE = 256;
2193 char buffer[SIZE];
2194 String8 result;
2195
2196 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2197 result.append(buffer);
2198
2199 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2200 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002201 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2202 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002203 snprintf(buffer, SIZE, " Force use for communications %d\n",
2204 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002205 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002206 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002207 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002208 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07002209 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002210 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07002211 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002212 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002213 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002214 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2215 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2216 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002217
Eric Laurent3a4311c2014-03-17 12:00:47 -07002218 snprintf(buffer, SIZE, " Available output devices:\n");
2219 result.append(buffer);
2220 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002221 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002222 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002223 }
2224 snprintf(buffer, SIZE, "\n Available input devices:\n");
2225 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002226 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002227 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002228 }
Eric Laurente552edb2014-03-10 17:42:56 -07002229
2230 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2231 write(fd, buffer, strlen(buffer));
2232 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002233 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002234 write(fd, buffer, strlen(buffer));
2235 mHwModules[i]->dump(fd);
2236 }
2237
2238 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2239 write(fd, buffer, strlen(buffer));
2240 for (size_t i = 0; i < mOutputs.size(); i++) {
2241 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2242 write(fd, buffer, strlen(buffer));
2243 mOutputs.valueAt(i)->dump(fd);
2244 }
2245
2246 snprintf(buffer, SIZE, "\nInputs dump:\n");
2247 write(fd, buffer, strlen(buffer));
2248 for (size_t i = 0; i < mInputs.size(); i++) {
2249 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2250 write(fd, buffer, strlen(buffer));
2251 mInputs.valueAt(i)->dump(fd);
2252 }
2253
2254 snprintf(buffer, SIZE, "\nStreams dump:\n");
2255 write(fd, buffer, strlen(buffer));
2256 snprintf(buffer, SIZE,
2257 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2258 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002259 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002260 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002261 write(fd, buffer, strlen(buffer));
2262 mStreams[i].dump(fd);
2263 }
2264
2265 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2266 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2267 write(fd, buffer, strlen(buffer));
2268
2269 snprintf(buffer, SIZE, "Registered effects:\n");
2270 write(fd, buffer, strlen(buffer));
2271 for (size_t i = 0; i < mEffects.size(); i++) {
2272 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2273 write(fd, buffer, strlen(buffer));
2274 mEffects.valueAt(i)->dump(fd);
2275 }
2276
Eric Laurent4d416952014-08-10 14:07:09 -07002277 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2278 write(fd, buffer, strlen(buffer));
2279 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2280 mAudioPatches[i]->dump(fd, 2, i);
2281 }
Eric Laurente552edb2014-03-10 17:42:56 -07002282
2283 return NO_ERROR;
2284}
2285
2286// This function checks for the parameters which can be offloaded.
2287// This can be enhanced depending on the capability of the DSP and policy
2288// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002289bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002290{
2291 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002292 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002293 offloadInfo.sample_rate, offloadInfo.channel_mask,
2294 offloadInfo.format,
2295 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2296 offloadInfo.has_video);
2297
2298 // Check if offload has been disabled
2299 char propValue[PROPERTY_VALUE_MAX];
2300 if (property_get("audio.offload.disable", propValue, "0")) {
2301 if (atoi(propValue) != 0) {
2302 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2303 return false;
2304 }
2305 }
2306
2307 // Check if stream type is music, then only allow offload as of now.
2308 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2309 {
2310 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2311 return false;
2312 }
2313
2314 //TODO: enable audio offloading with video when ready
2315 if (offloadInfo.has_video)
2316 {
2317 ALOGV("isOffloadSupported: has_video == true, returning false");
2318 return false;
2319 }
2320
2321 //If duration is less than minimum value defined in property, return false
2322 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2323 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2324 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2325 return false;
2326 }
2327 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2328 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2329 return false;
2330 }
2331
2332 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2333 // creating an offloaded track and tearing it down immediately after start when audioflinger
2334 // detects there is an active non offloadable effect.
2335 // FIXME: We should check the audio session here but we do not have it in this context.
2336 // This may prevent offloading in rare situations where effects are left active by apps
2337 // in the background.
2338 if (isNonOffloadableEffectEnabled()) {
2339 return false;
2340 }
2341
2342 // See if there is a profile to support this.
2343 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002344 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002345 offloadInfo.sample_rate,
2346 offloadInfo.format,
2347 offloadInfo.channel_mask,
2348 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002349 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2350 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002351}
2352
Eric Laurent6a94d692014-05-20 11:18:06 -07002353status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2354 audio_port_type_t type,
2355 unsigned int *num_ports,
2356 struct audio_port *ports,
2357 unsigned int *generation)
2358{
2359 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2360 generation == NULL) {
2361 return BAD_VALUE;
2362 }
2363 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2364 if (ports == NULL) {
2365 *num_ports = 0;
2366 }
2367
2368 size_t portsWritten = 0;
2369 size_t portsMax = *num_ports;
2370 *num_ports = 0;
2371 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2372 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2373 for (size_t i = 0;
2374 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2375 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2376 }
2377 *num_ports += mAvailableOutputDevices.size();
2378 }
2379 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2380 for (size_t i = 0;
2381 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2382 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2383 }
2384 *num_ports += mAvailableInputDevices.size();
2385 }
2386 }
2387 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2388 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2389 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2390 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2391 }
2392 *num_ports += mInputs.size();
2393 }
2394 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002395 size_t numOutputs = 0;
2396 for (size_t i = 0; i < mOutputs.size(); i++) {
2397 if (!mOutputs[i]->isDuplicated()) {
2398 numOutputs++;
2399 if (portsWritten < portsMax) {
2400 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2401 }
2402 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002403 }
Eric Laurent84c70242014-06-23 08:46:27 -07002404 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002405 }
2406 }
2407 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002408 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002409 return NO_ERROR;
2410}
2411
2412status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2413{
2414 return NO_ERROR;
2415}
2416
Eric Laurent1f2f2232014-06-02 12:01:23 -07002417sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002418 audio_port_handle_t id) const
2419{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002420 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002421 for (size_t i = 0; i < mOutputs.size(); i++) {
2422 outputDesc = mOutputs.valueAt(i);
2423 if (outputDesc->mId == id) {
2424 break;
2425 }
2426 }
2427 return outputDesc;
2428}
2429
Eric Laurent1f2f2232014-06-02 12:01:23 -07002430sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002431 audio_port_handle_t id) const
2432{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002433 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002434 for (size_t i = 0; i < mInputs.size(); i++) {
2435 inputDesc = mInputs.valueAt(i);
2436 if (inputDesc->mId == id) {
2437 break;
2438 }
2439 }
2440 return inputDesc;
2441}
2442
Eric Laurent1f2f2232014-06-02 12:01:23 -07002443sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2444 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002445{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002446 sp <HwModule> module;
2447
Eric Laurent6a94d692014-05-20 11:18:06 -07002448 for (size_t i = 0; i < mHwModules.size(); i++) {
2449 if (mHwModules[i]->mHandle == 0) {
2450 continue;
2451 }
2452 if (audio_is_output_device(device)) {
2453 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2454 {
2455 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2456 return mHwModules[i];
2457 }
2458 }
2459 } else {
2460 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2461 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2462 device & ~AUDIO_DEVICE_BIT_IN) {
2463 return mHwModules[i];
2464 }
2465 }
2466 }
2467 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002468 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002469}
2470
Eric Laurent1f2f2232014-06-02 12:01:23 -07002471sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002472{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002473 sp <HwModule> module;
2474
Eric Laurent1afeecb2014-05-14 08:52:28 -07002475 for (size_t i = 0; i < mHwModules.size(); i++)
2476 {
2477 if (strcmp(mHwModules[i]->mName, name) == 0) {
2478 return mHwModules[i];
2479 }
2480 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002481 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002482}
2483
Eric Laurentc2730ba2014-07-20 15:47:07 -07002484audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2485{
2486 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2487 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2488 return devices & mAvailableOutputDevices.types();
2489}
2490
2491audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2492{
2493 audio_module_handle_t primaryHandle =
2494 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2495 audio_devices_t devices = AUDIO_DEVICE_NONE;
2496 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2497 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2498 devices |= mAvailableInputDevices[i]->mDeviceType;
2499 }
2500 }
2501 return devices;
2502}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002503
Eric Laurent6a94d692014-05-20 11:18:06 -07002504status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2505 audio_patch_handle_t *handle,
2506 uid_t uid)
2507{
2508 ALOGV("createAudioPatch()");
2509
2510 if (handle == NULL || patch == NULL) {
2511 return BAD_VALUE;
2512 }
2513 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2514
Eric Laurent874c42872014-08-08 15:13:39 -07002515 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2516 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2517 return BAD_VALUE;
2518 }
2519 // only one source per audio patch supported for now
2520 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002521 return INVALID_OPERATION;
2522 }
Eric Laurent874c42872014-08-08 15:13:39 -07002523
2524 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002525 return INVALID_OPERATION;
2526 }
Eric Laurent874c42872014-08-08 15:13:39 -07002527 for (size_t i = 0; i < patch->num_sinks; i++) {
2528 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2529 return INVALID_OPERATION;
2530 }
2531 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002532
2533 sp<AudioPatch> patchDesc;
2534 ssize_t index = mAudioPatches.indexOfKey(*handle);
2535
Eric Laurent6a94d692014-05-20 11:18:06 -07002536 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2537 patch->sources[0].role,
2538 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002539#if LOG_NDEBUG == 0
2540 for (size_t i = 0; i < patch->num_sinks; i++) {
2541 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2542 patch->sinks[i].role,
2543 patch->sinks[i].type);
2544 }
2545#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002546
2547 if (index >= 0) {
2548 patchDesc = mAudioPatches.valueAt(index);
2549 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2550 mUidCached, patchDesc->mUid, uid);
2551 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2552 return INVALID_OPERATION;
2553 }
2554 } else {
2555 *handle = 0;
2556 }
2557
2558 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002559 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002560 if (outputDesc == NULL) {
2561 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2562 return BAD_VALUE;
2563 }
Eric Laurent84c70242014-06-23 08:46:27 -07002564 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2565 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002566 if (patchDesc != 0) {
2567 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2568 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2569 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2570 return BAD_VALUE;
2571 }
2572 }
Eric Laurent874c42872014-08-08 15:13:39 -07002573 DeviceVector devices;
2574 for (size_t i = 0; i < patch->num_sinks; i++) {
2575 // Only support mix to devices connection
2576 // TODO add support for mix to mix connection
2577 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2578 ALOGV("createAudioPatch() source mix but sink is not a device");
2579 return INVALID_OPERATION;
2580 }
2581 sp<DeviceDescriptor> devDesc =
2582 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2583 if (devDesc == 0) {
2584 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2585 return BAD_VALUE;
2586 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002587
Eric Laurent874c42872014-08-08 15:13:39 -07002588 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002589 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002590 patch->sources[0].sample_rate,
2591 NULL, // updatedSamplingRate
2592 patch->sources[0].format,
2593 patch->sources[0].channel_mask,
2594 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2595 ALOGV("createAudioPatch() profile not supported for device %08x",
2596 devDesc->mDeviceType);
2597 return INVALID_OPERATION;
2598 }
2599 devices.add(devDesc);
2600 }
2601 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002602 return INVALID_OPERATION;
2603 }
Eric Laurent874c42872014-08-08 15:13:39 -07002604
Eric Laurent6a94d692014-05-20 11:18:06 -07002605 // TODO: reconfigure output format and channels here
2606 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002607 devices.types(), outputDesc->mIoHandle);
2608 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002609 index = mAudioPatches.indexOfKey(*handle);
2610 if (index >= 0) {
2611 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2612 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2613 }
2614 patchDesc = mAudioPatches.valueAt(index);
2615 patchDesc->mUid = uid;
2616 ALOGV("createAudioPatch() success");
2617 } else {
2618 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2619 return INVALID_OPERATION;
2620 }
2621 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2622 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2623 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002624 // only one sink supported when connecting an input device to a mix
2625 if (patch->num_sinks > 1) {
2626 return INVALID_OPERATION;
2627 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002628 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002629 if (inputDesc == NULL) {
2630 return BAD_VALUE;
2631 }
2632 if (patchDesc != 0) {
2633 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2634 return BAD_VALUE;
2635 }
2636 }
2637 sp<DeviceDescriptor> devDesc =
2638 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2639 if (devDesc == 0) {
2640 return BAD_VALUE;
2641 }
2642
Eric Laurent84c70242014-06-23 08:46:27 -07002643 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002644 devDesc->mAddress,
2645 patch->sinks[0].sample_rate,
2646 NULL, /*updatedSampleRate*/
2647 patch->sinks[0].format,
2648 patch->sinks[0].channel_mask,
2649 // FIXME for the parameter type,
2650 // and the NONE
2651 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002652 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002653 return INVALID_OPERATION;
2654 }
2655 // TODO: reconfigure output format and channels here
2656 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002657 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002658 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002659 index = mAudioPatches.indexOfKey(*handle);
2660 if (index >= 0) {
2661 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2662 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2663 }
2664 patchDesc = mAudioPatches.valueAt(index);
2665 patchDesc->mUid = uid;
2666 ALOGV("createAudioPatch() success");
2667 } else {
2668 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2669 return INVALID_OPERATION;
2670 }
2671 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2672 // device to device connection
2673 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002674 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002675 return BAD_VALUE;
2676 }
2677 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002678 sp<DeviceDescriptor> srcDeviceDesc =
2679 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002680 if (srcDeviceDesc == 0) {
2681 return BAD_VALUE;
2682 }
Eric Laurent874c42872014-08-08 15:13:39 -07002683
Eric Laurent6a94d692014-05-20 11:18:06 -07002684 //update source and sink with our own data as the data passed in the patch may
2685 // be incomplete.
2686 struct audio_patch newPatch = *patch;
2687 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002688
Eric Laurent874c42872014-08-08 15:13:39 -07002689 for (size_t i = 0; i < patch->num_sinks; i++) {
2690 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2691 ALOGV("createAudioPatch() source device but one sink is not a device");
2692 return INVALID_OPERATION;
2693 }
2694
2695 sp<DeviceDescriptor> sinkDeviceDesc =
2696 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2697 if (sinkDeviceDesc == 0) {
2698 return BAD_VALUE;
2699 }
2700 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2701
2702 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2703 // only one sink supported when connected devices across HW modules
2704 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002705 return INVALID_OPERATION;
2706 }
Eric Laurent874c42872014-08-08 15:13:39 -07002707 SortedVector<audio_io_handle_t> outputs =
2708 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2709 mOutputs);
2710 // if the sink device is reachable via an opened output stream, request to go via
2711 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002712 audio_io_handle_t output = selectOutput(outputs,
2713 AUDIO_OUTPUT_FLAG_NONE,
2714 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002715 if (output != AUDIO_IO_HANDLE_NONE) {
2716 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2717 if (outputDesc->isDuplicated()) {
2718 return INVALID_OPERATION;
2719 }
2720 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2721 newPatch.num_sources = 2;
2722 }
Eric Laurent83b88082014-06-20 18:31:16 -07002723 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002724 }
2725 // TODO: check from routing capabilities in config file and other conflicting patches
2726
2727 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2728 if (index >= 0) {
2729 afPatchHandle = patchDesc->mAfPatchHandle;
2730 }
2731
2732 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2733 &afPatchHandle,
2734 0);
2735 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2736 status, afPatchHandle);
2737 if (status == NO_ERROR) {
2738 if (index < 0) {
2739 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2740 &newPatch, uid);
2741 addAudioPatch(patchDesc->mHandle, patchDesc);
2742 } else {
2743 patchDesc->mPatch = newPatch;
2744 }
2745 patchDesc->mAfPatchHandle = afPatchHandle;
2746 *handle = patchDesc->mHandle;
2747 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002748 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002749 } else {
2750 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2751 status);
2752 return INVALID_OPERATION;
2753 }
2754 } else {
2755 return BAD_VALUE;
2756 }
2757 } else {
2758 return BAD_VALUE;
2759 }
2760 return NO_ERROR;
2761}
2762
2763status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2764 uid_t uid)
2765{
2766 ALOGV("releaseAudioPatch() patch %d", handle);
2767
2768 ssize_t index = mAudioPatches.indexOfKey(handle);
2769
2770 if (index < 0) {
2771 return BAD_VALUE;
2772 }
2773 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2774 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2775 mUidCached, patchDesc->mUid, uid);
2776 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2777 return INVALID_OPERATION;
2778 }
2779
2780 struct audio_patch *patch = &patchDesc->mPatch;
2781 patchDesc->mUid = mUidCached;
2782 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002783 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002784 if (outputDesc == NULL) {
2785 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2786 return BAD_VALUE;
2787 }
2788
2789 setOutputDevice(outputDesc->mIoHandle,
2790 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2791 true,
2792 0,
2793 NULL);
2794 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2795 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002796 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002797 if (inputDesc == NULL) {
2798 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2799 return BAD_VALUE;
2800 }
2801 setInputDevice(inputDesc->mIoHandle,
2802 getNewInputDevice(inputDesc->mIoHandle),
2803 true,
2804 NULL);
2805 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2806 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2807 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2808 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2809 status, patchDesc->mAfPatchHandle);
2810 removeAudioPatch(patchDesc->mHandle);
2811 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002812 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002813 } else {
2814 return BAD_VALUE;
2815 }
2816 } else {
2817 return BAD_VALUE;
2818 }
2819 return NO_ERROR;
2820}
2821
2822status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2823 struct audio_patch *patches,
2824 unsigned int *generation)
2825{
2826 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2827 generation == NULL) {
2828 return BAD_VALUE;
2829 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002830 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002831 *num_patches, patches, mAudioPatches.size());
2832 if (patches == NULL) {
2833 *num_patches = 0;
2834 }
2835
2836 size_t patchesWritten = 0;
2837 size_t patchesMax = *num_patches;
2838 for (size_t i = 0;
2839 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2840 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2841 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002842 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002843 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2844 }
2845 *num_patches = mAudioPatches.size();
2846
2847 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002848 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002849 return NO_ERROR;
2850}
2851
Eric Laurente1715a42014-05-20 11:30:42 -07002852status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002853{
Eric Laurente1715a42014-05-20 11:30:42 -07002854 ALOGV("setAudioPortConfig()");
2855
2856 if (config == NULL) {
2857 return BAD_VALUE;
2858 }
2859 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2860 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002861 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2862 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002863 }
2864
Eric Laurenta121f902014-06-03 13:32:54 -07002865 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002866 if (config->type == AUDIO_PORT_TYPE_MIX) {
2867 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002868 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002869 if (outputDesc == NULL) {
2870 return BAD_VALUE;
2871 }
Eric Laurent84c70242014-06-23 08:46:27 -07002872 ALOG_ASSERT(!outputDesc->isDuplicated(),
2873 "setAudioPortConfig() called on duplicated output %d",
2874 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002875 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002876 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002877 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002878 if (inputDesc == NULL) {
2879 return BAD_VALUE;
2880 }
Eric Laurenta121f902014-06-03 13:32:54 -07002881 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002882 } else {
2883 return BAD_VALUE;
2884 }
2885 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2886 sp<DeviceDescriptor> deviceDesc;
2887 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2888 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2889 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2890 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2891 } else {
2892 return BAD_VALUE;
2893 }
2894 if (deviceDesc == NULL) {
2895 return BAD_VALUE;
2896 }
Eric Laurenta121f902014-06-03 13:32:54 -07002897 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002898 } else {
2899 return BAD_VALUE;
2900 }
2901
Eric Laurenta121f902014-06-03 13:32:54 -07002902 struct audio_port_config backupConfig;
2903 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2904 if (status == NO_ERROR) {
2905 struct audio_port_config newConfig;
2906 audioPortConfig->toAudioPortConfig(&newConfig, config);
2907 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002908 }
Eric Laurenta121f902014-06-03 13:32:54 -07002909 if (status != NO_ERROR) {
2910 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002911 }
Eric Laurente1715a42014-05-20 11:30:42 -07002912
2913 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002914}
2915
2916void AudioPolicyManager::clearAudioPatches(uid_t uid)
2917{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002918 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002919 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2920 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002921 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002922 }
2923 }
2924}
2925
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002926status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2927 audio_io_handle_t *ioHandle,
2928 audio_devices_t *device)
2929{
2930 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2931 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002932 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002933
2934 mSoundTriggerSessions.add(*session, *ioHandle);
2935
2936 return NO_ERROR;
2937}
2938
2939status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2940{
2941 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2942 if (index < 0) {
2943 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2944 return BAD_VALUE;
2945 }
2946
2947 mSoundTriggerSessions.removeItem(session);
2948 return NO_ERROR;
2949}
2950
Eric Laurent6a94d692014-05-20 11:18:06 -07002951status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2952 const sp<AudioPatch>& patch)
2953{
2954 ssize_t index = mAudioPatches.indexOfKey(handle);
2955
2956 if (index >= 0) {
2957 ALOGW("addAudioPatch() patch %d already in", handle);
2958 return ALREADY_EXISTS;
2959 }
2960 mAudioPatches.add(handle, patch);
2961 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2962 "sink handle %d",
2963 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2964 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2965 return NO_ERROR;
2966}
2967
2968status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2969{
2970 ssize_t index = mAudioPatches.indexOfKey(handle);
2971
2972 if (index < 0) {
2973 ALOGW("removeAudioPatch() patch %d not in", handle);
2974 return ALREADY_EXISTS;
2975 }
2976 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2977 mAudioPatches.valueAt(index)->mAfPatchHandle);
2978 mAudioPatches.removeItemsAt(index);
2979 return NO_ERROR;
2980}
2981
Eric Laurente552edb2014-03-10 17:42:56 -07002982// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002983// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002984// ----------------------------------------------------------------------------
2985
Eric Laurent3a4311c2014-03-17 12:00:47 -07002986uint32_t AudioPolicyManager::nextUniqueId()
2987{
2988 return android_atomic_inc(&mNextUniqueId);
2989}
2990
Eric Laurent6a94d692014-05-20 11:18:06 -07002991uint32_t AudioPolicyManager::nextAudioPortGeneration()
2992{
2993 return android_atomic_inc(&mAudioPortGeneration);
2994}
2995
Eric Laurente0720872014-03-11 09:30:41 -07002996AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002997 :
2998#ifdef AUDIO_POLICY_TEST
2999 Thread(false),
3000#endif //AUDIO_POLICY_TEST
3001 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07003002 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07003003 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
3004 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003005 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07003006 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003007 mAudioPortGeneration(1),
3008 mBeaconMuteRefCount(0),
3009 mBeaconPlayingRefCount(0),
3010 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003011{
Eric Laurent6a94d692014-05-20 11:18:06 -07003012 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07003013 mpClientInterface = clientInterface;
3014
Eric Laurent3b73df72014-03-11 09:06:29 -07003015 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
3016 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003017 }
3018
Eric Laurent1afeecb2014-05-14 08:52:28 -07003019 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07003020 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
3021 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
3022 ALOGE("could not load audio policy configuration file, setting defaults");
3023 defaultAudioPolicyConfig();
3024 }
3025 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003026 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003027
3028 // must be done after reading the policy
3029 initializeVolumeCurves();
3030
3031 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003032 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3033 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003034 for (size_t i = 0; i < mHwModules.size(); i++) {
3035 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3036 if (mHwModules[i]->mHandle == 0) {
3037 ALOGW("could not open HW module %s", mHwModules[i]->mName);
3038 continue;
3039 }
3040 // open all output streams needed to access attached devices
3041 // except for direct output streams that are only opened when they are actually
3042 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003043 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003044 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3045 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003046 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003047
Eric Laurent3a4311c2014-03-17 12:00:47 -07003048 if (outProfile->mSupportedDevices.isEmpty()) {
3049 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3050 continue;
3051 }
3052
Eric Laurentd78f1532014-09-16 16:38:20 -07003053 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3054 continue;
3055 }
Eric Laurent83b88082014-06-20 18:31:16 -07003056 audio_devices_t profileType = outProfile->mSupportedDevices.types();
3057 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3058 profileType = mDefaultOutputDevice->mDeviceType;
3059 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07003060 // chose first device present in mSupportedDevices also part of
3061 // outputDeviceTypes
3062 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3063 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3064 if ((profileType & outputDeviceTypes) != 0) {
3065 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003066 }
Eric Laurente552edb2014-03-10 17:42:56 -07003067 }
3068 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003069 if ((profileType & outputDeviceTypes) == 0) {
3070 continue;
3071 }
3072 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3073
3074 outputDesc->mDevice = profileType;
3075 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3076 config.sample_rate = outputDesc->mSamplingRate;
3077 config.channel_mask = outputDesc->mChannelMask;
3078 config.format = outputDesc->mFormat;
3079 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3080 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3081 &output,
3082 &config,
3083 &outputDesc->mDevice,
3084 String8(""),
3085 &outputDesc->mLatency,
3086 outputDesc->mFlags);
3087
3088 if (status != NO_ERROR) {
3089 ALOGW("Cannot open output stream for device %08x on hw module %s",
3090 outputDesc->mDevice,
3091 mHwModules[i]->mName);
3092 } else {
3093 outputDesc->mSamplingRate = config.sample_rate;
3094 outputDesc->mChannelMask = config.channel_mask;
3095 outputDesc->mFormat = config.format;
3096
3097 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3098 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3099 ssize_t index =
3100 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3101 // give a valid ID to an attached device once confirmed it is reachable
3102 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3103 mAvailableOutputDevices[index]->mId = nextUniqueId();
3104 mAvailableOutputDevices[index]->mModule = mHwModules[i];
3105 }
3106 }
3107 if (mPrimaryOutput == 0 &&
3108 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3109 mPrimaryOutput = output;
3110 }
3111 addOutput(output, outputDesc);
3112 setOutputDevice(output,
3113 outputDesc->mDevice,
3114 true);
3115 }
Eric Laurente552edb2014-03-10 17:42:56 -07003116 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003117 // open input streams needed to access attached devices to validate
3118 // mAvailableInputDevices list
3119 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3120 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003121 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003122
Eric Laurent3a4311c2014-03-17 12:00:47 -07003123 if (inProfile->mSupportedDevices.isEmpty()) {
3124 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3125 continue;
3126 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003127 // chose first device present in mSupportedDevices also part of
3128 // inputDeviceTypes
3129 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3130 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3131 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3132 if (profileType & inputDeviceTypes) {
3133 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003134 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003135 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003136 if ((profileType & inputDeviceTypes) == 0) {
3137 continue;
3138 }
3139 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3140
3141 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3142 inputDesc->mDevice = profileType;
3143
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003144 // find the address
3145 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3146 // the inputs vector must be of size 1, but we don't want to crash here
3147 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3148 : String8("");
3149 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3150 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3151
Eric Laurentd78f1532014-09-16 16:38:20 -07003152 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3153 config.sample_rate = inputDesc->mSamplingRate;
3154 config.channel_mask = inputDesc->mChannelMask;
3155 config.format = inputDesc->mFormat;
3156 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3157 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3158 &input,
3159 &config,
3160 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003161 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003162 AUDIO_SOURCE_MIC,
3163 AUDIO_INPUT_FLAG_NONE);
3164
3165 if (status == NO_ERROR) {
3166 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3167 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3168 ssize_t index =
3169 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3170 // give a valid ID to an attached device once confirmed it is reachable
3171 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3172 mAvailableInputDevices[index]->mId = nextUniqueId();
3173 mAvailableInputDevices[index]->mModule = mHwModules[i];
3174 }
3175 }
3176 mpClientInterface->closeInput(input);
3177 } else {
3178 ALOGW("Cannot open input stream for device %08x on hw module %s",
3179 inputDesc->mDevice,
3180 mHwModules[i]->mName);
3181 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003182 }
3183 }
3184 // make sure all attached devices have been allocated a unique ID
3185 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3186 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003187 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003188 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3189 continue;
3190 }
3191 i++;
3192 }
3193 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3194 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003195 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003196 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3197 continue;
3198 }
3199 i++;
3200 }
3201 // make sure default device is reachable
3202 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003203 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003204 }
Eric Laurente552edb2014-03-10 17:42:56 -07003205
3206 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3207
3208 updateDevicesAndOutputs();
3209
3210#ifdef AUDIO_POLICY_TEST
3211 if (mPrimaryOutput != 0) {
3212 AudioParameter outputCmd = AudioParameter();
3213 outputCmd.addInt(String8("set_id"), 0);
3214 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3215
3216 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3217 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003218 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3219 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003220 mTestLatencyMs = 0;
3221 mCurOutput = 0;
3222 mDirectOutput = false;
3223 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3224 mTestOutputs[i] = 0;
3225 }
3226
3227 const size_t SIZE = 256;
3228 char buffer[SIZE];
3229 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3230 run(buffer, ANDROID_PRIORITY_AUDIO);
3231 }
3232#endif //AUDIO_POLICY_TEST
3233}
3234
Eric Laurente0720872014-03-11 09:30:41 -07003235AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003236{
3237#ifdef AUDIO_POLICY_TEST
3238 exit();
3239#endif //AUDIO_POLICY_TEST
3240 for (size_t i = 0; i < mOutputs.size(); i++) {
3241 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003242 }
3243 for (size_t i = 0; i < mInputs.size(); i++) {
3244 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003245 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003246 mAvailableOutputDevices.clear();
3247 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003248 mOutputs.clear();
3249 mInputs.clear();
3250 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003251}
3252
Eric Laurente0720872014-03-11 09:30:41 -07003253status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003254{
3255 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3256}
3257
3258#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003259bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003260{
3261 ALOGV("entering threadLoop()");
3262 while (!exitPending())
3263 {
3264 String8 command;
3265 int valueInt;
3266 String8 value;
3267
3268 Mutex::Autolock _l(mLock);
3269 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3270
3271 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3272 AudioParameter param = AudioParameter(command);
3273
3274 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3275 valueInt != 0) {
3276 ALOGV("Test command %s received", command.string());
3277 String8 target;
3278 if (param.get(String8("target"), target) != NO_ERROR) {
3279 target = "Manager";
3280 }
3281 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3282 param.remove(String8("test_cmd_policy_output"));
3283 mCurOutput = valueInt;
3284 }
3285 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3286 param.remove(String8("test_cmd_policy_direct"));
3287 if (value == "false") {
3288 mDirectOutput = false;
3289 } else if (value == "true") {
3290 mDirectOutput = true;
3291 }
3292 }
3293 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3294 param.remove(String8("test_cmd_policy_input"));
3295 mTestInput = valueInt;
3296 }
3297
3298 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3299 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003300 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003301 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003302 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003303 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003304 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003305 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003306 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003307 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003308 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003309 if (target == "Manager") {
3310 mTestFormat = format;
3311 } else if (mTestOutputs[mCurOutput] != 0) {
3312 AudioParameter outputParam = AudioParameter();
3313 outputParam.addInt(String8("format"), format);
3314 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3315 }
3316 }
3317 }
3318 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3319 param.remove(String8("test_cmd_policy_channels"));
3320 int channels = 0;
3321
3322 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003323 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003324 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003325 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003326 }
3327 if (channels != 0) {
3328 if (target == "Manager") {
3329 mTestChannels = channels;
3330 } else if (mTestOutputs[mCurOutput] != 0) {
3331 AudioParameter outputParam = AudioParameter();
3332 outputParam.addInt(String8("channels"), channels);
3333 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3334 }
3335 }
3336 }
3337 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3338 param.remove(String8("test_cmd_policy_sampleRate"));
3339 if (valueInt >= 0 && valueInt <= 96000) {
3340 int samplingRate = valueInt;
3341 if (target == "Manager") {
3342 mTestSamplingRate = samplingRate;
3343 } else if (mTestOutputs[mCurOutput] != 0) {
3344 AudioParameter outputParam = AudioParameter();
3345 outputParam.addInt(String8("sampling_rate"), samplingRate);
3346 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3347 }
3348 }
3349 }
3350
3351 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3352 param.remove(String8("test_cmd_policy_reopen"));
3353
Eric Laurent1f2f2232014-06-02 12:01:23 -07003354 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003355 mpClientInterface->closeOutput(mPrimaryOutput);
3356
3357 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3358
Eric Laurente552edb2014-03-10 17:42:56 -07003359 mOutputs.removeItem(mPrimaryOutput);
3360
Eric Laurent1f2f2232014-06-02 12:01:23 -07003361 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003362 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003363 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3364 config.sample_rate = outputDesc->mSamplingRate;
3365 config.channel_mask = outputDesc->mChannelMask;
3366 config.format = outputDesc->mFormat;
3367 status_t status = mpClientInterface->openOutput(moduleHandle,
3368 &mPrimaryOutput,
3369 &config,
3370 &outputDesc->mDevice,
3371 String8(""),
3372 &outputDesc->mLatency,
3373 outputDesc->mFlags);
3374 if (status != NO_ERROR) {
3375 ALOGE("Failed to reopen hardware output stream, "
3376 "samplingRate: %d, format %d, channels %d",
3377 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003378 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003379 outputDesc->mSamplingRate = config.sample_rate;
3380 outputDesc->mChannelMask = config.channel_mask;
3381 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003382 AudioParameter outputCmd = AudioParameter();
3383 outputCmd.addInt(String8("set_id"), 0);
3384 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3385 addOutput(mPrimaryOutput, outputDesc);
3386 }
3387 }
3388
3389
3390 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3391 }
3392 }
3393 return false;
3394}
3395
Eric Laurente0720872014-03-11 09:30:41 -07003396void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003397{
3398 {
3399 AutoMutex _l(mLock);
3400 requestExit();
3401 mWaitWorkCV.signal();
3402 }
3403 requestExitAndWait();
3404}
3405
Eric Laurente0720872014-03-11 09:30:41 -07003406int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003407{
3408 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3409 if (output == mTestOutputs[i]) return i;
3410 }
3411 return 0;
3412}
3413#endif //AUDIO_POLICY_TEST
3414
3415// ---
3416
Eric Laurent1f2f2232014-06-02 12:01:23 -07003417void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003418{
Eric Laurent1c333e22014-05-20 10:48:17 -07003419 outputDesc->mIoHandle = output;
3420 outputDesc->mId = nextUniqueId();
3421 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003422 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003423}
3424
Eric Laurent1f2f2232014-06-02 12:01:23 -07003425void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003426{
Eric Laurent1c333e22014-05-20 10:48:17 -07003427 inputDesc->mIoHandle = input;
3428 inputDesc->mId = nextUniqueId();
3429 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003430 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003431}
Eric Laurente552edb2014-03-10 17:42:56 -07003432
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003433void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3434 const String8 address /*in*/,
3435 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3436 // look for a match on the given address on the addresses of the outputs:
3437 // find the address by finding the patch that maps to this output
3438 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3439 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3440 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3441 if (patchIdx >= 0) {
3442 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3443 const int numSinks = patchDesc->mPatch.num_sinks;
3444 for (ssize_t j=0; j < numSinks; j++) {
3445 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3446 const char* patchAddr =
3447 patchDesc->mPatch.sinks[j].ext.device.address;
3448 if (strncmp(patchAddr,
3449 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003450 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003451 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3452 outputs.add(desc->mIoHandle);
3453 break;
3454 }
3455 }
3456 }
3457 }
3458}
3459
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003460status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003461 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003462 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003463 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003464{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003465 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003466 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003467 // erase all current sample rates, formats and channel masks
3468 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003469
Eric Laurent3b73df72014-03-11 09:06:29 -07003470 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003471 // first list already open outputs that can be routed to this device
3472 for (size_t i = 0; i < mOutputs.size(); i++) {
3473 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003474 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003475 if (!deviceDistinguishesOnAddress(device)) {
3476 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3477 outputs.add(mOutputs.keyAt(i));
3478 } else {
3479 ALOGV(" checking address match due to device 0x%x", device);
3480 findIoHandlesByAddress(desc, address, outputs);
3481 }
Eric Laurente552edb2014-03-10 17:42:56 -07003482 }
3483 }
3484 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003485 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003486 for (size_t i = 0; i < mHwModules.size(); i++)
3487 {
3488 if (mHwModules[i]->mHandle == 0) {
3489 continue;
3490 }
3491 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3492 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003493 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3494 if (profile->mSupportedDevices.types() & device) {
3495 if (!deviceDistinguishesOnAddress(device) ||
3496 address == profile->mSupportedDevices[0]->mAddress) {
3497 profiles.add(profile);
3498 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3499 }
Eric Laurente552edb2014-03-10 17:42:56 -07003500 }
3501 }
3502 }
3503
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003504 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3505
Eric Laurente552edb2014-03-10 17:42:56 -07003506 if (profiles.isEmpty() && outputs.isEmpty()) {
3507 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3508 return BAD_VALUE;
3509 }
3510
3511 // open outputs for matching profiles if needed. Direct outputs are also opened to
3512 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3513 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003514 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003515
3516 // nothing to do if one output is already opened for this profile
3517 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003518 for (j = 0; j < outputs.size(); j++) {
3519 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003520 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003521 // matching profile: save the sample rates, format and channel masks supported
3522 // by the profile in our device descriptor
3523 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003524 break;
3525 }
3526 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003527 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003528 continue;
3529 }
3530
Eric Laurent83b88082014-06-20 18:31:16 -07003531 ALOGV("opening output for device %08x with params %s profile %p",
3532 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003533 desc = new AudioOutputDescriptor(profile);
3534 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003535 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3536 config.sample_rate = desc->mSamplingRate;
3537 config.channel_mask = desc->mChannelMask;
3538 config.format = desc->mFormat;
3539 config.offload_info.sample_rate = desc->mSamplingRate;
3540 config.offload_info.channel_mask = desc->mChannelMask;
3541 config.offload_info.format = desc->mFormat;
3542 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3543 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3544 &output,
3545 &config,
3546 &desc->mDevice,
3547 address,
3548 &desc->mLatency,
3549 desc->mFlags);
3550 if (status == NO_ERROR) {
3551 desc->mSamplingRate = config.sample_rate;
3552 desc->mChannelMask = config.channel_mask;
3553 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003554
Eric Laurentd4692962014-05-05 18:13:44 -07003555 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003556 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003557 char *param = audio_device_address_to_parameter(device, address);
3558 mpClientInterface->setParameters(output, String8(param));
3559 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003560 }
3561
Eric Laurentd4692962014-05-05 18:13:44 -07003562 // Here is where we step through and resolve any "dynamic" fields
3563 String8 reply;
3564 char *value;
3565 if (profile->mSamplingRates[0] == 0) {
3566 reply = mpClientInterface->getParameters(output,
3567 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003568 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003569 reply.string());
3570 value = strpbrk((char *)reply.string(), "=");
3571 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003572 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003573 }
Eric Laurentd4692962014-05-05 18:13:44 -07003574 }
3575 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3576 reply = mpClientInterface->getParameters(output,
3577 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003578 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003579 reply.string());
3580 value = strpbrk((char *)reply.string(), "=");
3581 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003582 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003583 }
Eric Laurentd4692962014-05-05 18:13:44 -07003584 }
3585 if (profile->mChannelMasks[0] == 0) {
3586 reply = mpClientInterface->getParameters(output,
3587 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003588 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003589 reply.string());
3590 value = strpbrk((char *)reply.string(), "=");
3591 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003592 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003593 }
Eric Laurentd4692962014-05-05 18:13:44 -07003594 }
3595 if (((profile->mSamplingRates[0] == 0) &&
3596 (profile->mSamplingRates.size() < 2)) ||
3597 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3598 (profile->mFormats.size() < 2)) ||
3599 ((profile->mChannelMasks[0] == 0) &&
3600 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003601 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003602 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003603 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003604 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3605 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003606 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003607 config.sample_rate = profile->pickSamplingRate();
3608 config.channel_mask = profile->pickChannelMask();
3609 config.format = profile->pickFormat();
3610 config.offload_info.sample_rate = config.sample_rate;
3611 config.offload_info.channel_mask = config.channel_mask;
3612 config.offload_info.format = config.format;
3613 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3614 &output,
3615 &config,
3616 &desc->mDevice,
3617 address,
3618 &desc->mLatency,
3619 desc->mFlags);
3620 if (status == NO_ERROR) {
3621 desc->mSamplingRate = config.sample_rate;
3622 desc->mChannelMask = config.channel_mask;
3623 desc->mFormat = config.format;
3624 } else {
3625 output = AUDIO_IO_HANDLE_NONE;
3626 }
Eric Laurentd4692962014-05-05 18:13:44 -07003627 }
3628
Eric Laurentcf2c0212014-07-25 16:20:43 -07003629 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003630 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003631 if (deviceDistinguishesOnAddress(device) && address != "0") {
3632 ssize_t index = mPolicyMixes.indexOfKey(address);
3633 if (index >= 0) {
3634 mPolicyMixes[index]->mOutput = desc;
Eric Laurentc722f302014-12-10 11:21:49 -08003635 desc->mPolicyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08003636 } else {
3637 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3638 address.string());
3639 }
Eric Laurentc722f302014-12-10 11:21:49 -08003640 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3641 // no duplicated output for direct outputs and
3642 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003643 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003644
Eric Laurentd4692962014-05-05 18:13:44 -07003645 // set initial stream volume for device
3646 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003647
Eric Laurentd4692962014-05-05 18:13:44 -07003648 //TODO: configure audio effect output stage here
3649
3650 // open a duplicating output thread for the new output and the primary output
3651 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3652 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003653 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003654 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003655 sp<AudioOutputDescriptor> dupOutputDesc =
3656 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003657 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3658 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3659 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3660 dupOutputDesc->mFormat = desc->mFormat;
3661 dupOutputDesc->mChannelMask = desc->mChannelMask;
3662 dupOutputDesc->mLatency = desc->mLatency;
3663 addOutput(duplicatedOutput, dupOutputDesc);
3664 applyStreamVolumes(duplicatedOutput, device, 0, true);
3665 } else {
3666 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3667 mPrimaryOutput, output);
3668 mpClientInterface->closeOutput(output);
3669 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003670 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003671 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003672 }
Eric Laurente552edb2014-03-10 17:42:56 -07003673 }
3674 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003675 } else {
3676 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003677 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003678 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003679 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003680 profiles.removeAt(profile_index);
3681 profile_index--;
3682 } else {
3683 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003684 devDesc->importAudioPort(profile);
3685
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003686 if (deviceDistinguishesOnAddress(device)) {
3687 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3688 device, address.string());
3689 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3690 NULL/*patch handle*/, address.string());
3691 }
Eric Laurente552edb2014-03-10 17:42:56 -07003692 ALOGV("checkOutputsForDevice(): adding output %d", output);
3693 }
3694 }
3695
3696 if (profiles.isEmpty()) {
3697 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3698 return BAD_VALUE;
3699 }
Eric Laurentd4692962014-05-05 18:13:44 -07003700 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003701 // check if one opened output is not needed any more after disconnecting one device
3702 for (size_t i = 0; i < mOutputs.size(); i++) {
3703 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003704 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003705 // exact match on device
3706 if (deviceDistinguishesOnAddress(device) &&
3707 (desc->mProfile->mSupportedDevices.types() == device)) {
3708 findIoHandlesByAddress(desc, address, outputs);
3709 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003710 & mAvailableOutputDevices.types())) {
3711 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3712 mOutputs.keyAt(i));
3713 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003714 }
Eric Laurente552edb2014-03-10 17:42:56 -07003715 }
3716 }
Eric Laurentd4692962014-05-05 18:13:44 -07003717 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003718 for (size_t i = 0; i < mHwModules.size(); i++)
3719 {
3720 if (mHwModules[i]->mHandle == 0) {
3721 continue;
3722 }
3723 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3724 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003725 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003726 if (profile->mSupportedDevices.types() & device) {
3727 ALOGV("checkOutputsForDevice(): "
3728 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003729 if (profile->mSamplingRates[0] == 0) {
3730 profile->mSamplingRates.clear();
3731 profile->mSamplingRates.add(0);
3732 }
3733 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3734 profile->mFormats.clear();
3735 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3736 }
3737 if (profile->mChannelMasks[0] == 0) {
3738 profile->mChannelMasks.clear();
3739 profile->mChannelMasks.add(0);
3740 }
3741 }
3742 }
3743 }
3744 }
3745 return NO_ERROR;
3746}
3747
Eric Laurentd4692962014-05-05 18:13:44 -07003748status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3749 audio_policy_dev_state_t state,
3750 SortedVector<audio_io_handle_t>& inputs,
3751 const String8 address)
3752{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003753 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003754 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3755 // first list already open inputs that can be routed to this device
3756 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3757 desc = mInputs.valueAt(input_index);
3758 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3759 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3760 inputs.add(mInputs.keyAt(input_index));
3761 }
3762 }
3763
3764 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003765 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003766 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3767 {
3768 if (mHwModules[module_idx]->mHandle == 0) {
3769 continue;
3770 }
3771 for (size_t profile_index = 0;
3772 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3773 profile_index++)
3774 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003775 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3776
3777 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3778 if (!deviceDistinguishesOnAddress(device) ||
3779 address == profile->mSupportedDevices[0]->mAddress) {
3780 profiles.add(profile);
3781 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3782 profile_index, module_idx);
3783 }
Eric Laurentd4692962014-05-05 18:13:44 -07003784 }
3785 }
3786 }
3787
3788 if (profiles.isEmpty() && inputs.isEmpty()) {
3789 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3790 return BAD_VALUE;
3791 }
3792
3793 // open inputs for matching profiles if needed. Direct inputs are also opened to
3794 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3795 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3796
Eric Laurent1c333e22014-05-20 10:48:17 -07003797 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003798 // nothing to do if one input is already opened for this profile
3799 size_t input_index;
3800 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3801 desc = mInputs.valueAt(input_index);
3802 if (desc->mProfile == profile) {
3803 break;
3804 }
3805 }
3806 if (input_index != mInputs.size()) {
3807 continue;
3808 }
3809
3810 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3811 desc = new AudioInputDescriptor(profile);
3812 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003813 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3814 config.sample_rate = desc->mSamplingRate;
3815 config.channel_mask = desc->mChannelMask;
3816 config.format = desc->mFormat;
3817 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3818 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3819 &input,
3820 &config,
3821 &desc->mDevice,
3822 address,
3823 AUDIO_SOURCE_MIC,
3824 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003825
Eric Laurentcf2c0212014-07-25 16:20:43 -07003826 if (status == NO_ERROR) {
3827 desc->mSamplingRate = config.sample_rate;
3828 desc->mChannelMask = config.channel_mask;
3829 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003830
Eric Laurentd4692962014-05-05 18:13:44 -07003831 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003832 char *param = audio_device_address_to_parameter(device, address);
3833 mpClientInterface->setParameters(input, String8(param));
3834 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003835 }
3836
3837 // Here is where we step through and resolve any "dynamic" fields
3838 String8 reply;
3839 char *value;
3840 if (profile->mSamplingRates[0] == 0) {
3841 reply = mpClientInterface->getParameters(input,
3842 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3843 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3844 reply.string());
3845 value = strpbrk((char *)reply.string(), "=");
3846 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003847 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003848 }
3849 }
3850 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3851 reply = mpClientInterface->getParameters(input,
3852 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3853 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3854 value = strpbrk((char *)reply.string(), "=");
3855 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003856 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003857 }
3858 }
3859 if (profile->mChannelMasks[0] == 0) {
3860 reply = mpClientInterface->getParameters(input,
3861 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3862 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3863 reply.string());
3864 value = strpbrk((char *)reply.string(), "=");
3865 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003866 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003867 }
3868 }
3869 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3870 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3871 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3872 ALOGW("checkInputsForDevice() direct input missing param");
3873 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003874 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003875 }
3876
3877 if (input != 0) {
3878 addInput(input, desc);
3879 }
3880 } // endif input != 0
3881
Eric Laurentcf2c0212014-07-25 16:20:43 -07003882 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003883 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003884 profiles.removeAt(profile_index);
3885 profile_index--;
3886 } else {
3887 inputs.add(input);
3888 ALOGV("checkInputsForDevice(): adding input %d", input);
3889 }
3890 } // end scan profiles
3891
3892 if (profiles.isEmpty()) {
3893 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3894 return BAD_VALUE;
3895 }
3896 } else {
3897 // Disconnect
3898 // check if one opened input is not needed any more after disconnecting one device
3899 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3900 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003901 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3902 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003903 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3904 mInputs.keyAt(input_index));
3905 inputs.add(mInputs.keyAt(input_index));
3906 }
3907 }
3908 // Clear any profiles associated with the disconnected device.
3909 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3910 if (mHwModules[module_index]->mHandle == 0) {
3911 continue;
3912 }
3913 for (size_t profile_index = 0;
3914 profile_index < mHwModules[module_index]->mInputProfiles.size();
3915 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003916 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003917 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003918 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003919 profile_index, module_index);
3920 if (profile->mSamplingRates[0] == 0) {
3921 profile->mSamplingRates.clear();
3922 profile->mSamplingRates.add(0);
3923 }
3924 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3925 profile->mFormats.clear();
3926 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3927 }
3928 if (profile->mChannelMasks[0] == 0) {
3929 profile->mChannelMasks.clear();
3930 profile->mChannelMasks.add(0);
3931 }
3932 }
3933 }
3934 }
3935 } // end disconnect
3936
3937 return NO_ERROR;
3938}
3939
3940
Eric Laurente0720872014-03-11 09:30:41 -07003941void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003942{
3943 ALOGV("closeOutput(%d)", output);
3944
Eric Laurent1f2f2232014-06-02 12:01:23 -07003945 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003946 if (outputDesc == NULL) {
3947 ALOGW("closeOutput() unknown output %d", output);
3948 return;
3949 }
3950
Eric Laurent275e8e92014-11-30 15:14:47 -08003951 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3952 if (mPolicyMixes[i]->mOutput == outputDesc) {
3953 mPolicyMixes[i]->mOutput.clear();
3954 }
3955 }
3956
Eric Laurente552edb2014-03-10 17:42:56 -07003957 // look for duplicated outputs connected to the output being removed.
3958 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003959 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003960 if (dupOutputDesc->isDuplicated() &&
3961 (dupOutputDesc->mOutput1 == outputDesc ||
3962 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003963 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003964 if (dupOutputDesc->mOutput1 == outputDesc) {
3965 outputDesc2 = dupOutputDesc->mOutput2;
3966 } else {
3967 outputDesc2 = dupOutputDesc->mOutput1;
3968 }
3969 // As all active tracks on duplicated output will be deleted,
3970 // and as they were also referenced on the other output, the reference
3971 // count for their stream type must be adjusted accordingly on
3972 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003973 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003974 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003975 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003976 }
3977 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3978 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3979
3980 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003981 mOutputs.removeItem(duplicatedOutput);
3982 }
3983 }
3984
Eric Laurent05b90f82014-08-27 15:32:29 -07003985 nextAudioPortGeneration();
3986
3987 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3988 if (index >= 0) {
3989 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3990 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3991 mAudioPatches.removeItemsAt(index);
3992 mpClientInterface->onAudioPatchListUpdate();
3993 }
3994
Eric Laurente552edb2014-03-10 17:42:56 -07003995 AudioParameter param;
3996 param.add(String8("closing"), String8("true"));
3997 mpClientInterface->setParameters(output, param.toString());
3998
3999 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004000 mOutputs.removeItem(output);
4001 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004002}
4003
4004void AudioPolicyManager::closeInput(audio_io_handle_t input)
4005{
4006 ALOGV("closeInput(%d)", input);
4007
4008 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4009 if (inputDesc == NULL) {
4010 ALOGW("closeInput() unknown input %d", input);
4011 return;
4012 }
4013
Eric Laurent6a94d692014-05-20 11:18:06 -07004014 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004015
4016 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4017 if (index >= 0) {
4018 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4019 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4020 mAudioPatches.removeItemsAt(index);
4021 mpClientInterface->onAudioPatchListUpdate();
4022 }
4023
4024 mpClientInterface->closeInput(input);
4025 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004026}
4027
Eric Laurente0720872014-03-11 09:30:41 -07004028SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07004029 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004030{
4031 SortedVector<audio_io_handle_t> outputs;
4032
4033 ALOGVV("getOutputsForDevice() device %04x", device);
4034 for (size_t i = 0; i < openOutputs.size(); i++) {
4035 ALOGVV("output %d isDuplicated=%d device=%04x",
4036 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4037 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4038 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4039 outputs.add(openOutputs.keyAt(i));
4040 }
4041 }
4042 return outputs;
4043}
4044
Eric Laurente0720872014-03-11 09:30:41 -07004045bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07004046 SortedVector<audio_io_handle_t>& outputs2)
4047{
4048 if (outputs1.size() != outputs2.size()) {
4049 return false;
4050 }
4051 for (size_t i = 0; i < outputs1.size(); i++) {
4052 if (outputs1[i] != outputs2[i]) {
4053 return false;
4054 }
4055 }
4056 return true;
4057}
4058
Eric Laurente0720872014-03-11 09:30:41 -07004059void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004060{
4061 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4062 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4063 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4064 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4065
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004066 // also take into account external policy-related changes: add all outputs which are
4067 // associated with policies in the "before" and "after" output vectors
4068 ALOGVV("checkOutputForStrategy(): policy related outputs");
4069 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
4070 const sp<AudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
4071 if (desc != 0 && desc->mPolicyMix != NULL) {
4072 srcOutputs.add(desc->mIoHandle);
4073 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4074 }
4075 }
4076 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
4077 const sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4078 if (desc != 0 && desc->mPolicyMix != NULL) {
4079 dstOutputs.add(desc->mIoHandle);
4080 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4081 }
4082 }
4083
Eric Laurente552edb2014-03-10 17:42:56 -07004084 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4085 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4086 strategy, srcOutputs[0], dstOutputs[0]);
4087 // mute strategy while moving tracks from one output to another
4088 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004089 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004090 if (desc->isStrategyActive(strategy)) {
4091 setStrategyMute(strategy, true, srcOutputs[i]);
4092 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4093 }
4094 }
4095
4096 // Move effects associated to this strategy from previous output to new output
4097 if (strategy == STRATEGY_MEDIA) {
4098 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4099 SortedVector<audio_io_handle_t> moved;
4100 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004101 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4102 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4103 effectDesc->mIo != fxOutput) {
4104 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004105 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4106 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004107 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004108 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004109 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004110 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004111 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004112 }
4113 }
4114 }
4115 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004116 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004117 if (i == AUDIO_STREAM_PATCH) {
4118 continue;
4119 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004120 if (getStrategy((audio_stream_type_t)i) == strategy) {
4121 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004122 }
4123 }
4124 }
4125}
4126
Eric Laurente0720872014-03-11 09:30:41 -07004127void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004128{
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_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004132 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4133 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004134 checkOutputForStrategy(STRATEGY_SONIFICATION);
4135 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004136 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004137 checkOutputForStrategy(STRATEGY_MEDIA);
4138 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004139 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004140}
4141
Eric Laurente0720872014-03-11 09:30:41 -07004142audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004143{
Eric Laurente552edb2014-03-10 17:42:56 -07004144 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004145 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004146 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4147 return mOutputs.keyAt(i);
4148 }
4149 }
4150
4151 return 0;
4152}
4153
Eric Laurente0720872014-03-11 09:30:41 -07004154void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004155{
Eric Laurente552edb2014-03-10 17:42:56 -07004156 audio_io_handle_t a2dpOutput = getA2dpOutput();
4157 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004158 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004159 return;
4160 }
4161
Eric Laurent3a4311c2014-03-17 12:00:47 -07004162 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004163 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4164 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4165 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004166 // suspend A2DP output if:
4167 // (NOT already suspended) &&
4168 // ((SCO device is connected &&
4169 // (forced usage for communication || for record is SCO))) ||
4170 // (phone state is ringing || in call)
4171 //
4172 // restore A2DP output if:
4173 // (Already suspended) &&
4174 // ((SCO device is NOT connected ||
4175 // (forced usage NOT for communication && NOT for record is SCO))) &&
4176 // (phone state is NOT ringing && NOT in call)
4177 //
4178 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004179 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004180 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4181 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4182 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4183 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004184
4185 mpClientInterface->restoreOutput(a2dpOutput);
4186 mA2dpSuspended = false;
4187 }
4188 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004189 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004190 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4191 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4192 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4193 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004194
4195 mpClientInterface->suspendOutput(a2dpOutput);
4196 mA2dpSuspended = true;
4197 }
4198 }
4199}
4200
Eric Laurent1c333e22014-05-20 10:48:17 -07004201audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004202{
4203 audio_devices_t device = AUDIO_DEVICE_NONE;
4204
Eric Laurent1f2f2232014-06-02 12:01:23 -07004205 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004206
4207 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4208 if (index >= 0) {
4209 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4210 if (patchDesc->mUid != mUidCached) {
4211 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4212 outputDesc->device(), outputDesc->mPatchHandle);
4213 return outputDesc->device();
4214 }
4215 }
4216
Eric Laurente552edb2014-03-10 17:42:56 -07004217 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004218 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004219 // use device for strategy enforced audible
4220 // 2: we are in call or the strategy phone is active on the output:
4221 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004222 // 3: the strategy for enforced audible is active but not enforced on the output:
4223 // use the device for strategy enforced audible
4224 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004225 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004226 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004227 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004228 // 6: the strategy accessibility is active on the output:
4229 // use device for strategy accessibility
4230 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004231 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004232 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004233 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004234 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004235 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004236 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4237 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004238 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4239 } else if (isInCall() ||
4240 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4241 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004242 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4243 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004244 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4245 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4246 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4247 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004248 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4249 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004250 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4251 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4252 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4253 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004254 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4255 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004256 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4257 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004258 }
4259
Eric Laurent1c333e22014-05-20 10:48:17 -07004260 ALOGV("getNewOutputDevice() selected device %x", device);
4261 return device;
4262}
4263
4264audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4265{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004266 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004267
4268 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4269 if (index >= 0) {
4270 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4271 if (patchDesc->mUid != mUidCached) {
4272 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4273 inputDesc->mDevice, inputDesc->mPatchHandle);
4274 return inputDesc->mDevice;
4275 }
4276 }
4277
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004278 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07004279
4280 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004281 return device;
4282}
4283
Eric Laurente0720872014-03-11 09:30:41 -07004284uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004285 return (uint32_t)getStrategy(stream);
4286}
4287
Eric Laurente0720872014-03-11 09:30:41 -07004288audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004289 // By checking the range of stream before calling getStrategy, we avoid
4290 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4291 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004292 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004293 return AUDIO_DEVICE_NONE;
4294 }
4295 audio_devices_t devices;
4296 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4297 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4298 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4299 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004300 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004301 if (outputDesc->isStrategyActive(strategy)) {
4302 devices = outputDesc->device();
4303 break;
4304 }
Eric Laurente552edb2014-03-10 17:42:56 -07004305 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004306
4307 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4308 and doesn't really need to.*/
4309 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4310 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4311 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4312 }
4313
Eric Laurente552edb2014-03-10 17:42:56 -07004314 return devices;
4315}
4316
Eric Laurente0720872014-03-11 09:30:41 -07004317AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004318 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004319
4320 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4321
Eric Laurente552edb2014-03-10 17:42:56 -07004322 // stream to strategy mapping
4323 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004324 case AUDIO_STREAM_VOICE_CALL:
4325 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004326 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004327 case AUDIO_STREAM_RING:
4328 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004329 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004330 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004331 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004332 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004333 return STRATEGY_DTMF;
4334 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004335 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004336 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004337 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4338 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004339 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004340 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004341 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004342 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004343 case AUDIO_STREAM_TTS:
4344 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004345 case AUDIO_STREAM_ACCESSIBILITY:
4346 return STRATEGY_ACCESSIBILITY;
4347 case AUDIO_STREAM_REROUTING:
4348 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004349 }
4350}
4351
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004352uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4353 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004354 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4355 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4356 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004357 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4358 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4359 }
4360
4361 // usage to strategy mapping
4362 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004363 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4364 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4365 return (uint32_t) STRATEGY_SONIFICATION;
4366 }
4367 if (isInCall()) {
4368 return (uint32_t) STRATEGY_PHONE;
4369 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004370 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004371
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004372 case AUDIO_USAGE_MEDIA:
4373 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004374 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4375 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4376 return (uint32_t) STRATEGY_MEDIA;
4377
4378 case AUDIO_USAGE_VOICE_COMMUNICATION:
4379 return (uint32_t) STRATEGY_PHONE;
4380
4381 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4382 return (uint32_t) STRATEGY_DTMF;
4383
4384 case AUDIO_USAGE_ALARM:
4385 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4386 return (uint32_t) STRATEGY_SONIFICATION;
4387
4388 case AUDIO_USAGE_NOTIFICATION:
4389 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4390 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4391 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4392 case AUDIO_USAGE_NOTIFICATION_EVENT:
4393 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4394
4395 case AUDIO_USAGE_UNKNOWN:
4396 default:
4397 return (uint32_t) STRATEGY_MEDIA;
4398 }
4399}
4400
Eric Laurente0720872014-03-11 09:30:41 -07004401void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004402 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004403 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004404 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4405 updateDevicesAndOutputs();
4406 break;
4407 default:
4408 break;
4409 }
4410}
4411
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004412bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4413 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4414 if (s == (size_t) streamToIgnore) {
4415 continue;
4416 }
4417 for (size_t i = 0; i < mOutputs.size(); i++) {
4418 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4419 if (outputDesc->mRefCount[s] != 0) {
4420 return true;
4421 }
4422 }
4423 }
4424 return false;
4425}
4426
4427uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4428 switch(event) {
4429 case STARTING_OUTPUT:
4430 mBeaconMuteRefCount++;
4431 break;
4432 case STOPPING_OUTPUT:
4433 if (mBeaconMuteRefCount > 0) {
4434 mBeaconMuteRefCount--;
4435 }
4436 break;
4437 case STARTING_BEACON:
4438 mBeaconPlayingRefCount++;
4439 break;
4440 case STOPPING_BEACON:
4441 if (mBeaconPlayingRefCount > 0) {
4442 mBeaconPlayingRefCount--;
4443 }
4444 break;
4445 }
4446
4447 if (mBeaconMuteRefCount > 0) {
4448 // any playback causes beacon to be muted
4449 return setBeaconMute(true);
4450 } else {
4451 // no other playback: unmute when beacon starts playing, mute when it stops
4452 return setBeaconMute(mBeaconPlayingRefCount == 0);
4453 }
4454}
4455
4456uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4457 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4458 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4459 // keep track of muted state to avoid repeating mute/unmute operations
4460 if (mBeaconMuted != mute) {
4461 // mute/unmute AUDIO_STREAM_TTS on all outputs
4462 ALOGV("\t muting %d", mute);
4463 uint32_t maxLatency = 0;
4464 for (size_t i = 0; i < mOutputs.size(); i++) {
4465 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4466 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4467 desc->mIoHandle,
4468 0 /*delay*/, AUDIO_DEVICE_NONE);
4469 const uint32_t latency = desc->latency() * 2;
4470 if (latency > maxLatency) {
4471 maxLatency = latency;
4472 }
4473 }
4474 mBeaconMuted = mute;
4475 return maxLatency;
4476 }
4477 return 0;
4478}
4479
Eric Laurente0720872014-03-11 09:30:41 -07004480audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004481 bool fromCache)
4482{
4483 uint32_t device = AUDIO_DEVICE_NONE;
4484
4485 if (fromCache) {
4486 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4487 strategy, mDeviceForStrategy[strategy]);
4488 return mDeviceForStrategy[strategy];
4489 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004490 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004491 switch (strategy) {
4492
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004493 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4494 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4495 if (!device) {
4496 ALOGE("getDeviceForStrategy() no device found for "\
4497 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4498 }
4499 break;
4500
Eric Laurente552edb2014-03-10 17:42:56 -07004501 case STRATEGY_SONIFICATION_RESPECTFUL:
4502 if (isInCall()) {
4503 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004504 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004505 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4506 // while media is playing on a remote device, use the the sonification behavior.
4507 // Note that we test this usecase before testing if media is playing because
4508 // the isStreamActive() method only informs about the activity of a stream, not
4509 // if it's for local playback. Note also that we use the same delay between both tests
4510 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004511 //user "safe" speaker if available instead of normal speaker to avoid triggering
4512 //other acoustic safety mechanisms for notification
4513 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4514 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004515 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004516 // while media is playing (or has recently played), use the same device
4517 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4518 } else {
4519 // when media is not playing anymore, fall back on the sonification behavior
4520 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004521 //user "safe" speaker if available instead of normal speaker to avoid triggering
4522 //other acoustic safety mechanisms for notification
4523 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4524 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004525 }
4526
4527 break;
4528
4529 case STRATEGY_DTMF:
4530 if (!isInCall()) {
4531 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4532 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4533 break;
4534 }
4535 // when in call, DTMF and PHONE strategies follow the same rules
4536 // FALL THROUGH
4537
4538 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004539 // Force use of only devices on primary output if:
4540 // - in call AND
4541 // - cannot route from voice call RX OR
4542 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4543 if (mPhoneState == AUDIO_MODE_IN_CALL) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004544 audio_devices_t txDevice =
4545 getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -07004546 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4547 if (((mAvailableInputDevices.types() &
4548 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4549 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004550 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004551 AUDIO_DEVICE_API_VERSION_3_0))) {
4552 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4553 }
4554 }
Eric Laurente552edb2014-03-10 17:42:56 -07004555 // for phone strategy, we first consider the forced use and then the available devices by order
4556 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004557 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4558 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004559 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004560 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004561 if (device) break;
4562 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004563 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004564 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004565 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004566 if (device) break;
4567 // if SCO device is requested but no SCO device is available, fall back to default case
4568 // FALL THROUGH
4569
4570 default: // FORCE_NONE
4571 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004572 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004573 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004574 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004575 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004576 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004577 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004578 if (device) break;
4579 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004580 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004581 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004582 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004583 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004584 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4585 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004586 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004587 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004588 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004589 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004590 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004591 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004592 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004593 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004594 if (device) break;
4595 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004596 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004597 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004598 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004599 if (device == AUDIO_DEVICE_NONE) {
4600 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4601 }
4602 break;
4603
Eric Laurent3b73df72014-03-11 09:06:29 -07004604 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004605 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4606 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004607 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004608 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004609 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004610 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004611 if (device) break;
4612 }
Eric Laurentcd71a692014-12-16 12:01:12 -08004613 if (!isInCall()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004614 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004615 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004616 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004617 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004618 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004619 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004620 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004621 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004622 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004623 if (device) break;
4624 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004625 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4626 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004627 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004628 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004629 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004630 if (device == AUDIO_DEVICE_NONE) {
4631 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4632 }
4633 break;
4634 }
4635 break;
4636
4637 case STRATEGY_SONIFICATION:
4638
4639 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4640 // handleIncallSonification().
4641 if (isInCall()) {
4642 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4643 break;
4644 }
4645 // FALL THROUGH
4646
4647 case STRATEGY_ENFORCED_AUDIBLE:
4648 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4649 // except:
4650 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4651 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4652
4653 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004654 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004655 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004656 if (device == AUDIO_DEVICE_NONE) {
4657 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4658 }
4659 }
4660 // The second device used for sonification is the same as the device used by media strategy
4661 // FALL THROUGH
4662
Eric Laurent223fd5c2014-11-11 13:43:36 -08004663 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4664 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004665 if (strategy == STRATEGY_ACCESSIBILITY) {
4666 // do not route accessibility prompts to a digital output currently configured with a
4667 // compressed format as they would likely not be mixed and dropped.
4668 for (size_t i = 0; i < mOutputs.size(); i++) {
4669 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4670 audio_devices_t devices = desc->device() &
4671 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4672 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4673 devices != AUDIO_DEVICE_NONE) {
4674 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4675 }
4676 }
4677 }
4678 // FALL THROUGH
4679
Eric Laurent223fd5c2014-11-11 13:43:36 -08004680 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004681 case STRATEGY_MEDIA: {
4682 uint32_t device2 = AUDIO_DEVICE_NONE;
4683 if (strategy != STRATEGY_SONIFICATION) {
4684 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004685 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4686 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4687 }
Eric Laurente552edb2014-03-10 17:42:56 -07004688 }
4689 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004690 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004691 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004692 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004693 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004694 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004695 }
4696 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004697 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004698 }
4699 }
Hochi Huang327cb702014-09-21 09:47:31 +08004700 if ((device2 == AUDIO_DEVICE_NONE) &&
4701 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4702 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4703 }
Eric Laurente552edb2014-03-10 17:42:56 -07004704 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004705 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004706 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004707 if ((device2 == AUDIO_DEVICE_NONE)) {
4708 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4709 }
Eric Laurente552edb2014-03-10 17:42:56 -07004710 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004711 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
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_ACCESSORY;
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_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004718 }
4719 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004720 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004721 }
4722 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4723 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004724 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004725 }
4726 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004727 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004728 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004729 }
4730 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004731 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004732 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004733 int device3 = AUDIO_DEVICE_NONE;
4734 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004735 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004736 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4737 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004738 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004739 }
Eric Laurente552edb2014-03-10 17:42:56 -07004740
Jungshik Jang839e4f32014-06-26 17:23:40 +09004741 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004742 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4743 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4744 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004745
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004746 // If hdmi system audio mode is on, remove speaker out of output list.
4747 if ((strategy == STRATEGY_MEDIA) &&
4748 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4749 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4750 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4751 }
4752
Eric Laurente552edb2014-03-10 17:42:56 -07004753 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004754 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004755 if (device == AUDIO_DEVICE_NONE) {
4756 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4757 }
4758 } break;
4759
4760 default:
4761 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4762 break;
4763 }
4764
4765 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4766 return device;
4767}
4768
Eric Laurente0720872014-03-11 09:30:41 -07004769void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004770{
4771 for (int i = 0; i < NUM_STRATEGIES; i++) {
4772 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4773 }
4774 mPreviousOutputs = mOutputs;
4775}
4776
Eric Laurent1f2f2232014-06-02 12:01:23 -07004777uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004778 audio_devices_t prevDevice,
4779 uint32_t delayMs)
4780{
4781 // mute/unmute strategies using an incompatible device combination
4782 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4783 // if unmuting, unmute only after the specified delay
4784 if (outputDesc->isDuplicated()) {
4785 return 0;
4786 }
4787
4788 uint32_t muteWaitMs = 0;
4789 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004790 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004791
4792 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4793 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004794 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004795 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4796 bool doMute = false;
4797
4798 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4799 doMute = true;
4800 outputDesc->mStrategyMutedByDevice[i] = true;
4801 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4802 doMute = true;
4803 outputDesc->mStrategyMutedByDevice[i] = false;
4804 }
Eric Laurent99401132014-05-07 19:48:15 -07004805 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004806 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004807 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004808 // skip output if it does not share any device with current output
4809 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4810 == AUDIO_DEVICE_NONE) {
4811 continue;
4812 }
4813 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4814 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4815 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4816 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4817 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004818 if (mute) {
4819 // FIXME: should not need to double latency if volume could be applied
4820 // immediately by the audioflinger mixer. We must account for the delay
4821 // between now and the next time the audioflinger thread for this output
4822 // will process a buffer (which corresponds to one buffer size,
4823 // usually 1/2 or 1/4 of the latency).
4824 if (muteWaitMs < desc->latency() * 2) {
4825 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004826 }
4827 }
4828 }
4829 }
4830 }
4831 }
4832
Eric Laurent99401132014-05-07 19:48:15 -07004833 // temporary mute output if device selection changes to avoid volume bursts due to
4834 // different per device volumes
4835 if (outputDesc->isActive() && (device != prevDevice)) {
4836 if (muteWaitMs < outputDesc->latency() * 2) {
4837 muteWaitMs = outputDesc->latency() * 2;
4838 }
4839 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4840 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004841 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004842 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004843 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004844 muteWaitMs *2, device);
4845 }
4846 }
4847 }
4848
Eric Laurente552edb2014-03-10 17:42:56 -07004849 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4850 if (muteWaitMs > delayMs) {
4851 muteWaitMs -= delayMs;
4852 usleep(muteWaitMs * 1000);
4853 return muteWaitMs;
4854 }
4855 return 0;
4856}
4857
Eric Laurente0720872014-03-11 09:30:41 -07004858uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004859 audio_devices_t device,
4860 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004861 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004862 audio_patch_handle_t *patchHandle,
4863 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004864{
4865 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004866 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004867 AudioParameter param;
4868 uint32_t muteWaitMs;
4869
4870 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004871 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4872 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004873 return muteWaitMs;
4874 }
4875 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4876 // output profile
4877 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004878 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004879 return 0;
4880 }
4881
4882 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004883 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004884
4885 audio_devices_t prevDevice = outputDesc->mDevice;
4886
4887 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4888
4889 if (device != AUDIO_DEVICE_NONE) {
4890 outputDesc->mDevice = device;
4891 }
4892 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4893
4894 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004895 // the requested device is AUDIO_DEVICE_NONE
4896 // OR the requested device is the same as current device
4897 // AND force is not specified
4898 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004899 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004900 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4901 outputDesc->mPatchHandle != 0) {
4902 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4903 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004904 return muteWaitMs;
4905 }
4906
4907 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004908
Eric Laurente552edb2014-03-10 17:42:56 -07004909 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004910 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004911 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004912 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004913 DeviceVector deviceList = (address == NULL) ?
4914 mAvailableOutputDevices.getDevicesFromType(device)
4915 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004916 if (!deviceList.isEmpty()) {
4917 struct audio_patch patch;
4918 outputDesc->toAudioPortConfig(&patch.sources[0]);
4919 patch.num_sources = 1;
4920 patch.num_sinks = 0;
4921 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4922 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004923 patch.num_sinks++;
4924 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 ssize_t index;
4926 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4927 index = mAudioPatches.indexOfKey(*patchHandle);
4928 } else {
4929 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4930 }
4931 sp< AudioPatch> patchDesc;
4932 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4933 if (index >= 0) {
4934 patchDesc = mAudioPatches.valueAt(index);
4935 afPatchHandle = patchDesc->mAfPatchHandle;
4936 }
4937
Eric Laurent1c333e22014-05-20 10:48:17 -07004938 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 &afPatchHandle,
4940 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004941 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4942 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004943 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004944 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004945 if (index < 0) {
4946 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4947 &patch, mUidCached);
4948 addAudioPatch(patchDesc->mHandle, patchDesc);
4949 } else {
4950 patchDesc->mPatch = patch;
4951 }
4952 patchDesc->mAfPatchHandle = afPatchHandle;
4953 patchDesc->mUid = mUidCached;
4954 if (patchHandle) {
4955 *patchHandle = patchDesc->mHandle;
4956 }
4957 outputDesc->mPatchHandle = patchDesc->mHandle;
4958 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004959 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004960 }
4961 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004962
4963 // inform all input as well
4964 for (size_t i = 0; i < mInputs.size(); i++) {
4965 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4966 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4967 AudioParameter inputCmd = AudioParameter();
4968 ALOGV("%s: inform input %d of device:%d", __func__,
4969 inputDescriptor->mIoHandle, device);
4970 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4971 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4972 inputCmd.toString(),
4973 delayMs);
4974 }
4975 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004976 }
Eric Laurente552edb2014-03-10 17:42:56 -07004977
4978 // update stream volumes according to new device
4979 applyStreamVolumes(output, device, delayMs);
4980
4981 return muteWaitMs;
4982}
4983
Eric Laurent1c333e22014-05-20 10:48:17 -07004984status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004985 int delayMs,
4986 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004987{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004988 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004989 ssize_t index;
4990 if (patchHandle) {
4991 index = mAudioPatches.indexOfKey(*patchHandle);
4992 } else {
4993 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4994 }
4995 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004996 return INVALID_OPERATION;
4997 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4999 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005000 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
5001 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 removeAudioPatch(patchDesc->mHandle);
5003 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005004 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005005 return status;
5006}
5007
5008status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5009 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005010 bool force,
5011 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005012{
5013 status_t status = NO_ERROR;
5014
Eric Laurent1f2f2232014-06-02 12:01:23 -07005015 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005016 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5017 inputDesc->mDevice = device;
5018
5019 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5020 if (!deviceList.isEmpty()) {
5021 struct audio_patch patch;
5022 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005023 // AUDIO_SOURCE_HOTWORD is for internal use only:
5024 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005025 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
5026 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005027 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5028 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005029 patch.num_sinks = 1;
5030 //only one input device for now
5031 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005032 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005033 ssize_t index;
5034 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5035 index = mAudioPatches.indexOfKey(*patchHandle);
5036 } else {
5037 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5038 }
5039 sp< AudioPatch> patchDesc;
5040 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5041 if (index >= 0) {
5042 patchDesc = mAudioPatches.valueAt(index);
5043 afPatchHandle = patchDesc->mAfPatchHandle;
5044 }
5045
Eric Laurent1c333e22014-05-20 10:48:17 -07005046 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005047 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005048 0);
5049 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005050 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005051 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005052 if (index < 0) {
5053 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5054 &patch, mUidCached);
5055 addAudioPatch(patchDesc->mHandle, patchDesc);
5056 } else {
5057 patchDesc->mPatch = patch;
5058 }
5059 patchDesc->mAfPatchHandle = afPatchHandle;
5060 patchDesc->mUid = mUidCached;
5061 if (patchHandle) {
5062 *patchHandle = patchDesc->mHandle;
5063 }
5064 inputDesc->mPatchHandle = patchDesc->mHandle;
5065 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005066 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005067 }
5068 }
5069 }
5070 return status;
5071}
5072
Eric Laurent6a94d692014-05-20 11:18:06 -07005073status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5074 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005075{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005076 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005077 ssize_t index;
5078 if (patchHandle) {
5079 index = mAudioPatches.indexOfKey(*patchHandle);
5080 } else {
5081 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5082 }
5083 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005084 return INVALID_OPERATION;
5085 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005086 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5087 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005088 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5089 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005090 removeAudioPatch(patchDesc->mHandle);
5091 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005092 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005093 return status;
5094}
5095
5096sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08005097 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07005098 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005099 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005100 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07005101 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005102{
5103 // Choose an input profile based on the requested capture parameters: select the first available
5104 // profile supporting all requested parameters.
5105
5106 for (size_t i = 0; i < mHwModules.size(); i++)
5107 {
5108 if (mHwModules[i]->mHandle == 0) {
5109 continue;
5110 }
5111 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5112 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005113 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005114 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005115 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005116 &samplingRate /*updatedSamplingRate*/,
5117 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005118
Eric Laurente552edb2014-03-10 17:42:56 -07005119 return profile;
5120 }
5121 }
5122 }
5123 return NULL;
5124}
5125
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005126
5127audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
Eric Laurentc722f302014-12-10 11:21:49 -08005128 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005129{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005130 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5131 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005132
5133 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5134 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5135 continue;
5136 }
5137 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5138 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5139 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5140 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5141 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5142 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurentc722f302014-12-10 11:21:49 -08005143 if (policyMix != NULL) {
5144 *policyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005145 }
5146 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5147 }
5148 break;
5149 }
5150 }
5151 }
5152
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005153 return getDeviceForInputSource(inputSource);
5154}
5155
5156audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5157{
5158 uint32_t device = AUDIO_DEVICE_NONE;
5159 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5160 ~AUDIO_DEVICE_BIT_IN;
5161
Eric Laurente552edb2014-03-10 17:42:56 -07005162 switch (inputSource) {
5163 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005164 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005165 device = AUDIO_DEVICE_IN_VOICE_CALL;
5166 break;
5167 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005168 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005169
5170 case AUDIO_SOURCE_DEFAULT:
5171 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005172 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5173 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentdc136ff2014-12-16 12:24:18 -08005174 } else if ((mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO) &&
5175 (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET)) {
5176 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005177 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5178 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5179 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5180 device = AUDIO_DEVICE_IN_USB_DEVICE;
5181 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5182 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005183 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005184 break;
5185
5186 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5187 // Allow only use of devices on primary input if in call and HAL does not support routing
5188 // to voice call path.
5189 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5190 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5191 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5192 }
5193
5194 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5195 case AUDIO_POLICY_FORCE_BT_SCO:
5196 // if SCO device is requested but no SCO device is available, fall back to default case
5197 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5198 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5199 break;
5200 }
5201 // FALL THROUGH
5202
5203 default: // FORCE_NONE
5204 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5205 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5206 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5207 device = AUDIO_DEVICE_IN_USB_DEVICE;
5208 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5209 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5210 }
5211 break;
5212
5213 case AUDIO_POLICY_FORCE_SPEAKER:
5214 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5215 device = AUDIO_DEVICE_IN_BACK_MIC;
5216 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5217 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5218 }
5219 break;
5220 }
5221 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005222
Eric Laurente552edb2014-03-10 17:42:56 -07005223 case AUDIO_SOURCE_VOICE_RECOGNITION:
5224 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005225 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005226 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005227 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005228 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005229 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005230 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5231 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005232 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005233 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5234 }
5235 break;
5236 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005237 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005238 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005239 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005240 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5241 }
5242 break;
5243 case AUDIO_SOURCE_VOICE_DOWNLINK:
5244 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005245 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005246 device = AUDIO_DEVICE_IN_VOICE_CALL;
5247 }
5248 break;
5249 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005250 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005251 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5252 }
5253 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005254 case AUDIO_SOURCE_FM_TUNER:
5255 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5256 device = AUDIO_DEVICE_IN_FM_TUNER;
5257 }
5258 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005259 default:
5260 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5261 break;
5262 }
5263 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5264 return device;
5265}
5266
Eric Laurente0720872014-03-11 09:30:41 -07005267bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005268{
5269 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5270 device &= ~AUDIO_DEVICE_BIT_IN;
5271 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5272 return true;
5273 }
5274 return false;
5275}
5276
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005277bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005278 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005279}
5280
Eric Laurente0720872014-03-11 09:30:41 -07005281audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005282{
5283 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005284 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005285 if ((input_descriptor->mRefCount > 0)
5286 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5287 return mInputs.keyAt(i);
5288 }
5289 }
5290 return 0;
5291}
5292
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005293uint32_t AudioPolicyManager::activeInputsCount() const
5294{
5295 uint32_t count = 0;
5296 for (size_t i = 0; i < mInputs.size(); i++) {
5297 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5298 if (desc->mRefCount > 0) {
5299 return count++;
5300 }
5301 }
5302 return count;
5303}
5304
Eric Laurente552edb2014-03-10 17:42:56 -07005305
Eric Laurente0720872014-03-11 09:30:41 -07005306audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005307{
5308 if (device == AUDIO_DEVICE_NONE) {
5309 // this happens when forcing a route update and no track is active on an output.
5310 // In this case the returned category is not important.
5311 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005312 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005313 // Multiple device selection is either:
5314 // - speaker + one other device: give priority to speaker in this case.
5315 // - one A2DP device + another device: happens with duplicated output. In this case
5316 // retain the device on the A2DP output as the other must not correspond to an active
5317 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005318 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005319 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5320 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005321 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5322 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5323 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5324 device = AUDIO_DEVICE_OUT_AUX_LINE;
5325 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5326 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005327 } else {
5328 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5329 }
5330 }
5331
Jon Eklund11c9fb12014-06-23 14:47:03 -05005332 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5333 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5334 device = AUDIO_DEVICE_OUT_SPEAKER;
5335
Eric Laurent3b73df72014-03-11 09:06:29 -07005336 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005337 "getDeviceForVolume() invalid device combination: %08x",
5338 device);
5339
5340 return device;
5341}
5342
Eric Laurente0720872014-03-11 09:30:41 -07005343AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005344{
5345 switch(getDeviceForVolume(device)) {
5346 case AUDIO_DEVICE_OUT_EARPIECE:
5347 return DEVICE_CATEGORY_EARPIECE;
5348 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5349 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5350 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5351 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5352 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5353 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5354 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005355 case AUDIO_DEVICE_OUT_LINE:
5356 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5357 /*USB? Remote submix?*/
5358 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005359 case AUDIO_DEVICE_OUT_SPEAKER:
5360 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5361 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005362 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5363 case AUDIO_DEVICE_OUT_USB_DEVICE:
5364 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5365 default:
5366 return DEVICE_CATEGORY_SPEAKER;
5367 }
5368}
5369
Eric Laurent223fd5c2014-11-11 13:43:36 -08005370/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005371float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005372 int indexInUi)
5373{
5374 device_category deviceCategory = getDeviceCategory(device);
5375 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5376
5377 // the volume index in the UI is relative to the min and max volume indices for this stream type
5378 int nbSteps = 1 + curve[VOLMAX].mIndex -
5379 curve[VOLMIN].mIndex;
5380 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5381 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5382
5383 // find what part of the curve this index volume belongs to, or if it's out of bounds
5384 int segment = 0;
5385 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5386 return 0.0f;
5387 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5388 segment = 0;
5389 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5390 segment = 1;
5391 } else if (volIdx <= curve[VOLMAX].mIndex) {
5392 segment = 2;
5393 } else { // out of bounds
5394 return 1.0f;
5395 }
5396
5397 // linear interpolation in the attenuation table in dB
5398 float decibels = curve[segment].mDBAttenuation +
5399 ((float)(volIdx - curve[segment].mIndex)) *
5400 ( (curve[segment+1].mDBAttenuation -
5401 curve[segment].mDBAttenuation) /
5402 ((float)(curve[segment+1].mIndex -
5403 curve[segment].mIndex)) );
5404
5405 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5406
5407 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5408 curve[segment].mIndex, volIdx,
5409 curve[segment+1].mIndex,
5410 curve[segment].mDBAttenuation,
5411 decibels,
5412 curve[segment+1].mDBAttenuation,
5413 amplification);
5414
5415 return amplification;
5416}
5417
Eric Laurente0720872014-03-11 09:30:41 -07005418const AudioPolicyManager::VolumeCurvePoint
5419 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005420 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5421};
5422
Eric Laurente0720872014-03-11 09:30:41 -07005423const AudioPolicyManager::VolumeCurvePoint
5424 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005425 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5426};
5427
Eric Laurente0720872014-03-11 09:30:41 -07005428const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005429 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5430 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5431};
5432
5433const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005434 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005435 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5436};
5437
Eric Laurente0720872014-03-11 09:30:41 -07005438const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005439 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005440 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005441};
5442
5443const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005444 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005445 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5446};
5447
Eric Laurente0720872014-03-11 09:30:41 -07005448const AudioPolicyManager::VolumeCurvePoint
5449 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005450 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5451};
5452
5453// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5454// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5455// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5456// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5457
Eric Laurente0720872014-03-11 09:30:41 -07005458const AudioPolicyManager::VolumeCurvePoint
5459 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005460 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5461};
5462
Eric Laurente0720872014-03-11 09:30:41 -07005463const AudioPolicyManager::VolumeCurvePoint
5464 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005465 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5466};
5467
Eric Laurente0720872014-03-11 09:30:41 -07005468const AudioPolicyManager::VolumeCurvePoint
5469 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005470 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5471};
5472
Eric Laurente0720872014-03-11 09:30:41 -07005473const AudioPolicyManager::VolumeCurvePoint
5474 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005475 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5476};
5477
Eric Laurente0720872014-03-11 09:30:41 -07005478const AudioPolicyManager::VolumeCurvePoint
5479 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005480 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5481};
5482
Eric Laurente0720872014-03-11 09:30:41 -07005483const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005484 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5485 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5486};
5487
5488const AudioPolicyManager::VolumeCurvePoint
5489 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5490 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5491};
5492
5493const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005494 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5495 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5496};
5497
5498const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005499 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5500 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005501 { // AUDIO_STREAM_VOICE_CALL
5502 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5503 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005504 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5505 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005506 },
5507 { // AUDIO_STREAM_SYSTEM
5508 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5509 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005510 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5511 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005512 },
5513 { // AUDIO_STREAM_RING
5514 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5515 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005516 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5517 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005518 },
5519 { // AUDIO_STREAM_MUSIC
5520 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5521 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005522 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5523 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005524 },
5525 { // AUDIO_STREAM_ALARM
5526 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5527 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005528 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5529 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005530 },
5531 { // AUDIO_STREAM_NOTIFICATION
5532 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5533 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005534 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5535 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005536 },
5537 { // AUDIO_STREAM_BLUETOOTH_SCO
5538 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5539 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005540 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5541 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005542 },
5543 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5544 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5545 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005546 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5547 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005548 },
5549 { // AUDIO_STREAM_DTMF
5550 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5551 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005552 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5553 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005554 },
5555 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005556 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5557 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5558 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5559 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5560 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005561 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005562 { // AUDIO_STREAM_ACCESSIBILITY
5563 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5564 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5565 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5566 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5567 },
5568 { // AUDIO_STREAM_REROUTING
5569 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5570 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5571 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5572 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5573 },
5574 { // AUDIO_STREAM_PATCH
5575 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5576 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5577 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5578 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5579 },
Eric Laurente552edb2014-03-10 17:42:56 -07005580};
5581
Eric Laurente0720872014-03-11 09:30:41 -07005582void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005583{
5584 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5585 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5586 mStreams[i].mVolumeCurve[j] =
5587 sVolumeProfiles[i][j];
5588 }
5589 }
5590
5591 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5592 if (mSpeakerDrcEnabled) {
5593 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5594 sDefaultSystemVolumeCurveDrc;
5595 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5596 sSpeakerSonificationVolumeCurveDrc;
5597 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5598 sSpeakerSonificationVolumeCurveDrc;
5599 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5600 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005601 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5602 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005603 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5604 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005605 }
5606}
5607
Eric Laurente0720872014-03-11 09:30:41 -07005608float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005609 int index,
5610 audio_io_handle_t output,
5611 audio_devices_t device)
5612{
5613 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005614 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005615 StreamDescriptor &streamDesc = mStreams[stream];
5616
5617 if (device == AUDIO_DEVICE_NONE) {
5618 device = outputDesc->device();
5619 }
5620
Eric Laurente552edb2014-03-10 17:42:56 -07005621 volume = volIndexToAmpl(device, streamDesc, index);
5622
5623 // if a headset is connected, apply the following rules to ring tones and notifications
5624 // to avoid sound level bursts in user's ears:
5625 // - always attenuate ring tones and notifications volume by 6dB
5626 // - if music is playing, always limit the volume to current music volume,
5627 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005628 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005629 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5630 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5631 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5632 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5633 ((stream_strategy == STRATEGY_SONIFICATION)
5634 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005635 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005636 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005637 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005638 streamDesc.mCanBeMuted) {
5639 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5640 // when the phone is ringing we must consider that music could have been paused just before
5641 // by the music application and behave as if music was active if the last music track was
5642 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005643 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005644 mLimitRingtoneVolume) {
5645 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005646 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5647 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005648 output,
5649 musicDevice);
5650 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5651 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5652 if (volume > minVol) {
5653 volume = minVol;
5654 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5655 }
5656 }
5657 }
5658
5659 return volume;
5660}
5661
Eric Laurente0720872014-03-11 09:30:41 -07005662status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005663 int index,
5664 audio_io_handle_t output,
5665 audio_devices_t device,
5666 int delayMs,
5667 bool force)
5668{
5669
5670 // do not change actual stream volume if the stream is muted
5671 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5672 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5673 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5674 return NO_ERROR;
5675 }
5676
5677 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005678 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5679 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5680 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5681 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005682 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005683 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005684 return INVALID_OPERATION;
5685 }
5686
5687 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005688 // unit gain if rerouting to external policy
5689 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5690 ssize_t index = mOutputs.indexOfKey(output);
5691 if (index >= 0) {
5692 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurentc722f302014-12-10 11:21:49 -08005693 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005694 ALOGV("max gain when rerouting for output=%d", output);
5695 volume = 1.0f;
5696 }
5697 }
5698
5699 }
Eric Laurente552edb2014-03-10 17:42:56 -07005700 // We actually change the volume if:
5701 // - the float value returned by computeVolume() changed
5702 // - the force flag is set
5703 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5704 force) {
5705 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5706 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5707 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5708 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005709 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5710 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005711 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005712 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005713 }
5714
Eric Laurent3b73df72014-03-11 09:06:29 -07005715 if (stream == AUDIO_STREAM_VOICE_CALL ||
5716 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005717 float voiceVolume;
5718 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005719 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005720 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5721 } else {
5722 voiceVolume = 1.0;
5723 }
5724
5725 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5726 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5727 mLastVoiceVolume = voiceVolume;
5728 }
5729 }
5730
5731 return NO_ERROR;
5732}
5733
Eric Laurente0720872014-03-11 09:30:41 -07005734void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005735 audio_devices_t device,
5736 int delayMs,
5737 bool force)
5738{
5739 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5740
Eric Laurent3b73df72014-03-11 09:06:29 -07005741 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005742 if (stream == AUDIO_STREAM_PATCH) {
5743 continue;
5744 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005745 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005746 mStreams[stream].getVolumeIndex(device),
5747 output,
5748 device,
5749 delayMs,
5750 force);
5751 }
5752}
5753
Eric Laurente0720872014-03-11 09:30:41 -07005754void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005755 bool on,
5756 audio_io_handle_t output,
5757 int delayMs,
5758 audio_devices_t device)
5759{
5760 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005761 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005762 if (stream == AUDIO_STREAM_PATCH) {
5763 continue;
5764 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005765 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5766 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005767 }
5768 }
5769}
5770
Eric Laurente0720872014-03-11 09:30:41 -07005771void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005772 bool on,
5773 audio_io_handle_t output,
5774 int delayMs,
5775 audio_devices_t device)
5776{
5777 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005778 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005779 if (device == AUDIO_DEVICE_NONE) {
5780 device = outputDesc->device();
5781 }
5782
5783 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5784 stream, on, output, outputDesc->mMuteCount[stream], device);
5785
5786 if (on) {
5787 if (outputDesc->mMuteCount[stream] == 0) {
5788 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005789 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5790 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005791 checkAndSetVolume(stream, 0, output, device, delayMs);
5792 }
5793 }
5794 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5795 outputDesc->mMuteCount[stream]++;
5796 } else {
5797 if (outputDesc->mMuteCount[stream] == 0) {
5798 ALOGV("setStreamMute() unmuting non muted stream!");
5799 return;
5800 }
5801 if (--outputDesc->mMuteCount[stream] == 0) {
5802 checkAndSetVolume(stream,
5803 streamDesc.getVolumeIndex(device),
5804 output,
5805 device,
5806 delayMs);
5807 }
5808 }
5809}
5810
Eric Laurente0720872014-03-11 09:30:41 -07005811void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005812 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005813{
5814 // if the stream pertains to sonification strategy and we are in call we must
5815 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5816 // in the device used for phone strategy and play the tone if the selected device does not
5817 // interfere with the device used for phone strategy
5818 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5819 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005820 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005821 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5822 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005823 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005824 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5825 stream, starting, outputDesc->mDevice, stateChange);
5826 if (outputDesc->mRefCount[stream]) {
5827 int muteCount = 1;
5828 if (stateChange) {
5829 muteCount = outputDesc->mRefCount[stream];
5830 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005831 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005832 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5833 for (int i = 0; i < muteCount; i++) {
5834 setStreamMute(stream, starting, mPrimaryOutput);
5835 }
5836 } else {
5837 ALOGV("handleIncallSonification() high visibility");
5838 if (outputDesc->device() &
5839 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5840 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5841 for (int i = 0; i < muteCount; i++) {
5842 setStreamMute(stream, starting, mPrimaryOutput);
5843 }
5844 }
5845 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005846 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5847 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005848 } else {
5849 mpClientInterface->stopTone();
5850 }
5851 }
5852 }
5853 }
5854}
5855
Eric Laurente0720872014-03-11 09:30:41 -07005856bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005857{
5858 return isStateInCall(mPhoneState);
5859}
5860
Eric Laurente0720872014-03-11 09:30:41 -07005861bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005862 return ((state == AUDIO_MODE_IN_CALL) ||
5863 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005864}
5865
Eric Laurente0720872014-03-11 09:30:41 -07005866uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005867{
5868 return MAX_EFFECTS_CPU_LOAD;
5869}
5870
Eric Laurente0720872014-03-11 09:30:41 -07005871uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005872{
5873 return MAX_EFFECTS_MEMORY;
5874}
5875
Eric Laurent6a94d692014-05-20 11:18:06 -07005876
Eric Laurente552edb2014-03-10 17:42:56 -07005877// --- AudioOutputDescriptor class implementation
5878
Eric Laurente0720872014-03-11 09:30:41 -07005879AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005880 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005881 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurentc722f302014-12-10 11:21:49 -08005882 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
Eric Laurent275e8e92014-11-30 15:14:47 -08005883 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005884 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5885{
5886 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005887 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005888 mRefCount[i] = 0;
5889 mCurVolume[i] = -1.0;
5890 mMuteCount[i] = 0;
5891 mStopTime[i] = 0;
5892 }
5893 for (int i = 0; i < NUM_STRATEGIES; i++) {
5894 mStrategyMutedByDevice[i] = false;
5895 }
5896 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005897 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005898 mSamplingRate = profile->pickSamplingRate();
5899 mFormat = profile->pickFormat();
5900 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005901 if (profile->mGains.size() > 0) {
5902 profile->mGains[0]->getDefaultConfig(&mGain);
5903 }
Eric Laurente552edb2014-03-10 17:42:56 -07005904 }
5905}
5906
Eric Laurente0720872014-03-11 09:30:41 -07005907audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005908{
5909 if (isDuplicated()) {
5910 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5911 } else {
5912 return mDevice;
5913 }
5914}
5915
Eric Laurente0720872014-03-11 09:30:41 -07005916uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005917{
5918 if (isDuplicated()) {
5919 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5920 } else {
5921 return mLatency;
5922 }
5923}
5924
Eric Laurente0720872014-03-11 09:30:41 -07005925bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005926 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005927{
5928 if (isDuplicated()) {
5929 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5930 } else if (outputDesc->isDuplicated()){
5931 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5932 } else {
5933 return (mProfile->mModule == outputDesc->mProfile->mModule);
5934 }
5935}
5936
Eric Laurente0720872014-03-11 09:30:41 -07005937void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005938 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005939{
5940 // forward usage count change to attached outputs
5941 if (isDuplicated()) {
5942 mOutput1->changeRefCount(stream, delta);
5943 mOutput2->changeRefCount(stream, delta);
5944 }
5945 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005946 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5947 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005948 mRefCount[stream] = 0;
5949 return;
5950 }
5951 mRefCount[stream] += delta;
5952 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5953}
5954
Eric Laurente0720872014-03-11 09:30:41 -07005955audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005956{
5957 if (isDuplicated()) {
5958 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5959 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005960 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005961 }
5962}
5963
Eric Laurente0720872014-03-11 09:30:41 -07005964bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005965{
5966 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5967}
5968
Eric Laurente0720872014-03-11 09:30:41 -07005969bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005970 uint32_t inPastMs,
5971 nsecs_t sysTime) const
5972{
5973 if ((sysTime == 0) && (inPastMs != 0)) {
5974 sysTime = systemTime();
5975 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005976 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005977 if (i == AUDIO_STREAM_PATCH) {
5978 continue;
5979 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005980 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005981 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005982 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005983 return true;
5984 }
5985 }
5986 return false;
5987}
5988
Eric Laurente0720872014-03-11 09:30:41 -07005989bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005990 uint32_t inPastMs,
5991 nsecs_t sysTime) const
5992{
5993 if (mRefCount[stream] != 0) {
5994 return true;
5995 }
5996 if (inPastMs == 0) {
5997 return false;
5998 }
5999 if (sysTime == 0) {
6000 sysTime = systemTime();
6001 }
6002 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
6003 return true;
6004 }
6005 return false;
6006}
6007
Eric Laurent1c333e22014-05-20 10:48:17 -07006008void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006009 struct audio_port_config *dstConfig,
6010 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006011{
Eric Laurent84c70242014-06-23 08:46:27 -07006012 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
6013
Eric Laurent1f2f2232014-06-02 12:01:23 -07006014 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6015 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6016 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006017 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006018 }
6019 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6020
Eric Laurent6a94d692014-05-20 11:18:06 -07006021 dstConfig->id = mId;
6022 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
6023 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07006024 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6025 dstConfig->ext.mix.handle = mIoHandle;
6026 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07006027}
6028
6029void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
6030 struct audio_port *port) const
6031{
Eric Laurent84c70242014-06-23 08:46:27 -07006032 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07006033 mProfile->toAudioPort(port);
6034 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006035 toAudioPortConfig(&port->active_config);
6036 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006037 port->ext.mix.handle = mIoHandle;
6038 port->ext.mix.latency_class =
6039 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
6040}
Eric Laurente552edb2014-03-10 17:42:56 -07006041
Eric Laurente0720872014-03-11 09:30:41 -07006042status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006043{
6044 const size_t SIZE = 256;
6045 char buffer[SIZE];
6046 String8 result;
6047
Eric Laurent4d416952014-08-10 14:07:09 -07006048 snprintf(buffer, SIZE, " ID: %d\n", mId);
6049 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006050 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6051 result.append(buffer);
6052 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
6053 result.append(buffer);
6054 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6055 result.append(buffer);
6056 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
6057 result.append(buffer);
6058 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
6059 result.append(buffer);
6060 snprintf(buffer, SIZE, " Devices %08x\n", device());
6061 result.append(buffer);
6062 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
6063 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07006064 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6065 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
6066 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07006067 result.append(buffer);
6068 }
6069 write(fd, result.string(), result.size());
6070
6071 return NO_ERROR;
6072}
6073
6074// --- AudioInputDescriptor class implementation
6075
Eric Laurent1c333e22014-05-20 10:48:17 -07006076AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006077 : mId(0), mIoHandle(0),
Eric Laurentc722f302014-12-10 11:21:49 -08006078 mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006079 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07006080{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006081 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006082 mSamplingRate = profile->pickSamplingRate();
6083 mFormat = profile->pickFormat();
6084 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07006085 if (profile->mGains.size() > 0) {
6086 profile->mGains[0]->getDefaultConfig(&mGain);
6087 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006088 }
Eric Laurente552edb2014-03-10 17:42:56 -07006089}
6090
Eric Laurent1c333e22014-05-20 10:48:17 -07006091void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006092 struct audio_port_config *dstConfig,
6093 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006094{
Eric Laurent84c70242014-06-23 08:46:27 -07006095 ALOG_ASSERT(mProfile != 0,
6096 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07006097 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6098 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6099 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006100 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006101 }
6102
6103 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6104
Eric Laurent6a94d692014-05-20 11:18:06 -07006105 dstConfig->id = mId;
6106 dstConfig->role = AUDIO_PORT_ROLE_SINK;
6107 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07006108 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6109 dstConfig->ext.mix.handle = mIoHandle;
6110 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07006111}
6112
6113void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6114 struct audio_port *port) const
6115{
Eric Laurent84c70242014-06-23 08:46:27 -07006116 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6117
Eric Laurent1c333e22014-05-20 10:48:17 -07006118 mProfile->toAudioPort(port);
6119 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006120 toAudioPortConfig(&port->active_config);
6121 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006122 port->ext.mix.handle = mIoHandle;
6123 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6124}
6125
Eric Laurente0720872014-03-11 09:30:41 -07006126status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006127{
6128 const size_t SIZE = 256;
6129 char buffer[SIZE];
6130 String8 result;
6131
Eric Laurent4d416952014-08-10 14:07:09 -07006132 snprintf(buffer, SIZE, " ID: %d\n", mId);
6133 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006134 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6135 result.append(buffer);
6136 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6137 result.append(buffer);
6138 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6139 result.append(buffer);
6140 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6141 result.append(buffer);
6142 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6143 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006144 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6145 result.append(buffer);
6146
Eric Laurente552edb2014-03-10 17:42:56 -07006147 write(fd, result.string(), result.size());
6148
6149 return NO_ERROR;
6150}
6151
6152// --- StreamDescriptor class implementation
6153
Eric Laurente0720872014-03-11 09:30:41 -07006154AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006155 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6156{
6157 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6158}
6159
Eric Laurente0720872014-03-11 09:30:41 -07006160int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006161{
Eric Laurente0720872014-03-11 09:30:41 -07006162 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006163 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6164 if (mIndexCur.indexOfKey(device) < 0) {
6165 device = AUDIO_DEVICE_OUT_DEFAULT;
6166 }
6167 return mIndexCur.valueFor(device);
6168}
6169
Eric Laurente0720872014-03-11 09:30:41 -07006170void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006171{
6172 const size_t SIZE = 256;
6173 char buffer[SIZE];
6174 String8 result;
6175
6176 snprintf(buffer, SIZE, "%s %02d %02d ",
6177 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6178 result.append(buffer);
6179 for (size_t i = 0; i < mIndexCur.size(); i++) {
6180 snprintf(buffer, SIZE, "%04x : %02d, ",
6181 mIndexCur.keyAt(i),
6182 mIndexCur.valueAt(i));
6183 result.append(buffer);
6184 }
6185 result.append("\n");
6186
6187 write(fd, result.string(), result.size());
6188}
6189
6190// --- EffectDescriptor class implementation
6191
Eric Laurente0720872014-03-11 09:30:41 -07006192status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006193{
6194 const size_t SIZE = 256;
6195 char buffer[SIZE];
6196 String8 result;
6197
6198 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6199 result.append(buffer);
6200 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6201 result.append(buffer);
6202 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6203 result.append(buffer);
6204 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6205 result.append(buffer);
6206 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6207 result.append(buffer);
6208 write(fd, result.string(), result.size());
6209
6210 return NO_ERROR;
6211}
6212
Eric Laurent1c333e22014-05-20 10:48:17 -07006213// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006214
Eric Laurente0720872014-03-11 09:30:41 -07006215AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006216 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6217 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006218{
6219}
6220
Eric Laurente0720872014-03-11 09:30:41 -07006221AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006222{
6223 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006224 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006225 }
6226 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006227 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006228 }
6229 free((void *)mName);
6230}
6231
Eric Laurent1afeecb2014-05-14 08:52:28 -07006232status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6233{
6234 cnode *node = root->first_child;
6235
6236 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6237
6238 while (node) {
6239 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6240 profile->loadSamplingRates((char *)node->value);
6241 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6242 profile->loadFormats((char *)node->value);
6243 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6244 profile->loadInChannels((char *)node->value);
6245 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6246 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6247 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006248 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6249 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006250 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6251 profile->loadGains(node);
6252 }
6253 node = node->next;
6254 }
6255 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6256 "loadInput() invalid supported devices");
6257 ALOGW_IF(profile->mChannelMasks.size() == 0,
6258 "loadInput() invalid supported channel masks");
6259 ALOGW_IF(profile->mSamplingRates.size() == 0,
6260 "loadInput() invalid supported sampling rates");
6261 ALOGW_IF(profile->mFormats.size() == 0,
6262 "loadInput() invalid supported formats");
6263 if (!profile->mSupportedDevices.isEmpty() &&
6264 (profile->mChannelMasks.size() != 0) &&
6265 (profile->mSamplingRates.size() != 0) &&
6266 (profile->mFormats.size() != 0)) {
6267
6268 ALOGV("loadInput() adding input Supported Devices %04x",
6269 profile->mSupportedDevices.types());
6270
6271 mInputProfiles.add(profile);
6272 return NO_ERROR;
6273 } else {
6274 return BAD_VALUE;
6275 }
6276}
6277
6278status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6279{
6280 cnode *node = root->first_child;
6281
6282 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6283
6284 while (node) {
6285 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6286 profile->loadSamplingRates((char *)node->value);
6287 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6288 profile->loadFormats((char *)node->value);
6289 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6290 profile->loadOutChannels((char *)node->value);
6291 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6292 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6293 mDeclaredDevices);
6294 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006295 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006296 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6297 profile->loadGains(node);
6298 }
6299 node = node->next;
6300 }
6301 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6302 "loadOutput() invalid supported devices");
6303 ALOGW_IF(profile->mChannelMasks.size() == 0,
6304 "loadOutput() invalid supported channel masks");
6305 ALOGW_IF(profile->mSamplingRates.size() == 0,
6306 "loadOutput() invalid supported sampling rates");
6307 ALOGW_IF(profile->mFormats.size() == 0,
6308 "loadOutput() invalid supported formats");
6309 if (!profile->mSupportedDevices.isEmpty() &&
6310 (profile->mChannelMasks.size() != 0) &&
6311 (profile->mSamplingRates.size() != 0) &&
6312 (profile->mFormats.size() != 0)) {
6313
6314 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6315 profile->mSupportedDevices.types(), profile->mFlags);
6316
6317 mOutputProfiles.add(profile);
6318 return NO_ERROR;
6319 } else {
6320 return BAD_VALUE;
6321 }
6322}
6323
6324status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6325{
6326 cnode *node = root->first_child;
6327
6328 audio_devices_t type = AUDIO_DEVICE_NONE;
6329 while (node) {
6330 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6331 type = parseDeviceNames((char *)node->value);
6332 break;
6333 }
6334 node = node->next;
6335 }
6336 if (type == AUDIO_DEVICE_NONE ||
6337 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6338 ALOGW("loadDevice() bad type %08x", type);
6339 return BAD_VALUE;
6340 }
6341 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6342 deviceDesc->mModule = this;
6343
6344 node = root->first_child;
6345 while (node) {
6346 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6347 deviceDesc->mAddress = String8((char *)node->value);
6348 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6349 if (audio_is_input_device(type)) {
6350 deviceDesc->loadInChannels((char *)node->value);
6351 } else {
6352 deviceDesc->loadOutChannels((char *)node->value);
6353 }
6354 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6355 deviceDesc->loadGains(node);
6356 }
6357 node = node->next;
6358 }
6359
6360 ALOGV("loadDevice() adding device name %s type %08x address %s",
6361 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6362
6363 mDeclaredDevices.add(deviceDesc);
6364
6365 return NO_ERROR;
6366}
6367
Eric Laurent275e8e92014-11-30 15:14:47 -08006368status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6369 audio_devices_t device, String8 address)
6370{
6371 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6372
6373 profile->mSamplingRates.add(config->sample_rate);
6374 profile->mChannelMasks.add(config->channel_mask);
6375 profile->mFormats.add(config->format);
6376
6377 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6378 devDesc->mAddress = address;
6379 profile->mSupportedDevices.add(devDesc);
6380
6381 mOutputProfiles.add(profile);
6382
6383 return NO_ERROR;
6384}
6385
6386status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6387{
6388 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6389 if (mOutputProfiles[i]->mName == name) {
6390 mOutputProfiles.removeAt(i);
6391 break;
6392 }
6393 }
6394
6395 return NO_ERROR;
6396}
6397
6398status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6399 audio_devices_t device, String8 address)
6400{
6401 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6402
6403 profile->mSamplingRates.add(config->sample_rate);
6404 profile->mChannelMasks.add(config->channel_mask);
6405 profile->mFormats.add(config->format);
6406
6407 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6408 devDesc->mAddress = address;
6409 profile->mSupportedDevices.add(devDesc);
6410
6411 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6412
6413 mInputProfiles.add(profile);
6414
6415 return NO_ERROR;
6416}
6417
6418status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6419{
6420 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6421 if (mInputProfiles[i]->mName == name) {
6422 mInputProfiles.removeAt(i);
6423 break;
6424 }
6425 }
6426
6427 return NO_ERROR;
6428}
6429
6430
Eric Laurente0720872014-03-11 09:30:41 -07006431void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006432{
6433 const size_t SIZE = 256;
6434 char buffer[SIZE];
6435 String8 result;
6436
6437 snprintf(buffer, SIZE, " - name: %s\n", mName);
6438 result.append(buffer);
6439 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6440 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006441 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6442 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006443 write(fd, result.string(), result.size());
6444 if (mOutputProfiles.size()) {
6445 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6446 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006447 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006448 write(fd, buffer, strlen(buffer));
6449 mOutputProfiles[i]->dump(fd);
6450 }
6451 }
6452 if (mInputProfiles.size()) {
6453 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6454 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006455 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006456 write(fd, buffer, strlen(buffer));
6457 mInputProfiles[i]->dump(fd);
6458 }
6459 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006460 if (mDeclaredDevices.size()) {
6461 write(fd, " - devices:\n", strlen(" - devices:\n"));
6462 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6463 mDeclaredDevices[i]->dump(fd, 4, i);
6464 }
6465 }
Eric Laurente552edb2014-03-10 17:42:56 -07006466}
6467
Eric Laurent1c333e22014-05-20 10:48:17 -07006468// --- AudioPort class implementation
6469
Eric Laurenta121f902014-06-03 13:32:54 -07006470
6471AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6472 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006473 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006474{
6475 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6476 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6477}
6478
Eric Laurent1c333e22014-05-20 10:48:17 -07006479void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6480{
6481 port->role = mRole;
6482 port->type = mType;
6483 unsigned int i;
6484 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006485 if (mSamplingRates[i] != 0) {
6486 port->sample_rates[i] = mSamplingRates[i];
6487 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006488 }
6489 port->num_sample_rates = i;
6490 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006491 if (mChannelMasks[i] != 0) {
6492 port->channel_masks[i] = mChannelMasks[i];
6493 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006494 }
6495 port->num_channel_masks = i;
6496 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006497 if (mFormats[i] != 0) {
6498 port->formats[i] = mFormats[i];
6499 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006500 }
6501 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006502
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006503 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006504
6505 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6506 port->gains[i] = mGains[i]->mGain;
6507 }
6508 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006509}
6510
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006511void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6512 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6513 const uint32_t rate = port->mSamplingRates.itemAt(k);
6514 if (rate != 0) { // skip "dynamic" rates
6515 bool hasRate = false;
6516 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6517 if (rate == mSamplingRates.itemAt(l)) {
6518 hasRate = true;
6519 break;
6520 }
6521 }
6522 if (!hasRate) { // never import a sampling rate twice
6523 mSamplingRates.add(rate);
6524 }
6525 }
6526 }
6527 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6528 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6529 if (mask != 0) { // skip "dynamic" masks
6530 bool hasMask = false;
6531 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6532 if (mask == mChannelMasks.itemAt(l)) {
6533 hasMask = true;
6534 break;
6535 }
6536 }
6537 if (!hasMask) { // never import a channel mask twice
6538 mChannelMasks.add(mask);
6539 }
6540 }
6541 }
6542 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6543 const audio_format_t format = port->mFormats.itemAt(k);
6544 if (format != 0) { // skip "dynamic" formats
6545 bool hasFormat = false;
6546 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6547 if (format == mFormats.itemAt(l)) {
6548 hasFormat = true;
6549 break;
6550 }
6551 }
6552 if (!hasFormat) { // never import a channel mask twice
6553 mFormats.add(format);
6554 }
6555 }
6556 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006557 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6558 sp<AudioGain> gain = port->mGains.itemAt(k);
6559 if (gain != 0) {
6560 bool hasGain = false;
6561 for (size_t l = 0 ; l < mGains.size() ; l++) {
6562 if (gain == mGains.itemAt(l)) {
6563 hasGain = true;
6564 break;
6565 }
6566 }
6567 if (!hasGain) { // never import a gain twice
6568 mGains.add(gain);
6569 }
6570 }
6571 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006572}
6573
6574void AudioPolicyManager::AudioPort::clearCapabilities() {
6575 mChannelMasks.clear();
6576 mFormats.clear();
6577 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006578 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006579}
Eric Laurent1c333e22014-05-20 10:48:17 -07006580
6581void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6582{
6583 char *str = strtok(name, "|");
6584
6585 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6586 // rates should be read from the output stream after it is opened for the first time
6587 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6588 mSamplingRates.add(0);
6589 return;
6590 }
6591
6592 while (str != NULL) {
6593 uint32_t rate = atoi(str);
6594 if (rate != 0) {
6595 ALOGV("loadSamplingRates() adding rate %d", rate);
6596 mSamplingRates.add(rate);
6597 }
6598 str = strtok(NULL, "|");
6599 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006600}
6601
6602void AudioPolicyManager::AudioPort::loadFormats(char *name)
6603{
6604 char *str = strtok(name, "|");
6605
6606 // by convention, "0' in the first entry in mFormats indicates the supported formats
6607 // should be read from the output stream after it is opened for the first time
6608 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6609 mFormats.add(AUDIO_FORMAT_DEFAULT);
6610 return;
6611 }
6612
6613 while (str != NULL) {
6614 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6615 ARRAY_SIZE(sFormatNameToEnumTable),
6616 str);
6617 if (format != AUDIO_FORMAT_DEFAULT) {
6618 mFormats.add(format);
6619 }
6620 str = strtok(NULL, "|");
6621 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006622}
6623
6624void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6625{
6626 const char *str = strtok(name, "|");
6627
6628 ALOGV("loadInChannels() %s", name);
6629
6630 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6631 mChannelMasks.add(0);
6632 return;
6633 }
6634
6635 while (str != NULL) {
6636 audio_channel_mask_t channelMask =
6637 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6638 ARRAY_SIZE(sInChannelsNameToEnumTable),
6639 str);
6640 if (channelMask != 0) {
6641 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6642 mChannelMasks.add(channelMask);
6643 }
6644 str = strtok(NULL, "|");
6645 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006646}
6647
6648void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6649{
6650 const char *str = strtok(name, "|");
6651
6652 ALOGV("loadOutChannels() %s", name);
6653
6654 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6655 // masks should be read from the output stream after it is opened for the first time
6656 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6657 mChannelMasks.add(0);
6658 return;
6659 }
6660
6661 while (str != NULL) {
6662 audio_channel_mask_t channelMask =
6663 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6664 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6665 str);
6666 if (channelMask != 0) {
6667 mChannelMasks.add(channelMask);
6668 }
6669 str = strtok(NULL, "|");
6670 }
6671 return;
6672}
6673
Eric Laurent1afeecb2014-05-14 08:52:28 -07006674audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6675{
6676 const char *str = strtok(name, "|");
6677
6678 ALOGV("loadGainMode() %s", name);
6679 audio_gain_mode_t mode = 0;
6680 while (str != NULL) {
6681 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6682 ARRAY_SIZE(sGainModeNameToEnumTable),
6683 str);
6684 str = strtok(NULL, "|");
6685 }
6686 return mode;
6687}
6688
Eric Laurenta121f902014-06-03 13:32:54 -07006689void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006690{
6691 cnode *node = root->first_child;
6692
Eric Laurenta121f902014-06-03 13:32:54 -07006693 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006694
6695 while (node) {
6696 if (strcmp(node->name, GAIN_MODE) == 0) {
6697 gain->mGain.mode = loadGainMode((char *)node->value);
6698 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006699 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006700 gain->mGain.channel_mask =
6701 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6702 ARRAY_SIZE(sInChannelsNameToEnumTable),
6703 (char *)node->value);
6704 } else {
6705 gain->mGain.channel_mask =
6706 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6707 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6708 (char *)node->value);
6709 }
6710 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6711 gain->mGain.min_value = atoi((char *)node->value);
6712 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6713 gain->mGain.max_value = atoi((char *)node->value);
6714 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6715 gain->mGain.default_value = atoi((char *)node->value);
6716 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6717 gain->mGain.step_value = atoi((char *)node->value);
6718 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6719 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6720 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6721 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6722 }
6723 node = node->next;
6724 }
6725
6726 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6727 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6728
6729 if (gain->mGain.mode == 0) {
6730 return;
6731 }
6732 mGains.add(gain);
6733}
6734
6735void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6736{
6737 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006738 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006739 while (node) {
6740 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006741 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006742 node = node->next;
6743 }
6744}
6745
Glenn Kastencbd48022014-07-24 13:46:44 -07006746status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006747{
Eric Laurent0daea392014-12-04 19:14:54 -08006748 if (mSamplingRates.isEmpty()) {
6749 return NO_ERROR;
6750 }
6751
Eric Laurenta121f902014-06-03 13:32:54 -07006752 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6753 if (mSamplingRates[i] == samplingRate) {
6754 return NO_ERROR;
6755 }
6756 }
6757 return BAD_VALUE;
6758}
6759
Glenn Kastencbd48022014-07-24 13:46:44 -07006760status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6761 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006762{
Eric Laurent0daea392014-12-04 19:14:54 -08006763 if (mSamplingRates.isEmpty()) {
6764 return NO_ERROR;
6765 }
6766
Glenn Kastencbd48022014-07-24 13:46:44 -07006767 // Search for the closest supported sampling rate that is above (preferred)
6768 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6769 // The sampling rates do not need to be sorted in ascending order.
6770 ssize_t maxBelow = -1;
6771 ssize_t minAbove = -1;
6772 uint32_t candidate;
6773 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6774 candidate = mSamplingRates[i];
6775 if (candidate == samplingRate) {
6776 if (updatedSamplingRate != NULL) {
6777 *updatedSamplingRate = candidate;
6778 }
6779 return NO_ERROR;
6780 }
6781 // candidate < desired
6782 if (candidate < samplingRate) {
6783 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6784 maxBelow = i;
6785 }
6786 // candidate > desired
6787 } else {
6788 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6789 minAbove = i;
6790 }
6791 }
6792 }
6793 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6794 // TODO Move these assumptions out.
6795 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6796 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6797 // due to approximation by an int32_t of the
6798 // phase increments
6799 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6800 if (minAbove >= 0) {
6801 candidate = mSamplingRates[minAbove];
6802 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6803 if (updatedSamplingRate != NULL) {
6804 *updatedSamplingRate = candidate;
6805 }
6806 return NO_ERROR;
6807 }
6808 }
6809 // But if we have to up-sample from a lower sampling rate, that's OK.
6810 if (maxBelow >= 0) {
6811 candidate = mSamplingRates[maxBelow];
6812 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6813 if (updatedSamplingRate != NULL) {
6814 *updatedSamplingRate = candidate;
6815 }
6816 return NO_ERROR;
6817 }
6818 }
6819 // leave updatedSamplingRate unmodified
6820 return BAD_VALUE;
6821}
6822
6823status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6824{
Eric Laurent0daea392014-12-04 19:14:54 -08006825 if (mChannelMasks.isEmpty()) {
6826 return NO_ERROR;
6827 }
6828
Glenn Kastencbd48022014-07-24 13:46:44 -07006829 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006830 if (mChannelMasks[i] == channelMask) {
6831 return NO_ERROR;
6832 }
6833 }
6834 return BAD_VALUE;
6835}
6836
Glenn Kastencbd48022014-07-24 13:46:44 -07006837status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6838 const
6839{
Eric Laurent0daea392014-12-04 19:14:54 -08006840 if (mChannelMasks.isEmpty()) {
6841 return NO_ERROR;
6842 }
6843
Glenn Kastencbd48022014-07-24 13:46:44 -07006844 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6845 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6846 // FIXME Does not handle multi-channel automatic conversions yet
6847 audio_channel_mask_t supported = mChannelMasks[i];
6848 if (supported == channelMask) {
6849 return NO_ERROR;
6850 }
6851 if (isRecordThread) {
6852 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6853 // FIXME Abstract this out to a table.
6854 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6855 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6856 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6857 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6858 return NO_ERROR;
6859 }
6860 }
6861 }
6862 return BAD_VALUE;
6863}
6864
Eric Laurenta121f902014-06-03 13:32:54 -07006865status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6866{
Eric Laurent0daea392014-12-04 19:14:54 -08006867 if (mFormats.isEmpty()) {
6868 return NO_ERROR;
6869 }
6870
Eric Laurenta121f902014-06-03 13:32:54 -07006871 for (size_t i = 0; i < mFormats.size(); i ++) {
6872 if (mFormats[i] == format) {
6873 return NO_ERROR;
6874 }
6875 }
6876 return BAD_VALUE;
6877}
6878
Eric Laurent1e693b52014-07-09 15:03:28 -07006879
6880uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6881{
6882 // special case for uninitialized dynamic profile
6883 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6884 return 0;
6885 }
6886
Eric Laurent828bcff2014-09-07 12:26:06 -07006887 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6888 // channel count / sampling rate combination chosen will be supported by the connected
6889 // sink
6890 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6891 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6892 uint32_t samplingRate = UINT_MAX;
6893 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6894 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6895 samplingRate = mSamplingRates[i];
6896 }
6897 }
6898 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6899 }
6900
Eric Laurent1e693b52014-07-09 15:03:28 -07006901 uint32_t samplingRate = 0;
6902 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6903
6904 // For mixed output and inputs, use max mixer sampling rates. Do not
6905 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006906 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006907 maxRate = UINT_MAX;
6908 }
6909 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6910 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6911 samplingRate = mSamplingRates[i];
6912 }
6913 }
6914 return samplingRate;
6915}
6916
6917audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6918{
6919 // special case for uninitialized dynamic profile
6920 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6921 return AUDIO_CHANNEL_NONE;
6922 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006923 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006924
6925 // For direct outputs, pick minimum channel count: this helps ensuring that the
6926 // channel count / sampling rate combination chosen will be supported by the connected
6927 // sink
6928 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6929 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6930 uint32_t channelCount = UINT_MAX;
6931 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6932 uint32_t cnlCount;
6933 if (mUseInChannelMask) {
6934 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6935 } else {
6936 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6937 }
6938 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6939 channelMask = mChannelMasks[i];
6940 channelCount = cnlCount;
6941 }
6942 }
6943 return channelMask;
6944 }
6945
Eric Laurent1e693b52014-07-09 15:03:28 -07006946 uint32_t channelCount = 0;
6947 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6948
6949 // For mixed output and inputs, use max mixer channel count. Do not
6950 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006951 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006952 maxCount = UINT_MAX;
6953 }
6954 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6955 uint32_t cnlCount;
6956 if (mUseInChannelMask) {
6957 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6958 } else {
6959 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6960 }
6961 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6962 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006963 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006964 }
6965 }
6966 return channelMask;
6967}
6968
Andy Hung9a605382014-07-28 16:16:31 -07006969/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006970const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6971 AUDIO_FORMAT_DEFAULT,
6972 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006973 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006974 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006975 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006976 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006977};
6978
6979int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6980 audio_format_t format2)
6981{
6982 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6983 // compressed format and better than any PCM format. This is by design of pickFormat()
6984 if (!audio_is_linear_pcm(format1)) {
6985 if (!audio_is_linear_pcm(format2)) {
6986 return 0;
6987 }
6988 return 1;
6989 }
6990 if (!audio_is_linear_pcm(format2)) {
6991 return -1;
6992 }
6993
6994 int index1 = -1, index2 = -1;
6995 for (size_t i = 0;
6996 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6997 i ++) {
6998 if (sPcmFormatCompareTable[i] == format1) {
6999 index1 = i;
7000 }
7001 if (sPcmFormatCompareTable[i] == format2) {
7002 index2 = i;
7003 }
7004 }
7005 // format1 not found => index1 < 0 => format2 > format1
7006 // format2 not found => index2 < 0 => format2 < format1
7007 return index1 - index2;
7008}
7009
7010audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
7011{
7012 // special case for uninitialized dynamic profile
7013 if (mFormats.size() == 1 && mFormats[0] == 0) {
7014 return AUDIO_FORMAT_DEFAULT;
7015 }
7016
7017 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07007018 audio_format_t bestFormat =
7019 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
7020 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07007021 // For mixed output and inputs, use best mixer output format. Do not
7022 // limit format otherwise
7023 if ((mType != AUDIO_PORT_TYPE_MIX) ||
7024 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07007025 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007026 bestFormat = AUDIO_FORMAT_INVALID;
7027 }
7028
7029 for (size_t i = 0; i < mFormats.size(); i ++) {
7030 if ((compareFormats(mFormats[i], format) > 0) &&
7031 (compareFormats(mFormats[i], bestFormat) <= 0)) {
7032 format = mFormats[i];
7033 }
7034 }
7035 return format;
7036}
7037
Eric Laurenta121f902014-06-03 13:32:54 -07007038status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
7039 int index) const
7040{
7041 if (index < 0 || (size_t)index >= mGains.size()) {
7042 return BAD_VALUE;
7043 }
7044 return mGains[index]->checkConfig(gainConfig);
7045}
7046
Eric Laurent1afeecb2014-05-14 08:52:28 -07007047void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
7048{
7049 const size_t SIZE = 256;
7050 char buffer[SIZE];
7051 String8 result;
7052
7053 if (mName.size() != 0) {
7054 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
7055 result.append(buffer);
7056 }
7057
7058 if (mSamplingRates.size() != 0) {
7059 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
7060 result.append(buffer);
7061 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007062 if (i == 0 && mSamplingRates[i] == 0) {
7063 snprintf(buffer, SIZE, "Dynamic");
7064 } else {
7065 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7066 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007067 result.append(buffer);
7068 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7069 }
7070 result.append("\n");
7071 }
7072
7073 if (mChannelMasks.size() != 0) {
7074 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7075 result.append(buffer);
7076 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007077 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7078
7079 if (i == 0 && mChannelMasks[i] == 0) {
7080 snprintf(buffer, SIZE, "Dynamic");
7081 } else {
7082 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7083 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007084 result.append(buffer);
7085 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7086 }
7087 result.append("\n");
7088 }
7089
7090 if (mFormats.size() != 0) {
7091 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7092 result.append(buffer);
7093 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007094 const char *formatStr = enumToString(sFormatNameToEnumTable,
7095 ARRAY_SIZE(sFormatNameToEnumTable),
7096 mFormats[i]);
7097 if (i == 0 && strcmp(formatStr, "") == 0) {
7098 snprintf(buffer, SIZE, "Dynamic");
7099 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07007100 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07007101 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007102 result.append(buffer);
7103 result.append(i == (mFormats.size() - 1) ? "" : ", ");
7104 }
7105 result.append("\n");
7106 }
7107 write(fd, result.string(), result.size());
7108 if (mGains.size() != 0) {
7109 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7110 write(fd, buffer, strlen(buffer) + 1);
7111 result.append(buffer);
7112 for (size_t i = 0; i < mGains.size(); i++) {
7113 mGains[i]->dump(fd, spaces + 2, i);
7114 }
7115 }
7116}
7117
7118// --- AudioGain class implementation
7119
Eric Laurenta121f902014-06-03 13:32:54 -07007120AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07007121{
Eric Laurenta121f902014-06-03 13:32:54 -07007122 mIndex = index;
7123 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007124 memset(&mGain, 0, sizeof(struct audio_gain));
7125}
7126
Eric Laurenta121f902014-06-03 13:32:54 -07007127void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7128{
7129 config->index = mIndex;
7130 config->mode = mGain.mode;
7131 config->channel_mask = mGain.channel_mask;
7132 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7133 config->values[0] = mGain.default_value;
7134 } else {
7135 uint32_t numValues;
7136 if (mUseInChannelMask) {
7137 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7138 } else {
7139 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7140 }
7141 for (size_t i = 0; i < numValues; i++) {
7142 config->values[i] = mGain.default_value;
7143 }
7144 }
7145 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7146 config->ramp_duration_ms = mGain.min_ramp_ms;
7147 }
7148}
7149
7150status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7151{
7152 if ((config->mode & ~mGain.mode) != 0) {
7153 return BAD_VALUE;
7154 }
7155 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7156 if ((config->values[0] < mGain.min_value) ||
7157 (config->values[0] > mGain.max_value)) {
7158 return BAD_VALUE;
7159 }
7160 } else {
7161 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7162 return BAD_VALUE;
7163 }
7164 uint32_t numValues;
7165 if (mUseInChannelMask) {
7166 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7167 } else {
7168 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7169 }
7170 for (size_t i = 0; i < numValues; i++) {
7171 if ((config->values[i] < mGain.min_value) ||
7172 (config->values[i] > mGain.max_value)) {
7173 return BAD_VALUE;
7174 }
7175 }
7176 }
7177 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7178 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7179 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7180 return BAD_VALUE;
7181 }
7182 }
7183 return NO_ERROR;
7184}
7185
Eric Laurent1afeecb2014-05-14 08:52:28 -07007186void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7187{
7188 const size_t SIZE = 256;
7189 char buffer[SIZE];
7190 String8 result;
7191
7192 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7193 result.append(buffer);
7194 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7195 result.append(buffer);
7196 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7197 result.append(buffer);
7198 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7199 result.append(buffer);
7200 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7201 result.append(buffer);
7202 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7203 result.append(buffer);
7204 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7205 result.append(buffer);
7206 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7207 result.append(buffer);
7208 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7209 result.append(buffer);
7210
7211 write(fd, result.string(), result.size());
7212}
7213
Eric Laurent1f2f2232014-06-02 12:01:23 -07007214// --- AudioPortConfig class implementation
7215
7216AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7217{
7218 mSamplingRate = 0;
7219 mChannelMask = AUDIO_CHANNEL_NONE;
7220 mFormat = AUDIO_FORMAT_INVALID;
7221 mGain.index = -1;
7222}
7223
Eric Laurenta121f902014-06-03 13:32:54 -07007224status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7225 const struct audio_port_config *config,
7226 struct audio_port_config *backupConfig)
7227{
7228 struct audio_port_config localBackupConfig;
7229 status_t status = NO_ERROR;
7230
7231 localBackupConfig.config_mask = config->config_mask;
7232 toAudioPortConfig(&localBackupConfig);
7233
Marco Nelissen961ec212014-08-25 15:58:39 -07007234 sp<AudioPort> audioport = getAudioPort();
7235 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007236 status = NO_INIT;
7237 goto exit;
7238 }
7239 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007240 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007241 if (status != NO_ERROR) {
7242 goto exit;
7243 }
7244 mSamplingRate = config->sample_rate;
7245 }
7246 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007247 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007248 if (status != NO_ERROR) {
7249 goto exit;
7250 }
7251 mChannelMask = config->channel_mask;
7252 }
7253 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007254 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007255 if (status != NO_ERROR) {
7256 goto exit;
7257 }
7258 mFormat = config->format;
7259 }
7260 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007261 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007262 if (status != NO_ERROR) {
7263 goto exit;
7264 }
7265 mGain = config->gain;
7266 }
7267
7268exit:
7269 if (status != NO_ERROR) {
7270 applyAudioPortConfig(&localBackupConfig);
7271 }
7272 if (backupConfig != NULL) {
7273 *backupConfig = localBackupConfig;
7274 }
7275 return status;
7276}
7277
Eric Laurent1f2f2232014-06-02 12:01:23 -07007278void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7279 struct audio_port_config *dstConfig,
7280 const struct audio_port_config *srcConfig) const
7281{
7282 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7283 dstConfig->sample_rate = mSamplingRate;
7284 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7285 dstConfig->sample_rate = srcConfig->sample_rate;
7286 }
7287 } else {
7288 dstConfig->sample_rate = 0;
7289 }
7290 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7291 dstConfig->channel_mask = mChannelMask;
7292 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7293 dstConfig->channel_mask = srcConfig->channel_mask;
7294 }
7295 } else {
7296 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7297 }
7298 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7299 dstConfig->format = mFormat;
7300 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7301 dstConfig->format = srcConfig->format;
7302 }
7303 } else {
7304 dstConfig->format = AUDIO_FORMAT_INVALID;
7305 }
7306 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7307 dstConfig->gain = mGain;
7308 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7309 dstConfig->gain = srcConfig->gain;
7310 }
7311 } else {
7312 dstConfig->gain.index = -1;
7313 }
7314 if (dstConfig->gain.index != -1) {
7315 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7316 } else {
7317 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7318 }
7319}
7320
Eric Laurent1c333e22014-05-20 10:48:17 -07007321// --- IOProfile class implementation
7322
Eric Laurent1afeecb2014-05-14 08:52:28 -07007323AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007324 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007325 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007326{
7327}
7328
Eric Laurente0720872014-03-11 09:30:41 -07007329AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007330{
7331}
7332
7333// checks if the IO profile is compatible with specified parameters.
7334// Sampling rate, format and channel mask must be specified in order to
7335// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007336bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007337 String8 address,
7338 uint32_t samplingRate,
7339 uint32_t *updatedSamplingRate,
7340 audio_format_t format,
7341 audio_channel_mask_t channelMask,
7342 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007343{
Glenn Kastencbd48022014-07-24 13:46:44 -07007344 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7345 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7346 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007347
Eric Laurent275e8e92014-11-30 15:14:47 -08007348 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007349 return false;
7350 }
7351
7352 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007353 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007354 }
7355 uint32_t myUpdatedSamplingRate = samplingRate;
7356 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007357 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007358 }
7359 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7360 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007361 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007362 }
7363
7364 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7365 return false;
7366 }
7367
7368 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7369 checkExactChannelMask(channelMask) != NO_ERROR)) {
7370 return false;
7371 }
7372 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7373 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7374 return false;
7375 }
7376
7377 if (isPlaybackThread && (mFlags & flags) != flags) {
7378 return false;
7379 }
7380 // The only input flag that is allowed to be different is the fast flag.
7381 // An existing fast stream is compatible with a normal track request.
7382 // An existing normal stream is compatible with a fast track request,
7383 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007384 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007385 ~AUDIO_INPUT_FLAG_FAST)) {
7386 return false;
7387 }
7388
7389 if (updatedSamplingRate != NULL) {
7390 *updatedSamplingRate = myUpdatedSamplingRate;
7391 }
7392 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007393}
7394
Eric Laurente0720872014-03-11 09:30:41 -07007395void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007396{
7397 const size_t SIZE = 256;
7398 char buffer[SIZE];
7399 String8 result;
7400
Eric Laurent1afeecb2014-05-14 08:52:28 -07007401 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007402
Eric Laurente552edb2014-03-10 17:42:56 -07007403 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7404 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007405 snprintf(buffer, SIZE, " - devices:\n");
7406 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007407 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007408 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7409 mSupportedDevices[i]->dump(fd, 6, i);
7410 }
Eric Laurente552edb2014-03-10 17:42:56 -07007411}
7412
Eric Laurentd4692962014-05-05 18:13:44 -07007413void AudioPolicyManager::IOProfile::log()
7414{
7415 const size_t SIZE = 256;
7416 char buffer[SIZE];
7417 String8 result;
7418
7419 ALOGV(" - sampling rates: ");
7420 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7421 ALOGV(" %d", mSamplingRates[i]);
7422 }
7423
7424 ALOGV(" - channel masks: ");
7425 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7426 ALOGV(" 0x%04x", mChannelMasks[i]);
7427 }
7428
7429 ALOGV(" - formats: ");
7430 for (size_t i = 0; i < mFormats.size(); i++) {
7431 ALOGV(" 0x%08x", mFormats[i]);
7432 }
7433
7434 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7435 ALOGV(" - flags: 0x%04x\n", mFlags);
7436}
7437
7438
Eric Laurent3a4311c2014-03-17 12:00:47 -07007439// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007440
Eric Laurent1f2f2232014-06-02 12:01:23 -07007441
7442AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7443 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7444 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7445 AUDIO_PORT_ROLE_SOURCE,
7446 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007447 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007448{
Eric Laurenta121f902014-06-03 13:32:54 -07007449 if (mGains.size() > 0) {
7450 mGains[0]->getDefaultConfig(&mGain);
7451 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07007452}
7453
Eric Laurent3a4311c2014-03-17 12:00:47 -07007454bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007455{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007456 // Devices are considered equal if they:
7457 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7458 // - have the same address or one device does not specify the address
7459 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007460 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007461 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007462 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007463 mChannelMask == other->mChannelMask);
7464}
7465
7466void AudioPolicyManager::DeviceVector::refreshTypes()
7467{
Eric Laurent1c333e22014-05-20 10:48:17 -07007468 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007469 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007470 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007471 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007472 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007473}
7474
7475ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7476{
7477 for(size_t i = 0; i < size(); i++) {
7478 if (item->equals(itemAt(i))) {
7479 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007480 }
7481 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007482 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007483}
7484
Eric Laurent3a4311c2014-03-17 12:00:47 -07007485ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007486{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007487 ssize_t ret = indexOf(item);
7488
7489 if (ret < 0) {
7490 ret = SortedVector::add(item);
7491 if (ret >= 0) {
7492 refreshTypes();
7493 }
7494 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007495 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007496 ret = -1;
7497 }
7498 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007499}
7500
Eric Laurent3a4311c2014-03-17 12:00:47 -07007501ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7502{
7503 size_t i;
7504 ssize_t ret = indexOf(item);
7505
7506 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007507 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007508 } else {
7509 ret = SortedVector::removeAt(ret);
7510 if (ret >= 0) {
7511 refreshTypes();
7512 }
7513 }
7514 return ret;
7515}
7516
7517void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7518{
7519 DeviceVector deviceList;
7520
7521 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7522 types &= ~role_bit;
7523
7524 while (types) {
7525 uint32_t i = 31 - __builtin_clz(types);
7526 uint32_t type = 1 << i;
7527 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007528 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007529 }
7530}
7531
Eric Laurent1afeecb2014-05-14 08:52:28 -07007532void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7533 const DeviceVector& declaredDevices)
7534{
7535 char *devName = strtok(name, "|");
7536 while (devName != NULL) {
7537 if (strlen(devName) != 0) {
7538 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7539 ARRAY_SIZE(sDeviceNameToEnumTable),
7540 devName);
7541 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007542 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007543 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7544 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007545 dev->mAddress = String8("0");
7546 }
7547 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007548 } else {
7549 sp<DeviceDescriptor> deviceDesc =
7550 declaredDevices.getDeviceFromName(String8(devName));
7551 if (deviceDesc != 0) {
7552 add(deviceDesc);
7553 }
7554 }
7555 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007556 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007557 }
7558}
7559
Eric Laurent1c333e22014-05-20 10:48:17 -07007560sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7561 audio_devices_t type, String8 address) const
7562{
7563 sp<DeviceDescriptor> device;
7564 for (size_t i = 0; i < size(); i++) {
7565 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007566 if (address == "" || itemAt(i)->mAddress == address) {
7567 device = itemAt(i);
7568 if (itemAt(i)->mAddress == address) {
7569 break;
7570 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007571 }
7572 }
7573 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007574 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007575 type, address.string(), device.get());
7576 return device;
7577}
7578
Eric Laurent6a94d692014-05-20 11:18:06 -07007579sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7580 audio_port_handle_t id) const
7581{
7582 sp<DeviceDescriptor> device;
7583 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007584 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007585 if (itemAt(i)->mId == id) {
7586 device = itemAt(i);
7587 break;
7588 }
7589 }
7590 return device;
7591}
7592
Eric Laurent1c333e22014-05-20 10:48:17 -07007593AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7594 audio_devices_t type) const
7595{
7596 DeviceVector devices;
7597 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7598 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7599 devices.add(itemAt(i));
7600 type &= ~itemAt(i)->mDeviceType;
7601 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7602 itemAt(i)->mDeviceType, itemAt(i).get());
7603 }
7604 }
7605 return devices;
7606}
7607
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007608AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7609 audio_devices_t type, String8 address) const
7610{
7611 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007612 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007613 if (itemAt(i)->mDeviceType == type) {
7614 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007615 devices.add(itemAt(i));
7616 }
7617 }
7618 }
7619 return devices;
7620}
7621
Eric Laurent1afeecb2014-05-14 08:52:28 -07007622sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7623 const String8& name) const
7624{
7625 sp<DeviceDescriptor> device;
7626 for (size_t i = 0; i < size(); i++) {
7627 if (itemAt(i)->mName == name) {
7628 device = itemAt(i);
7629 break;
7630 }
7631 }
7632 return device;
7633}
7634
Eric Laurent6a94d692014-05-20 11:18:06 -07007635void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7636 struct audio_port_config *dstConfig,
7637 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007638{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007639 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7640 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007641 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007642 }
7643
7644 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7645
Eric Laurent6a94d692014-05-20 11:18:06 -07007646 dstConfig->id = mId;
7647 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007648 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007649 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007650 dstConfig->ext.device.type = mDeviceType;
7651 dstConfig->ext.device.hw_module = mModule->mHandle;
7652 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007653}
7654
7655void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7656{
Eric Laurent83b88082014-06-20 18:31:16 -07007657 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007658 AudioPort::toAudioPort(port);
7659 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007660 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007661 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007662 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007663 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7664}
7665
Eric Laurent1afeecb2014-05-14 08:52:28 -07007666status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007667{
7668 const size_t SIZE = 256;
7669 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007670 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007671
Eric Laurent1afeecb2014-05-14 08:52:28 -07007672 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7673 result.append(buffer);
7674 if (mId != 0) {
7675 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7676 result.append(buffer);
7677 }
7678 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7679 enumToString(sDeviceNameToEnumTable,
7680 ARRAY_SIZE(sDeviceNameToEnumTable),
7681 mDeviceType));
7682 result.append(buffer);
7683 if (mAddress.size() != 0) {
7684 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7685 result.append(buffer);
7686 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007687 write(fd, result.string(), result.size());
7688 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007689
7690 return NO_ERROR;
7691}
7692
Eric Laurent4d416952014-08-10 14:07:09 -07007693status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7694{
7695 const size_t SIZE = 256;
7696 char buffer[SIZE];
7697 String8 result;
7698
7699
7700 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7701 result.append(buffer);
7702 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7703 result.append(buffer);
7704 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7705 result.append(buffer);
7706 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7707 result.append(buffer);
7708 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7709 result.append(buffer);
7710 for (size_t i = 0; i < mPatch.num_sources; i++) {
7711 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7712 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7713 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7714 ARRAY_SIZE(sDeviceNameToEnumTable),
7715 mPatch.sources[i].ext.device.type));
7716 } else {
7717 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7718 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7719 }
7720 result.append(buffer);
7721 }
7722 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7723 result.append(buffer);
7724 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7725 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7726 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7727 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7728 ARRAY_SIZE(sDeviceNameToEnumTable),
7729 mPatch.sinks[i].ext.device.type));
7730 } else {
7731 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7732 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7733 }
7734 result.append(buffer);
7735 }
7736
7737 write(fd, result.string(), result.size());
7738 return NO_ERROR;
7739}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007740
7741// --- audio_policy.conf file parsing
7742
Eric Laurent5dbe4712014-09-19 19:04:57 -07007743uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007744{
7745 uint32_t flag = 0;
7746
7747 // it is OK to cast name to non const here as we are not going to use it after
7748 // strtok() modifies it
7749 char *flagName = strtok(name, "|");
7750 while (flagName != NULL) {
7751 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007752 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7753 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007754 flagName);
7755 }
7756 flagName = strtok(NULL, "|");
7757 }
7758 //force direct flag if offload flag is set: offloading implies a direct output stream
7759 // and all common behaviors are driven by checking only the direct flag
7760 // this should normally be set appropriately in the policy configuration file
7761 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7762 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7763 }
7764
Eric Laurent5dbe4712014-09-19 19:04:57 -07007765 return flag;
7766}
7767
7768uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7769{
7770 uint32_t flag = 0;
7771
7772 // it is OK to cast name to non const here as we are not going to use it after
7773 // strtok() modifies it
7774 char *flagName = strtok(name, "|");
7775 while (flagName != NULL) {
7776 if (strlen(flagName) != 0) {
7777 flag |= stringToEnum(sInputFlagNameToEnumTable,
7778 ARRAY_SIZE(sInputFlagNameToEnumTable),
7779 flagName);
7780 }
7781 flagName = strtok(NULL, "|");
7782 }
7783 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007784}
7785
Eric Laurente0720872014-03-11 09:30:41 -07007786audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007787{
7788 uint32_t device = 0;
7789
7790 char *devName = strtok(name, "|");
7791 while (devName != NULL) {
7792 if (strlen(devName) != 0) {
7793 device |= stringToEnum(sDeviceNameToEnumTable,
7794 ARRAY_SIZE(sDeviceNameToEnumTable),
7795 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007796 }
Eric Laurente552edb2014-03-10 17:42:56 -07007797 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007798 }
Eric Laurente552edb2014-03-10 17:42:56 -07007799 return device;
7800}
7801
Eric Laurente0720872014-03-11 09:30:41 -07007802void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007803{
Eric Laurente552edb2014-03-10 17:42:56 -07007804 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007805 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007806 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007807
Eric Laurent1afeecb2014-05-14 08:52:28 -07007808 node = config_find(root, DEVICES_TAG);
7809 if (node != NULL) {
7810 node = node->first_child;
7811 while (node) {
7812 ALOGV("loadHwModule() loading device %s", node->name);
7813 status_t tmpStatus = module->loadDevice(node);
7814 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7815 status = tmpStatus;
7816 }
7817 node = node->next;
7818 }
7819 }
7820 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007821 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007822 node = node->first_child;
7823 while (node) {
7824 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007825 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007826 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7827 status = tmpStatus;
7828 }
7829 node = node->next;
7830 }
7831 }
7832 node = config_find(root, INPUTS_TAG);
7833 if (node != NULL) {
7834 node = node->first_child;
7835 while (node) {
7836 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007837 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007838 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7839 status = tmpStatus;
7840 }
7841 node = node->next;
7842 }
7843 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007844 loadGlobalConfig(root, module);
7845
Eric Laurente552edb2014-03-10 17:42:56 -07007846 if (status == NO_ERROR) {
7847 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007848 }
7849}
7850
Eric Laurente0720872014-03-11 09:30:41 -07007851void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007852{
7853 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7854 if (node == NULL) {
7855 return;
7856 }
7857
7858 node = node->first_child;
7859 while (node) {
7860 ALOGV("loadHwModules() loading module %s", node->name);
7861 loadHwModule(node);
7862 node = node->next;
7863 }
7864}
7865
Eric Laurent1f2f2232014-06-02 12:01:23 -07007866void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007867{
7868 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007869
Eric Laurente552edb2014-03-10 17:42:56 -07007870 if (node == NULL) {
7871 return;
7872 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007873 DeviceVector declaredDevices;
7874 if (module != NULL) {
7875 declaredDevices = module->mDeclaredDevices;
7876 }
7877
Eric Laurente552edb2014-03-10 17:42:56 -07007878 node = node->first_child;
7879 while (node) {
7880 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007881 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7882 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007883 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7884 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007885 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007886 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007887 ARRAY_SIZE(sDeviceNameToEnumTable),
7888 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007889 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007890 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007891 } else {
7892 ALOGW("loadGlobalConfig() default device not specified");
7893 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007894 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007895 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007896 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7897 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007898 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007899 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7900 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7901 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007902 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7903 uint32_t major, minor;
7904 sscanf((char *)node->value, "%u.%u", &major, &minor);
7905 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7906 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7907 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007908 }
7909 node = node->next;
7910 }
7911}
7912
Eric Laurente0720872014-03-11 09:30:41 -07007913status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007914{
7915 cnode *root;
7916 char *data;
7917
7918 data = (char *)load_file(path, NULL);
7919 if (data == NULL) {
7920 return -ENODEV;
7921 }
7922 root = config_node("", "");
7923 config_load(root, data);
7924
Eric Laurente552edb2014-03-10 17:42:56 -07007925 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007926 // legacy audio_policy.conf files have one global_configuration section
7927 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007928 config_free(root);
7929 free(root);
7930 free(data);
7931
7932 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7933
7934 return NO_ERROR;
7935}
7936
Eric Laurente0720872014-03-11 09:30:41 -07007937void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007938{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007939 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007940 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007941 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7942 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007943 mAvailableOutputDevices.add(mDefaultOutputDevice);
7944 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007945
7946 module = new HwModule("primary");
7947
Eric Laurent1afeecb2014-05-14 08:52:28 -07007948 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007949 profile->mSamplingRates.add(44100);
7950 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7951 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007952 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007953 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7954 module->mOutputProfiles.add(profile);
7955
Eric Laurent1afeecb2014-05-14 08:52:28 -07007956 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007957 profile->mSamplingRates.add(8000);
7958 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7959 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007960 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007961 module->mInputProfiles.add(profile);
7962
7963 mHwModules.add(module);
7964}
7965
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007966audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7967{
7968 // flags to stream type mapping
7969 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7970 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7971 }
7972 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7973 return AUDIO_STREAM_BLUETOOTH_SCO;
7974 }
7975
7976 // usage to stream type mapping
7977 switch (attr->usage) {
7978 case AUDIO_USAGE_MEDIA:
7979 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007980 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7981 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007982 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007983 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7984 return AUDIO_STREAM_ALARM;
7985 }
7986 if (isStreamActive(AUDIO_STREAM_RING)) {
7987 return AUDIO_STREAM_RING;
7988 }
7989 if (isInCall()) {
7990 return AUDIO_STREAM_VOICE_CALL;
7991 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08007992 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007993 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7994 return AUDIO_STREAM_SYSTEM;
7995 case AUDIO_USAGE_VOICE_COMMUNICATION:
7996 return AUDIO_STREAM_VOICE_CALL;
7997
7998 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7999 return AUDIO_STREAM_DTMF;
8000
8001 case AUDIO_USAGE_ALARM:
8002 return AUDIO_STREAM_ALARM;
8003 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8004 return AUDIO_STREAM_RING;
8005
8006 case AUDIO_USAGE_NOTIFICATION:
8007 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8008 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8009 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8010 case AUDIO_USAGE_NOTIFICATION_EVENT:
8011 return AUDIO_STREAM_NOTIFICATION;
8012
8013 case AUDIO_USAGE_UNKNOWN:
8014 default:
8015 return AUDIO_STREAM_MUSIC;
8016 }
8017}
Eric Laurente83b55d2014-11-14 10:06:21 -08008018
8019bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
8020 // has flags that map to a strategy?
8021 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8022 return true;
8023 }
8024
8025 // has known usage?
8026 switch (paa->usage) {
8027 case AUDIO_USAGE_UNKNOWN:
8028 case AUDIO_USAGE_MEDIA:
8029 case AUDIO_USAGE_VOICE_COMMUNICATION:
8030 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8031 case AUDIO_USAGE_ALARM:
8032 case AUDIO_USAGE_NOTIFICATION:
8033 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8034 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8035 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8036 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8037 case AUDIO_USAGE_NOTIFICATION_EVENT:
8038 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8039 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8040 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8041 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008042 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08008043 break;
8044 default:
8045 return false;
8046 }
8047 return true;
8048}
8049
Eric Laurente552edb2014-03-10 17:42:56 -07008050}; // namespace android