blob: 76acc41ec317105d83c30c98ab46f31a50622660 [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
214
Eric Laurente0720872014-03-11 09:30:41 -0700215status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700216 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700217 const char *device_address)
218{
Eric Laurent22226012014-08-01 17:00:54 -0700219 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700220 // handle legacy remote submix case where the address was not always specified
221 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
222 address = String8("0");
223 }
Eric Laurente552edb2014-03-10 17:42:56 -0700224
Eric Laurent22226012014-08-01 17:00:54 -0700225 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
226 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700227
228 // connect/disconnect only 1 device at a time
229 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
230
Eric Laurente552edb2014-03-10 17:42:56 -0700231 // handle output devices
232 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700233 SortedVector <audio_io_handle_t> outputs;
234
Eric Laurent1afeecb2014-05-14 08:52:28 -0700235 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
236 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
238
Eric Laurente552edb2014-03-10 17:42:56 -0700239 // save a copy of the opened output descriptors before any output is opened or closed
240 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
241 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700242 switch (state)
243 {
244 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700245 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700246 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700247 ALOGW("setDeviceConnectionState() device already connected: %x", device);
248 return INVALID_OPERATION;
249 }
250 ALOGV("setDeviceConnectionState() connecting device %x", device);
251
Eric Laurente552edb2014-03-10 17:42:56 -0700252 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 index = mAvailableOutputDevices.add(devDesc);
254 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700255 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700256 if (module == 0) {
257 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
258 device);
259 mAvailableOutputDevices.remove(devDesc);
260 return INVALID_OPERATION;
261 }
262 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700263 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 } else {
265 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700266 }
267
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700268 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700269 mAvailableOutputDevices.remove(devDesc);
270 return INVALID_OPERATION;
271 }
272 // outputs should never be empty here
273 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
274 "checkOutputsForDevice() returned no outputs but status OK");
275 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
276 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700277 break;
278 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700279 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700280 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700281 ALOGW("setDeviceConnectionState() device not connected: %x", device);
282 return INVALID_OPERATION;
283 }
284
Paul McLean5c477aa2014-08-20 16:47:57 -0700285 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
286
287 // Set Disconnect to HALs
288 AudioParameter param = AudioParameter(address);
289 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
290 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
291
Eric Laurente552edb2014-03-10 17:42:56 -0700292 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700293 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700294
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700295 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700296 } break;
297
298 default:
299 ALOGE("setDeviceConnectionState() invalid state: %x", state);
300 return BAD_VALUE;
301 }
302
Eric Laurent3a4311c2014-03-17 12:00:47 -0700303 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
304 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700305 checkA2dpSuspend();
306 checkOutputForAllStrategies();
307 // outputs must be closed after checkOutputForAllStrategies() is executed
308 if (!outputs.isEmpty()) {
309 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700310 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700311 // close unused outputs after device disconnection or direct outputs that have been
312 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700313 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700314 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
315 (desc->mDirectOpenCount == 0))) {
316 closeOutput(outputs[i]);
317 }
318 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700319 // check again after closing A2DP output to reset mA2dpSuspended if needed
320 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700321 }
322
323 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 if (mPhoneState == AUDIO_MODE_IN_CALL) {
325 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
326 updateCallRouting(newDevice);
327 }
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700329 audio_io_handle_t output = mOutputs.keyAt(i);
330 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
331 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
332 true /*fromCache*/);
333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
336 bool force = !mOutputs.valueAt(i)->isDuplicated()
337 && (!deviceDistinguishesOnAddress(device)
338 // always force when disconnecting (a non-duplicated device)
339 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
340 setOutputDevice(output, newDevice, force, 0);
341 }
Eric Laurente552edb2014-03-10 17:42:56 -0700342 }
343
Eric Laurent72aa32f2014-05-30 18:51:48 -0700344 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700345 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700346 } // end if is output device
347
Eric Laurente552edb2014-03-10 17:42:56 -0700348 // handle input devices
349 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700350 SortedVector <audio_io_handle_t> inputs;
351
Eric Laurent1afeecb2014-05-14 08:52:28 -0700352 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
353 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700355 switch (state)
356 {
357 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700358 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700360 ALOGW("setDeviceConnectionState() device already connected: %d", device);
361 return INVALID_OPERATION;
362 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700363 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700364 if (module == NULL) {
365 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
366 device);
367 return INVALID_OPERATION;
368 }
Eric Laurentd4692962014-05-05 18:13:44 -0700369 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
370 return INVALID_OPERATION;
371 }
372
Eric Laurent3a4311c2014-03-17 12:00:47 -0700373 index = mAvailableInputDevices.add(devDesc);
374 if (index >= 0) {
375 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700376 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700377 } else {
378 return NO_MEMORY;
379 }
Eric Laurentd4692962014-05-05 18:13:44 -0700380 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700381
382 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700383 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700384 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700385 ALOGW("setDeviceConnectionState() device not connected: %d", device);
386 return INVALID_OPERATION;
387 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700388
389 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
390
391 // Set Disconnect to HALs
392 AudioParameter param = AudioParameter(address);
393 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
394 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
395
Eric Laurentd4692962014-05-05 18:13:44 -0700396 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700397 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700398
Eric Laurentd4692962014-05-05 18:13:44 -0700399 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700400
401 default:
402 ALOGE("setDeviceConnectionState() invalid state: %x", state);
403 return BAD_VALUE;
404 }
405
Eric Laurentd4692962014-05-05 18:13:44 -0700406 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700407
Eric Laurentc2730ba2014-07-20 15:47:07 -0700408 if (mPhoneState == AUDIO_MODE_IN_CALL) {
409 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
410 updateCallRouting(newDevice);
411 }
412
Eric Laurentb52c1522014-05-20 11:27:36 -0700413 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700414 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700415 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700416
417 ALOGW("setDeviceConnectionState() invalid device: %x", device);
418 return BAD_VALUE;
419}
420
Eric Laurente0720872014-03-11 09:30:41 -0700421audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700422 const char *device_address)
423{
Eric Laurent3b73df72014-03-11 09:06:29 -0700424 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700425 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700426 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700427 // handle legacy remote submix case where the address was not always specified
428 if (deviceDistinguishesOnAddress(device) && (devDesc->mAddress.length() == 0)) {
429 devDesc->mAddress = String8("0");
430 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700431 ssize_t index;
432 DeviceVector *deviceVector;
433
Eric Laurente552edb2014-03-10 17:42:56 -0700434 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700435 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700436 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700437 deviceVector = &mAvailableInputDevices;
438 } else {
439 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
440 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700441 }
442
Eric Laurent3a4311c2014-03-17 12:00:47 -0700443 index = deviceVector->indexOf(devDesc);
444 if (index >= 0) {
445 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
446 } else {
447 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
448 }
Eric Laurente552edb2014-03-10 17:42:56 -0700449}
450
Eric Laurentc2730ba2014-07-20 15:47:07 -0700451void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
452{
453 bool createTxPatch = false;
454 struct audio_patch patch;
455 patch.num_sources = 1;
456 patch.num_sinks = 1;
457 status_t status;
458 audio_patch_handle_t afPatchHandle;
459 DeviceVector deviceList;
460
461 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
462 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
463
464 // release existing RX patch if any
465 if (mCallRxPatch != 0) {
466 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
467 mCallRxPatch.clear();
468 }
469 // release TX patch if any
470 if (mCallTxPatch != 0) {
471 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
472 mCallTxPatch.clear();
473 }
474
475 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
476 // via setOutputDevice() on primary output.
477 // Otherwise, create two audio patches for TX and RX path.
478 if (availablePrimaryOutputDevices() & rxDevice) {
479 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
480 // If the TX device is also on the primary HW module, setOutputDevice() will take care
481 // of it due to legacy implementation. If not, create a patch.
482 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
483 == AUDIO_DEVICE_NONE) {
484 createTxPatch = true;
485 }
486 } else {
487 // create RX path audio patch
488 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
489 ALOG_ASSERT(!deviceList.isEmpty(),
490 "updateCallRouting() selected device not in output device list");
491 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
492 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
493 ALOG_ASSERT(!deviceList.isEmpty(),
494 "updateCallRouting() no telephony RX device");
495 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
496
497 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
498 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
499
500 // request to reuse existing output stream if one is already opened to reach the RX device
501 SortedVector<audio_io_handle_t> outputs =
502 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700503 audio_io_handle_t output = selectOutput(outputs,
504 AUDIO_OUTPUT_FLAG_NONE,
505 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700506 if (output != AUDIO_IO_HANDLE_NONE) {
507 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
508 ALOG_ASSERT(!outputDesc->isDuplicated(),
509 "updateCallRouting() RX device output is duplicated");
510 outputDesc->toAudioPortConfig(&patch.sources[1]);
511 patch.num_sources = 2;
512 }
513
514 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
515 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
516 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
517 status);
518 if (status == NO_ERROR) {
519 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
520 &patch, mUidCached);
521 mCallRxPatch->mAfPatchHandle = afPatchHandle;
522 mCallRxPatch->mUid = mUidCached;
523 }
524 createTxPatch = true;
525 }
526 if (createTxPatch) {
527
528 struct audio_patch patch;
529 patch.num_sources = 1;
530 patch.num_sinks = 1;
531 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
532 ALOG_ASSERT(!deviceList.isEmpty(),
533 "updateCallRouting() selected device not in input device list");
534 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
535 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
536 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
537 ALOG_ASSERT(!deviceList.isEmpty(),
538 "updateCallRouting() no telephony TX device");
539 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
540 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
541
542 SortedVector<audio_io_handle_t> outputs =
543 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700544 audio_io_handle_t output = selectOutput(outputs,
545 AUDIO_OUTPUT_FLAG_NONE,
546 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700547 // request to reuse existing output stream if one is already opened to reach the TX
548 // path output device
549 if (output != AUDIO_IO_HANDLE_NONE) {
550 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
551 ALOG_ASSERT(!outputDesc->isDuplicated(),
552 "updateCallRouting() RX device output is duplicated");
553 outputDesc->toAudioPortConfig(&patch.sources[1]);
554 patch.num_sources = 2;
555 }
556
557 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
558 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
559 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
560 status);
561 if (status == NO_ERROR) {
562 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
563 &patch, mUidCached);
564 mCallTxPatch->mAfPatchHandle = afPatchHandle;
565 mCallTxPatch->mUid = mUidCached;
566 }
567 }
568}
569
Eric Laurente0720872014-03-11 09:30:41 -0700570void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700571{
572 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700573 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700574 ALOGW("setPhoneState() invalid state %d", state);
575 return;
576 }
577
578 if (state == mPhoneState ) {
579 ALOGW("setPhoneState() setting same state %d", state);
580 return;
581 }
582
583 // if leaving call state, handle special case of active streams
584 // pertaining to sonification strategy see handleIncallSonification()
585 if (isInCall()) {
586 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700587 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800588 if (stream == AUDIO_STREAM_PATCH) {
589 continue;
590 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700591 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700592 }
593 }
594
595 // store previous phone state for management of sonification strategy below
596 int oldState = mPhoneState;
597 mPhoneState = state;
598 bool force = false;
599
600 // are we entering or starting a call
601 if (!isStateInCall(oldState) && isStateInCall(state)) {
602 ALOGV(" Entering call in setPhoneState()");
603 // force routing command to audio hardware when starting a call
604 // even if no device change is needed
605 force = true;
606 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
607 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
608 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
609 }
610 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
611 ALOGV(" Exiting call in setPhoneState()");
612 // force routing command to audio hardware when exiting 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_DTMF][j];
618 }
619 } else if (isStateInCall(state) && (state != oldState)) {
620 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
621 // force routing command to audio hardware when switching between telephony and VoIP
622 // even if no device change is needed
623 force = true;
624 }
625
626 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700627 checkA2dpSuspend();
628 checkOutputForAllStrategies();
629 updateDevicesAndOutputs();
630
Eric Laurent1f2f2232014-06-02 12:01:23 -0700631 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700632
Eric Laurente552edb2014-03-10 17:42:56 -0700633 int delayMs = 0;
634 if (isStateInCall(state)) {
635 nsecs_t sysTime = systemTime();
636 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700637 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700638 // mute media and sonification strategies and delay device switch by the largest
639 // latency of any output where either strategy is active.
640 // This avoid sending the ring tone or music tail into the earpiece or headset.
641 if ((desc->isStrategyActive(STRATEGY_MEDIA,
642 SONIFICATION_HEADSET_MUSIC_DELAY,
643 sysTime) ||
644 desc->isStrategyActive(STRATEGY_SONIFICATION,
645 SONIFICATION_HEADSET_MUSIC_DELAY,
646 sysTime)) &&
647 (delayMs < (int)desc->mLatency*2)) {
648 delayMs = desc->mLatency*2;
649 }
650 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
651 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
652 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
653 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
654 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
655 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
656 }
657 }
658
Eric Laurentc2730ba2014-07-20 15:47:07 -0700659 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
660 // the device returned is not necessarily reachable via this output
661 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
662 // force routing command to audio hardware when ending call
663 // even if no device change is needed
664 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
665 rxDevice = hwOutputDesc->device();
666 }
Eric Laurente552edb2014-03-10 17:42:56 -0700667
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668 if (state == AUDIO_MODE_IN_CALL) {
669 updateCallRouting(rxDevice, delayMs);
670 } else if (oldState == AUDIO_MODE_IN_CALL) {
671 if (mCallRxPatch != 0) {
672 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
673 mCallRxPatch.clear();
674 }
675 if (mCallTxPatch != 0) {
676 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
677 mCallTxPatch.clear();
678 }
679 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
680 } else {
681 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
682 }
Eric Laurente552edb2014-03-10 17:42:56 -0700683 // if entering in call state, handle special case of active streams
684 // pertaining to sonification strategy see handleIncallSonification()
685 if (isStateInCall(state)) {
686 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700687 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800688 if (stream == AUDIO_STREAM_PATCH) {
689 continue;
690 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700691 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700692 }
693 }
694
695 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700696 if (state == AUDIO_MODE_RINGTONE &&
697 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700698 mLimitRingtoneVolume = true;
699 } else {
700 mLimitRingtoneVolume = false;
701 }
702}
703
Eric Laurente0720872014-03-11 09:30:41 -0700704void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700705 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700706{
707 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
708
709 bool forceVolumeReeval = false;
710 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700711 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
712 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
713 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700714 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
715 return;
716 }
717 forceVolumeReeval = true;
718 mForceUse[usage] = config;
719 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700720 case AUDIO_POLICY_FORCE_FOR_MEDIA:
721 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
722 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
723 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
724 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800725 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700726 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
727 return;
728 }
729 mForceUse[usage] = config;
730 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700731 case AUDIO_POLICY_FORCE_FOR_RECORD:
732 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
733 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700734 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
735 return;
736 }
737 mForceUse[usage] = config;
738 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700739 case AUDIO_POLICY_FORCE_FOR_DOCK:
740 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
741 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
742 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
743 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
744 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700745 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
746 }
747 forceVolumeReeval = true;
748 mForceUse[usage] = config;
749 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700750 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
751 if (config != AUDIO_POLICY_FORCE_NONE &&
752 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700753 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
754 }
755 forceVolumeReeval = true;
756 mForceUse[usage] = config;
757 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900758 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
759 if (config != AUDIO_POLICY_FORCE_NONE &&
760 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
761 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
762 }
763 mForceUse[usage] = config;
764 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700765 default:
766 ALOGW("setForceUse() invalid usage %d", usage);
767 break;
768 }
769
770 // check for device and output changes triggered by new force usage
771 checkA2dpSuspend();
772 checkOutputForAllStrategies();
773 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700774 if (mPhoneState == AUDIO_MODE_IN_CALL) {
775 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
776 updateCallRouting(newDevice);
777 }
Eric Laurente552edb2014-03-10 17:42:56 -0700778 for (size_t i = 0; i < mOutputs.size(); i++) {
779 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700780 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700781 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
782 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
783 }
Eric Laurente552edb2014-03-10 17:42:56 -0700784 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
785 applyStreamVolumes(output, newDevice, 0, true);
786 }
787 }
788
789 audio_io_handle_t activeInput = getActiveInput();
790 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700791 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700792 }
793
794}
795
Eric Laurente0720872014-03-11 09:30:41 -0700796audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700797{
798 return mForceUse[usage];
799}
800
Eric Laurente0720872014-03-11 09:30:41 -0700801void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700802{
803 ALOGV("setSystemProperty() property %s, value %s", property, value);
804}
805
806// Find a direct output profile compatible with the parameters passed, even if the input flags do
807// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700808sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700809 audio_devices_t device,
810 uint32_t samplingRate,
811 audio_format_t format,
812 audio_channel_mask_t channelMask,
813 audio_output_flags_t flags)
814{
815 for (size_t i = 0; i < mHwModules.size(); i++) {
816 if (mHwModules[i]->mHandle == 0) {
817 continue;
818 }
819 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700820 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700821 bool found = profile->isCompatibleProfile(device, samplingRate,
822 NULL /*updatedSamplingRate*/, format, channelMask,
823 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
824 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700825 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
826 return profile;
827 }
Eric Laurente552edb2014-03-10 17:42:56 -0700828 }
829 }
830 return 0;
831}
832
Eric Laurente0720872014-03-11 09:30:41 -0700833audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700834 uint32_t samplingRate,
835 audio_format_t format,
836 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700837 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700838 const audio_offload_info_t *offloadInfo)
839{
Eric Laurent3b73df72014-03-11 09:06:29 -0700840 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700841 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
842 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
843 device, stream, samplingRate, format, channelMask, flags);
844
Eric Laurente83b55d2014-11-14 10:06:21 -0800845 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
846 stream, samplingRate,format, channelMask,
847 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848}
849
Eric Laurente83b55d2014-11-14 10:06:21 -0800850status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
851 audio_io_handle_t *output,
852 audio_session_t session,
853 audio_stream_type_t *stream,
854 uint32_t samplingRate,
855 audio_format_t format,
856 audio_channel_mask_t channelMask,
857 audio_output_flags_t flags,
858 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700859{
Eric Laurente83b55d2014-11-14 10:06:21 -0800860 audio_attributes_t attributes;
861 if (attr != NULL) {
862 if (!isValidAttributes(attr)) {
863 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
864 attr->usage, attr->content_type, attr->flags,
865 attr->tags);
866 return BAD_VALUE;
867 }
868 attributes = *attr;
869 } else {
870 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
871 ALOGE("getOutputForAttr(): invalid stream type");
872 return BAD_VALUE;
873 }
874 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700875 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800876
Eric Laurent93c3d412014-08-01 14:48:35 -0700877 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800878 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700879
880 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
Eric Laurente83b55d2014-11-14 10:06:21 -0800881 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700882 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700883
Eric Laurente83b55d2014-11-14 10:06:21 -0800884 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700885 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
886 }
887
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700888 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700889 device, samplingRate, format, channelMask, flags);
890
Eric Laurente83b55d2014-11-14 10:06:21 -0800891 *stream = streamTypefromAttributesInt(&attributes);
892 *output = getOutputForDevice(device, session, *stream,
893 samplingRate, format, channelMask,
894 flags, offloadInfo);
895 if (*output == AUDIO_IO_HANDLE_NONE) {
896 return INVALID_OPERATION;
897 }
898 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700899}
900
901audio_io_handle_t AudioPolicyManager::getOutputForDevice(
902 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800903 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700904 audio_stream_type_t stream,
905 uint32_t samplingRate,
906 audio_format_t format,
907 audio_channel_mask_t channelMask,
908 audio_output_flags_t flags,
909 const audio_offload_info_t *offloadInfo)
910{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700911 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700912 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700913 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700914
Eric Laurente552edb2014-03-10 17:42:56 -0700915#ifdef AUDIO_POLICY_TEST
916 if (mCurOutput != 0) {
917 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
918 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
919
920 if (mTestOutputs[mCurOutput] == 0) {
921 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700922 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700923 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700924 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700925 outputDesc->mFlags =
926 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700927 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700928 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
929 config.sample_rate = mTestSamplingRate;
930 config.channel_mask = mTestChannels;
931 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700932 if (offloadInfo != NULL) {
933 config.offload_info = *offloadInfo;
934 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700935 status = mpClientInterface->openOutput(0,
936 &mTestOutputs[mCurOutput],
937 &config,
938 &outputDesc->mDevice,
939 String8(""),
940 &outputDesc->mLatency,
941 outputDesc->mFlags);
942 if (status == NO_ERROR) {
943 outputDesc->mSamplingRate = config.sample_rate;
944 outputDesc->mFormat = config.format;
945 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700946 AudioParameter outputCmd = AudioParameter();
947 outputCmd.addInt(String8("set_id"),mCurOutput);
948 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
949 addOutput(mTestOutputs[mCurOutput], outputDesc);
950 }
951 }
952 return mTestOutputs[mCurOutput];
953 }
954#endif //AUDIO_POLICY_TEST
955
956 // open a direct output if required by specified parameters
957 //force direct flag if offload flag is set: offloading implies a direct output stream
958 // and all common behaviors are driven by checking only the direct flag
959 // this should normally be set appropriately in the policy configuration file
960 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700961 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700962 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700963 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
964 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
965 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800966 // only allow deep buffering for music stream type
967 if (stream != AUDIO_STREAM_MUSIC) {
968 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
969 }
Eric Laurente552edb2014-03-10 17:42:56 -0700970
Eric Laurentb732cf52014-09-24 19:08:21 -0700971 sp<IOProfile> profile;
972
973 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700974 // and not explicitly requested
975 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
976 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700977 audio_channel_count_from_out_mask(channelMask) <= 2) {
978 goto non_direct_output;
979 }
980
Eric Laurente552edb2014-03-10 17:42:56 -0700981 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
982 // creating an offloaded track and tearing it down immediately after start when audioflinger
983 // detects there is an active non offloadable effect.
984 // FIXME: We should check the audio session here but we do not have it in this context.
985 // This may prevent offloading in rare situations where effects are left active by apps
986 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700987
Eric Laurente552edb2014-03-10 17:42:56 -0700988 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
989 !isNonOffloadableEffectEnabled()) {
990 profile = getProfileForDirectOutput(device,
991 samplingRate,
992 format,
993 channelMask,
994 (audio_output_flags_t)flags);
995 }
996
Eric Laurent1c333e22014-05-20 10:48:17 -0700997 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700998 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700999
1000 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001001 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001002 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1003 outputDesc = desc;
1004 // reuse direct output if currently open and configured with same parameters
1005 if ((samplingRate == outputDesc->mSamplingRate) &&
1006 (format == outputDesc->mFormat) &&
1007 (channelMask == outputDesc->mChannelMask)) {
1008 outputDesc->mDirectOpenCount++;
1009 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1010 return mOutputs.keyAt(i);
1011 }
1012 }
1013 }
1014 // close direct output if currently open and configured with different parameters
1015 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001016 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001017 }
1018 outputDesc = new AudioOutputDescriptor(profile);
1019 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001020 outputDesc->mLatency = 0;
1021 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001022 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1023 config.sample_rate = samplingRate;
1024 config.channel_mask = channelMask;
1025 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001026 if (offloadInfo != NULL) {
1027 config.offload_info = *offloadInfo;
1028 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001029 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1030 &output,
1031 &config,
1032 &outputDesc->mDevice,
1033 String8(""),
1034 &outputDesc->mLatency,
1035 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001036
1037 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001038 if (status != NO_ERROR ||
1039 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1040 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1041 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001042 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1043 "format %d %d, channelMask %04x %04x", output, samplingRate,
1044 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1045 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001046 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001047 mpClientInterface->closeOutput(output);
1048 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001049 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001050 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001051 outputDesc->mSamplingRate = config.sample_rate;
1052 outputDesc->mChannelMask = config.channel_mask;
1053 outputDesc->mFormat = config.format;
1054 outputDesc->mRefCount[stream] = 0;
1055 outputDesc->mStopTime[stream] = 0;
1056 outputDesc->mDirectOpenCount = 1;
1057
Eric Laurente552edb2014-03-10 17:42:56 -07001058 audio_io_handle_t srcOutput = getOutputForEffect();
1059 addOutput(output, outputDesc);
1060 audio_io_handle_t dstOutput = getOutputForEffect();
1061 if (dstOutput == output) {
1062 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1063 }
1064 mPreviousOutputs = mOutputs;
1065 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001066 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001067 return output;
1068 }
1069
Eric Laurentb732cf52014-09-24 19:08:21 -07001070non_direct_output:
1071
Eric Laurente552edb2014-03-10 17:42:56 -07001072 // ignoring channel mask due to downmix capability in mixer
1073
1074 // open a non direct output
1075
1076 // for non direct outputs, only PCM is supported
1077 if (audio_is_linear_pcm(format)) {
1078 // get which output is suitable for the specified stream. The actual
1079 // routing change will happen when startOutput() will be called
1080 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1081
Eric Laurent8838a382014-09-08 16:44:28 -07001082 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1083 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1084 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001085 }
1086 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1087 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1088
1089 ALOGV("getOutput() returns output %d", output);
1090
1091 return output;
1092}
1093
Eric Laurente0720872014-03-11 09:30:41 -07001094audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001095 audio_output_flags_t flags,
1096 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001097{
1098 // select one output among several that provide a path to a particular device or set of
1099 // devices (the list was previously build by getOutputsForDevice()).
1100 // The priority is as follows:
1101 // 1: the output with the highest number of requested policy flags
1102 // 2: the primary output
1103 // 3: the first output in the list
1104
1105 if (outputs.size() == 0) {
1106 return 0;
1107 }
1108 if (outputs.size() == 1) {
1109 return outputs[0];
1110 }
1111
1112 int maxCommonFlags = 0;
1113 audio_io_handle_t outputFlags = 0;
1114 audio_io_handle_t outputPrimary = 0;
1115
1116 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001117 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001118 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001119 // if a valid format is specified, skip output if not compatible
1120 if (format != AUDIO_FORMAT_INVALID) {
1121 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1122 if (format != outputDesc->mFormat) {
1123 continue;
1124 }
1125 } else if (!audio_is_linear_pcm(format)) {
1126 continue;
1127 }
1128 }
1129
Eric Laurent3b73df72014-03-11 09:06:29 -07001130 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001131 if (commonFlags > maxCommonFlags) {
1132 outputFlags = outputs[i];
1133 maxCommonFlags = commonFlags;
1134 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1135 }
1136 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1137 outputPrimary = outputs[i];
1138 }
1139 }
1140 }
1141
1142 if (outputFlags != 0) {
1143 return outputFlags;
1144 }
1145 if (outputPrimary != 0) {
1146 return outputPrimary;
1147 }
1148
1149 return outputs[0];
1150}
1151
Eric Laurente0720872014-03-11 09:30:41 -07001152status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001153 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001154 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001155{
1156 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1157 ssize_t index = mOutputs.indexOfKey(output);
1158 if (index < 0) {
1159 ALOGW("startOutput() unknown output %d", output);
1160 return BAD_VALUE;
1161 }
1162
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001163 // cannot start playback of STREAM_TTS if any other output is being used
1164 uint32_t beaconMuteLatency = 0;
1165 if (stream == AUDIO_STREAM_TTS) {
1166 ALOGV("\t found BEACON stream");
1167 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1168 return INVALID_OPERATION;
1169 } else {
1170 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1171 }
1172 } else {
1173 // some playback other than beacon starts
1174 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1175 }
1176
Eric Laurent1f2f2232014-06-02 12:01:23 -07001177 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001178
1179 // increment usage count for this stream on the requested output:
1180 // NOTE that the usage count is the same for duplicated output and hardware output which is
1181 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1182 outputDesc->changeRefCount(stream, 1);
1183
1184 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001185 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001186 routing_strategy strategy = getStrategy(stream);
1187 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001188 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1189 (beaconMuteLatency > 0);
1190 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001191 bool force = false;
1192 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001193 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001194 if (desc != outputDesc) {
1195 // force a device change if any other output is managed by the same hw
1196 // module and has a current device selection that differs from selected device.
1197 // In this case, the audio HAL must receive the new device selection so that it can
1198 // change the device currently selected by the other active output.
1199 if (outputDesc->sharesHwModuleWith(desc) &&
1200 desc->device() != newDevice) {
1201 force = true;
1202 }
1203 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001204 // a notification so that audio focus effect can propagate, or that a mute/unmute
1205 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001206 uint32_t latency = desc->latency();
1207 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1208 waitMs = latency;
1209 }
1210 }
1211 }
1212 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1213
1214 // handle special case for sonification while in call
1215 if (isInCall()) {
1216 handleIncallSonification(stream, true, false);
1217 }
1218
1219 // apply volume rules for current stream and device if necessary
1220 checkAndSetVolume(stream,
1221 mStreams[stream].getVolumeIndex(newDevice),
1222 output,
1223 newDevice);
1224
1225 // update the outputs if starting an output with a stream that can affect notification
1226 // routing
1227 handleNotificationRoutingForStream(stream);
1228 if (waitMs > muteWaitMs) {
1229 usleep((waitMs - muteWaitMs) * 2 * 1000);
1230 }
1231 }
1232 return NO_ERROR;
1233}
1234
1235
Eric Laurente0720872014-03-11 09:30:41 -07001236status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001237 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001238 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001239{
1240 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1241 ssize_t index = mOutputs.indexOfKey(output);
1242 if (index < 0) {
1243 ALOGW("stopOutput() unknown output %d", output);
1244 return BAD_VALUE;
1245 }
1246
Eric Laurent1f2f2232014-06-02 12:01:23 -07001247 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001248
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001249 // always handle stream stop, check which stream type is stopping
1250 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1251
Eric Laurente552edb2014-03-10 17:42:56 -07001252 // handle special case for sonification while in call
1253 if (isInCall()) {
1254 handleIncallSonification(stream, false, false);
1255 }
1256
1257 if (outputDesc->mRefCount[stream] > 0) {
1258 // decrement usage count of this stream on the output
1259 outputDesc->changeRefCount(stream, -1);
1260 // store time at which the stream was stopped - see isStreamActive()
1261 if (outputDesc->mRefCount[stream] == 0) {
1262 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001263 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001264 // delay the device switch by twice the latency because stopOutput() is executed when
1265 // the track stop() command is received and at that time the audio track buffer can
1266 // still contain data that needs to be drained. The latency only covers the audio HAL
1267 // and kernel buffers. Also the latency does not always include additional delay in the
1268 // audio path (audio DSP, CODEC ...)
1269 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1270
1271 // force restoring the device selection on other active outputs if it differs from the
1272 // one being selected for this output
1273 for (size_t i = 0; i < mOutputs.size(); i++) {
1274 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001275 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001276 if (curOutput != output &&
1277 desc->isActive() &&
1278 outputDesc->sharesHwModuleWith(desc) &&
1279 (newDevice != desc->device())) {
1280 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001281 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001282 true,
1283 outputDesc->mLatency*2);
1284 }
1285 }
1286 // update the outputs if stopping one with a stream that can affect notification routing
1287 handleNotificationRoutingForStream(stream);
1288 }
1289 return NO_ERROR;
1290 } else {
1291 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1292 return INVALID_OPERATION;
1293 }
1294}
1295
Eric Laurente83b55d2014-11-14 10:06:21 -08001296void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001297 audio_stream_type_t stream __unused,
1298 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001299{
1300 ALOGV("releaseOutput() %d", output);
1301 ssize_t index = mOutputs.indexOfKey(output);
1302 if (index < 0) {
1303 ALOGW("releaseOutput() releasing unknown output %d", output);
1304 return;
1305 }
1306
1307#ifdef AUDIO_POLICY_TEST
1308 int testIndex = testOutputIndex(output);
1309 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001310 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001311 if (outputDesc->isActive()) {
1312 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001313 mOutputs.removeItem(output);
1314 mTestOutputs[testIndex] = 0;
1315 }
1316 return;
1317 }
1318#endif //AUDIO_POLICY_TEST
1319
Eric Laurent1f2f2232014-06-02 12:01:23 -07001320 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001321 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001322 if (desc->mDirectOpenCount <= 0) {
1323 ALOGW("releaseOutput() invalid open count %d for output %d",
1324 desc->mDirectOpenCount, output);
1325 return;
1326 }
1327 if (--desc->mDirectOpenCount == 0) {
1328 closeOutput(output);
1329 // If effects where present on the output, audioflinger moved them to the primary
1330 // output by default: move them back to the appropriate output.
1331 audio_io_handle_t dstOutput = getOutputForEffect();
1332 if (dstOutput != mPrimaryOutput) {
1333 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1334 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001335 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001336 }
1337 }
1338}
1339
1340
Eric Laurentcaf7f482014-11-25 17:50:47 -08001341status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1342 audio_io_handle_t *input,
1343 audio_session_t session,
1344 uint32_t samplingRate,
1345 audio_format_t format,
1346 audio_channel_mask_t channelMask,
1347 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001348{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001349 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1350 "session %d, flags %#x",
1351 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001352
Eric Laurentcaf7f482014-11-25 17:50:47 -08001353 audio_devices_t device = getDeviceForInputSource(attr->source);
Eric Laurente552edb2014-03-10 17:42:56 -07001354
1355 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001356 ALOGW("getInputForAttr() could not find device for source %d", attr->source);
1357 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001358 }
1359
1360 // adapt channel selection to input source
Eric Laurentcaf7f482014-11-25 17:50:47 -08001361 switch (attr->source) {
Eric Laurente552edb2014-03-10 17:42:56 -07001362 case AUDIO_SOURCE_VOICE_UPLINK:
1363 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1364 break;
1365 case AUDIO_SOURCE_VOICE_DOWNLINK:
1366 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1367 break;
1368 case AUDIO_SOURCE_VOICE_CALL:
1369 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1370 break;
1371 default:
1372 break;
1373 }
1374
Eric Laurentcaf7f482014-11-25 17:50:47 -08001375 *input = AUDIO_IO_HANDLE_NONE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001376 bool isSoundTrigger = false;
Eric Laurentcaf7f482014-11-25 17:50:47 -08001377 audio_source_t halInputSource = attr->source;
1378 if (attr->source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001379 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1380 if (index >= 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001381 *input = mSoundTriggerSessions.valueFor(session);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001382 isSoundTrigger = true;
1383 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001384 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001385 } else {
1386 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1387 }
1388 }
1389
Eric Laurent1c333e22014-05-20 10:48:17 -07001390 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001391 samplingRate,
1392 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001393 channelMask,
1394 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001395 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001396 //retry without flags
1397 audio_input_flags_t log_flags = flags;
1398 flags = AUDIO_INPUT_FLAG_NONE;
1399 profile = getInputProfile(device,
1400 samplingRate,
1401 format,
1402 channelMask,
1403 flags);
1404 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001405 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1406 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001407 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001408 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001409 }
Eric Laurente552edb2014-03-10 17:42:56 -07001410 }
1411
1412 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001413 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1414 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001415 }
1416
1417 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1418 config.sample_rate = samplingRate;
1419 config.channel_mask = channelMask;
1420 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001421
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001422 // handle legacy remote submix case where the address was not always specified
1423 String8 address = deviceDistinguishesOnAddress(device) ? String8("0") : String8("");
1424
Eric Laurentcf2c0212014-07-25 16:20:43 -07001425 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001426 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001427 &config,
1428 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001429 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001430 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001431 flags);
1432
1433 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001434 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001435 (samplingRate != config.sample_rate) ||
1436 (format != config.format) ||
1437 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001438 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001439 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001440 if (*input != AUDIO_IO_HANDLE_NONE) {
1441 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001442 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001443 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001444 }
1445
Eric Laurent1f2f2232014-06-02 12:01:23 -07001446 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001447 inputDesc->mInputSource = attr->source;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001448 inputDesc->mRefCount = 0;
1449 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001450 inputDesc->mSamplingRate = samplingRate;
1451 inputDesc->mFormat = format;
1452 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001453 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001454 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001455 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001456
Eric Laurentcaf7f482014-11-25 17:50:47 -08001457 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001458 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001459 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001460}
1461
Eric Laurent4dc68062014-07-28 17:26:49 -07001462status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1463 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001464{
1465 ALOGV("startInput() input %d", input);
1466 ssize_t index = mInputs.indexOfKey(input);
1467 if (index < 0) {
1468 ALOGW("startInput() unknown input %d", input);
1469 return BAD_VALUE;
1470 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001471 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001472
Eric Laurent4dc68062014-07-28 17:26:49 -07001473 index = inputDesc->mSessions.indexOf(session);
1474 if (index < 0) {
1475 ALOGW("startInput() unknown session %d on input %d", session, input);
1476 return BAD_VALUE;
1477 }
1478
Glenn Kasten74a8e252014-07-24 14:09:55 -07001479 // virtual input devices are compatible with other input devices
1480 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1481
1482 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001483 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001484 if (activeInput != 0 && activeInput != input) {
1485
1486 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1487 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001488 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001489 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001490 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001491 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1492 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001493 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001494 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001495 return INVALID_OPERATION;
1496 }
1497 }
1498 }
1499
Glenn Kasten74a8e252014-07-24 14:09:55 -07001500 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001501 if (activeInputsCount() == 0) {
1502 SoundTrigger::setCaptureState(true);
1503 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001504 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001505
Glenn Kasten74a8e252014-07-24 14:09:55 -07001506 // Automatically enable the remote submix output when input is started.
1507 // For remote submix (a virtual device), we open only one input per capture request.
1508 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1509 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1510 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1511 }
Eric Laurente552edb2014-03-10 17:42:56 -07001512 }
1513
Eric Laurente552edb2014-03-10 17:42:56 -07001514 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1515
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001516 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001517 return NO_ERROR;
1518}
1519
Eric Laurent4dc68062014-07-28 17:26:49 -07001520status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1521 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001522{
1523 ALOGV("stopInput() input %d", input);
1524 ssize_t index = mInputs.indexOfKey(input);
1525 if (index < 0) {
1526 ALOGW("stopInput() unknown input %d", input);
1527 return BAD_VALUE;
1528 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001529 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001530
Eric Laurent4dc68062014-07-28 17:26:49 -07001531 index = inputDesc->mSessions.indexOf(session);
1532 if (index < 0) {
1533 ALOGW("stopInput() unknown session %d on input %d", session, input);
1534 return BAD_VALUE;
1535 }
1536
Eric Laurente552edb2014-03-10 17:42:56 -07001537 if (inputDesc->mRefCount == 0) {
1538 ALOGW("stopInput() input %d already stopped", input);
1539 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001540 }
1541
1542 inputDesc->mRefCount--;
1543 if (inputDesc->mRefCount == 0) {
1544
Eric Laurente552edb2014-03-10 17:42:56 -07001545 // automatically disable the remote submix output when input is stopped
1546 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1547 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001548 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001549 }
1550
Eric Laurent1c333e22014-05-20 10:48:17 -07001551 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001552
1553 if (activeInputsCount() == 0) {
1554 SoundTrigger::setCaptureState(false);
1555 }
Eric Laurente552edb2014-03-10 17:42:56 -07001556 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001557 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001558}
1559
Eric Laurent4dc68062014-07-28 17:26:49 -07001560void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1561 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001562{
1563 ALOGV("releaseInput() %d", input);
1564 ssize_t index = mInputs.indexOfKey(input);
1565 if (index < 0) {
1566 ALOGW("releaseInput() releasing unknown input %d", input);
1567 return;
1568 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001569 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1570 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001571
1572 index = inputDesc->mSessions.indexOf(session);
1573 if (index < 0) {
1574 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1575 return;
1576 }
1577 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001578 if (inputDesc->mOpenRefCount == 0) {
1579 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1580 return;
1581 }
1582 inputDesc->mOpenRefCount--;
1583 if (inputDesc->mOpenRefCount > 0) {
1584 ALOGV("releaseInput() exit > 0");
1585 return;
1586 }
1587
Eric Laurent05b90f82014-08-27 15:32:29 -07001588 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001589 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001590 ALOGV("releaseInput() exit");
1591}
1592
Eric Laurentd4692962014-05-05 18:13:44 -07001593void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001594 bool patchRemoved = false;
1595
Eric Laurentd4692962014-05-05 18:13:44 -07001596 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001597 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1598 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1599 if (patch_index >= 0) {
1600 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1601 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1602 mAudioPatches.removeItemsAt(patch_index);
1603 patchRemoved = true;
1604 }
Eric Laurentd4692962014-05-05 18:13:44 -07001605 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1606 }
1607 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001608 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001609
1610 if (patchRemoved) {
1611 mpClientInterface->onAudioPatchListUpdate();
1612 }
Eric Laurentd4692962014-05-05 18:13:44 -07001613}
1614
Eric Laurente0720872014-03-11 09:30:41 -07001615void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001616 int indexMin,
1617 int indexMax)
1618{
1619 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1620 if (indexMin < 0 || indexMin >= indexMax) {
1621 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1622 return;
1623 }
1624 mStreams[stream].mIndexMin = indexMin;
1625 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001626 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1627 if (stream == AUDIO_STREAM_MUSIC) {
1628 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1629 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1630 }
Eric Laurente552edb2014-03-10 17:42:56 -07001631}
1632
Eric Laurente0720872014-03-11 09:30:41 -07001633status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001634 int index,
1635 audio_devices_t device)
1636{
1637
1638 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1639 return BAD_VALUE;
1640 }
1641 if (!audio_is_output_device(device)) {
1642 return BAD_VALUE;
1643 }
1644
1645 // Force max volume if stream cannot be muted
1646 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1647
1648 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1649 stream, device, index);
1650
1651 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1652 // clear all device specific values
1653 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1654 mStreams[stream].mIndexCur.clear();
1655 }
1656 mStreams[stream].mIndexCur.add(device, index);
1657
Eric Laurent31551f82014-10-10 18:21:56 -07001658 // update volume on all outputs whose current device is also selected by the same
1659 // strategy as the device specified by the caller
1660 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001661
1662
1663 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1664 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1665 if (stream == AUDIO_STREAM_MUSIC) {
1666 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1667 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1668 }
1669 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1670 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001671 return NO_ERROR;
1672 }
Eric Laurente552edb2014-03-10 17:42:56 -07001673 status_t status = NO_ERROR;
1674 for (size_t i = 0; i < mOutputs.size(); i++) {
1675 audio_devices_t curDevice =
1676 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001677 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001678 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1679 if (volStatus != NO_ERROR) {
1680 status = volStatus;
1681 }
1682 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001683 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1684 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1685 index, mOutputs.keyAt(i), curDevice);
1686 }
Eric Laurente552edb2014-03-10 17:42:56 -07001687 }
1688 return status;
1689}
1690
Eric Laurente0720872014-03-11 09:30:41 -07001691status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001692 int *index,
1693 audio_devices_t device)
1694{
1695 if (index == NULL) {
1696 return BAD_VALUE;
1697 }
1698 if (!audio_is_output_device(device)) {
1699 return BAD_VALUE;
1700 }
1701 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1702 // the strategy the stream belongs to.
1703 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1704 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1705 }
1706 device = getDeviceForVolume(device);
1707
1708 *index = mStreams[stream].getVolumeIndex(device);
1709 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1710 return NO_ERROR;
1711}
1712
Eric Laurente0720872014-03-11 09:30:41 -07001713audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001714 const SortedVector<audio_io_handle_t>& outputs)
1715{
1716 // select one output among several suitable for global effects.
1717 // The priority is as follows:
1718 // 1: An offloaded output. If the effect ends up not being offloadable,
1719 // AudioFlinger will invalidate the track and the offloaded output
1720 // will be closed causing the effect to be moved to a PCM output.
1721 // 2: A deep buffer output
1722 // 3: the first output in the list
1723
1724 if (outputs.size() == 0) {
1725 return 0;
1726 }
1727
1728 audio_io_handle_t outputOffloaded = 0;
1729 audio_io_handle_t outputDeepBuffer = 0;
1730
1731 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001732 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001733 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001734 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1735 outputOffloaded = outputs[i];
1736 }
1737 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1738 outputDeepBuffer = outputs[i];
1739 }
1740 }
1741
1742 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1743 outputOffloaded, outputDeepBuffer);
1744 if (outputOffloaded != 0) {
1745 return outputOffloaded;
1746 }
1747 if (outputDeepBuffer != 0) {
1748 return outputDeepBuffer;
1749 }
1750
1751 return outputs[0];
1752}
1753
Eric Laurente0720872014-03-11 09:30:41 -07001754audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001755{
1756 // apply simple rule where global effects are attached to the same output as MUSIC streams
1757
Eric Laurent3b73df72014-03-11 09:06:29 -07001758 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001759 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1760 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1761
1762 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1763 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1764 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1765
1766 return output;
1767}
1768
Eric Laurente0720872014-03-11 09:30:41 -07001769status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001770 audio_io_handle_t io,
1771 uint32_t strategy,
1772 int session,
1773 int id)
1774{
1775 ssize_t index = mOutputs.indexOfKey(io);
1776 if (index < 0) {
1777 index = mInputs.indexOfKey(io);
1778 if (index < 0) {
1779 ALOGW("registerEffect() unknown io %d", io);
1780 return INVALID_OPERATION;
1781 }
1782 }
1783
1784 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1785 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1786 desc->name, desc->memoryUsage);
1787 return INVALID_OPERATION;
1788 }
1789 mTotalEffectsMemory += desc->memoryUsage;
1790 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1791 desc->name, io, strategy, session, id);
1792 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1793
Eric Laurent1f2f2232014-06-02 12:01:23 -07001794 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1795 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1796 effectDesc->mIo = io;
1797 effectDesc->mStrategy = (routing_strategy)strategy;
1798 effectDesc->mSession = session;
1799 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001800
Eric Laurent1f2f2232014-06-02 12:01:23 -07001801 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001802
1803 return NO_ERROR;
1804}
1805
Eric Laurente0720872014-03-11 09:30:41 -07001806status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001807{
1808 ssize_t index = mEffects.indexOfKey(id);
1809 if (index < 0) {
1810 ALOGW("unregisterEffect() unknown effect ID %d", id);
1811 return INVALID_OPERATION;
1812 }
1813
Eric Laurent1f2f2232014-06-02 12:01:23 -07001814 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001815
Eric Laurent1f2f2232014-06-02 12:01:23 -07001816 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001817
Eric Laurent1f2f2232014-06-02 12:01:23 -07001818 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001819 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001820 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1821 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001822 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001823 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001824 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001825 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001826
1827 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001828
1829 return NO_ERROR;
1830}
1831
Eric Laurente0720872014-03-11 09:30:41 -07001832status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001833{
1834 ssize_t index = mEffects.indexOfKey(id);
1835 if (index < 0) {
1836 ALOGW("unregisterEffect() unknown effect ID %d", id);
1837 return INVALID_OPERATION;
1838 }
1839
1840 return setEffectEnabled(mEffects.valueAt(index), enabled);
1841}
1842
Eric Laurent1f2f2232014-06-02 12:01:23 -07001843status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001844{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001845 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001846 ALOGV("setEffectEnabled(%s) effect already %s",
1847 enabled?"true":"false", enabled?"enabled":"disabled");
1848 return INVALID_OPERATION;
1849 }
1850
1851 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001852 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001853 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001854 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001855 return INVALID_OPERATION;
1856 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001857 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001858 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1859 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001860 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001861 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001862 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1863 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001864 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001865 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001866 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1867 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001868 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001869 return NO_ERROR;
1870}
1871
Eric Laurente0720872014-03-11 09:30:41 -07001872bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001873{
1874 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001875 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1876 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1877 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001878 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001879 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001880 return true;
1881 }
1882 }
1883 return false;
1884}
1885
Eric Laurente0720872014-03-11 09:30:41 -07001886bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001887{
1888 nsecs_t sysTime = systemTime();
1889 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001890 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001891 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001892 return true;
1893 }
1894 }
1895 return false;
1896}
1897
Eric Laurente0720872014-03-11 09:30:41 -07001898bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001899 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001900{
1901 nsecs_t sysTime = systemTime();
1902 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001903 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001904 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001905 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001906 return true;
1907 }
1908 }
1909 return false;
1910}
1911
Eric Laurente0720872014-03-11 09:30:41 -07001912bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001913{
1914 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001915 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001916 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001917 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001918 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1919 && (inputDescriptor->mRefCount > 0)) {
1920 return true;
1921 }
1922 }
1923 return false;
1924}
1925
1926
Eric Laurente0720872014-03-11 09:30:41 -07001927status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001928{
1929 const size_t SIZE = 256;
1930 char buffer[SIZE];
1931 String8 result;
1932
1933 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1934 result.append(buffer);
1935
1936 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1937 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001938 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1939 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001940 snprintf(buffer, SIZE, " Force use for communications %d\n",
1941 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001942 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001943 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001944 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001945 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001946 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001947 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001948 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001949 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001950 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001951 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1952 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1953 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001954
Eric Laurent3a4311c2014-03-17 12:00:47 -07001955 snprintf(buffer, SIZE, " Available output devices:\n");
1956 result.append(buffer);
1957 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001958 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001959 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001960 }
1961 snprintf(buffer, SIZE, "\n Available input devices:\n");
1962 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001963 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001964 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001965 }
Eric Laurente552edb2014-03-10 17:42:56 -07001966
1967 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1968 write(fd, buffer, strlen(buffer));
1969 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001970 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001971 write(fd, buffer, strlen(buffer));
1972 mHwModules[i]->dump(fd);
1973 }
1974
1975 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1976 write(fd, buffer, strlen(buffer));
1977 for (size_t i = 0; i < mOutputs.size(); i++) {
1978 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1979 write(fd, buffer, strlen(buffer));
1980 mOutputs.valueAt(i)->dump(fd);
1981 }
1982
1983 snprintf(buffer, SIZE, "\nInputs dump:\n");
1984 write(fd, buffer, strlen(buffer));
1985 for (size_t i = 0; i < mInputs.size(); i++) {
1986 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1987 write(fd, buffer, strlen(buffer));
1988 mInputs.valueAt(i)->dump(fd);
1989 }
1990
1991 snprintf(buffer, SIZE, "\nStreams dump:\n");
1992 write(fd, buffer, strlen(buffer));
1993 snprintf(buffer, SIZE,
1994 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1995 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001996 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001997 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001998 write(fd, buffer, strlen(buffer));
1999 mStreams[i].dump(fd);
2000 }
2001
2002 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2003 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2004 write(fd, buffer, strlen(buffer));
2005
2006 snprintf(buffer, SIZE, "Registered effects:\n");
2007 write(fd, buffer, strlen(buffer));
2008 for (size_t i = 0; i < mEffects.size(); i++) {
2009 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2010 write(fd, buffer, strlen(buffer));
2011 mEffects.valueAt(i)->dump(fd);
2012 }
2013
Eric Laurent4d416952014-08-10 14:07:09 -07002014 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2015 write(fd, buffer, strlen(buffer));
2016 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2017 mAudioPatches[i]->dump(fd, 2, i);
2018 }
Eric Laurente552edb2014-03-10 17:42:56 -07002019
2020 return NO_ERROR;
2021}
2022
2023// This function checks for the parameters which can be offloaded.
2024// This can be enhanced depending on the capability of the DSP and policy
2025// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002026bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002027{
2028 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002029 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002030 offloadInfo.sample_rate, offloadInfo.channel_mask,
2031 offloadInfo.format,
2032 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2033 offloadInfo.has_video);
2034
2035 // Check if offload has been disabled
2036 char propValue[PROPERTY_VALUE_MAX];
2037 if (property_get("audio.offload.disable", propValue, "0")) {
2038 if (atoi(propValue) != 0) {
2039 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2040 return false;
2041 }
2042 }
2043
2044 // Check if stream type is music, then only allow offload as of now.
2045 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2046 {
2047 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2048 return false;
2049 }
2050
2051 //TODO: enable audio offloading with video when ready
2052 if (offloadInfo.has_video)
2053 {
2054 ALOGV("isOffloadSupported: has_video == true, returning false");
2055 return false;
2056 }
2057
2058 //If duration is less than minimum value defined in property, return false
2059 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2060 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2061 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2062 return false;
2063 }
2064 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2065 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2066 return false;
2067 }
2068
2069 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2070 // creating an offloaded track and tearing it down immediately after start when audioflinger
2071 // detects there is an active non offloadable effect.
2072 // FIXME: We should check the audio session here but we do not have it in this context.
2073 // This may prevent offloading in rare situations where effects are left active by apps
2074 // in the background.
2075 if (isNonOffloadableEffectEnabled()) {
2076 return false;
2077 }
2078
2079 // See if there is a profile to support this.
2080 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002081 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002082 offloadInfo.sample_rate,
2083 offloadInfo.format,
2084 offloadInfo.channel_mask,
2085 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002086 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2087 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002088}
2089
Eric Laurent6a94d692014-05-20 11:18:06 -07002090status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2091 audio_port_type_t type,
2092 unsigned int *num_ports,
2093 struct audio_port *ports,
2094 unsigned int *generation)
2095{
2096 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2097 generation == NULL) {
2098 return BAD_VALUE;
2099 }
2100 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2101 if (ports == NULL) {
2102 *num_ports = 0;
2103 }
2104
2105 size_t portsWritten = 0;
2106 size_t portsMax = *num_ports;
2107 *num_ports = 0;
2108 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2109 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2110 for (size_t i = 0;
2111 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2112 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2113 }
2114 *num_ports += mAvailableOutputDevices.size();
2115 }
2116 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2117 for (size_t i = 0;
2118 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2119 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2120 }
2121 *num_ports += mAvailableInputDevices.size();
2122 }
2123 }
2124 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2125 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2126 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2127 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2128 }
2129 *num_ports += mInputs.size();
2130 }
2131 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002132 size_t numOutputs = 0;
2133 for (size_t i = 0; i < mOutputs.size(); i++) {
2134 if (!mOutputs[i]->isDuplicated()) {
2135 numOutputs++;
2136 if (portsWritten < portsMax) {
2137 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2138 }
2139 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002140 }
Eric Laurent84c70242014-06-23 08:46:27 -07002141 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002142 }
2143 }
2144 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002145 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002146 return NO_ERROR;
2147}
2148
2149status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2150{
2151 return NO_ERROR;
2152}
2153
Eric Laurent1f2f2232014-06-02 12:01:23 -07002154sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002155 audio_port_handle_t id) const
2156{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002157 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002158 for (size_t i = 0; i < mOutputs.size(); i++) {
2159 outputDesc = mOutputs.valueAt(i);
2160 if (outputDesc->mId == id) {
2161 break;
2162 }
2163 }
2164 return outputDesc;
2165}
2166
Eric Laurent1f2f2232014-06-02 12:01:23 -07002167sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002168 audio_port_handle_t id) const
2169{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002170 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002171 for (size_t i = 0; i < mInputs.size(); i++) {
2172 inputDesc = mInputs.valueAt(i);
2173 if (inputDesc->mId == id) {
2174 break;
2175 }
2176 }
2177 return inputDesc;
2178}
2179
Eric Laurent1f2f2232014-06-02 12:01:23 -07002180sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2181 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002182{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002183 sp <HwModule> module;
2184
Eric Laurent6a94d692014-05-20 11:18:06 -07002185 for (size_t i = 0; i < mHwModules.size(); i++) {
2186 if (mHwModules[i]->mHandle == 0) {
2187 continue;
2188 }
2189 if (audio_is_output_device(device)) {
2190 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2191 {
2192 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2193 return mHwModules[i];
2194 }
2195 }
2196 } else {
2197 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2198 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2199 device & ~AUDIO_DEVICE_BIT_IN) {
2200 return mHwModules[i];
2201 }
2202 }
2203 }
2204 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002205 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002206}
2207
Eric Laurent1f2f2232014-06-02 12:01:23 -07002208sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002209{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002210 sp <HwModule> module;
2211
Eric Laurent1afeecb2014-05-14 08:52:28 -07002212 for (size_t i = 0; i < mHwModules.size(); i++)
2213 {
2214 if (strcmp(mHwModules[i]->mName, name) == 0) {
2215 return mHwModules[i];
2216 }
2217 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002218 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002219}
2220
Eric Laurentc2730ba2014-07-20 15:47:07 -07002221audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2222{
2223 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2224 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2225 return devices & mAvailableOutputDevices.types();
2226}
2227
2228audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2229{
2230 audio_module_handle_t primaryHandle =
2231 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2232 audio_devices_t devices = AUDIO_DEVICE_NONE;
2233 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2234 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2235 devices |= mAvailableInputDevices[i]->mDeviceType;
2236 }
2237 }
2238 return devices;
2239}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002240
Eric Laurent6a94d692014-05-20 11:18:06 -07002241status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2242 audio_patch_handle_t *handle,
2243 uid_t uid)
2244{
2245 ALOGV("createAudioPatch()");
2246
2247 if (handle == NULL || patch == NULL) {
2248 return BAD_VALUE;
2249 }
2250 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2251
Eric Laurent874c42872014-08-08 15:13:39 -07002252 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2253 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2254 return BAD_VALUE;
2255 }
2256 // only one source per audio patch supported for now
2257 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002258 return INVALID_OPERATION;
2259 }
Eric Laurent874c42872014-08-08 15:13:39 -07002260
2261 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002262 return INVALID_OPERATION;
2263 }
Eric Laurent874c42872014-08-08 15:13:39 -07002264 for (size_t i = 0; i < patch->num_sinks; i++) {
2265 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2266 return INVALID_OPERATION;
2267 }
2268 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002269
2270 sp<AudioPatch> patchDesc;
2271 ssize_t index = mAudioPatches.indexOfKey(*handle);
2272
Eric Laurent6a94d692014-05-20 11:18:06 -07002273 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2274 patch->sources[0].role,
2275 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002276#if LOG_NDEBUG == 0
2277 for (size_t i = 0; i < patch->num_sinks; i++) {
2278 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2279 patch->sinks[i].role,
2280 patch->sinks[i].type);
2281 }
2282#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002283
2284 if (index >= 0) {
2285 patchDesc = mAudioPatches.valueAt(index);
2286 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2287 mUidCached, patchDesc->mUid, uid);
2288 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2289 return INVALID_OPERATION;
2290 }
2291 } else {
2292 *handle = 0;
2293 }
2294
2295 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002296 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002297 if (outputDesc == NULL) {
2298 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2299 return BAD_VALUE;
2300 }
Eric Laurent84c70242014-06-23 08:46:27 -07002301 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2302 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002303 if (patchDesc != 0) {
2304 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2305 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2306 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2307 return BAD_VALUE;
2308 }
2309 }
Eric Laurent874c42872014-08-08 15:13:39 -07002310 DeviceVector devices;
2311 for (size_t i = 0; i < patch->num_sinks; i++) {
2312 // Only support mix to devices connection
2313 // TODO add support for mix to mix connection
2314 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2315 ALOGV("createAudioPatch() source mix but sink is not a device");
2316 return INVALID_OPERATION;
2317 }
2318 sp<DeviceDescriptor> devDesc =
2319 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2320 if (devDesc == 0) {
2321 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2322 return BAD_VALUE;
2323 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002324
Eric Laurent874c42872014-08-08 15:13:39 -07002325 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2326 patch->sources[0].sample_rate,
2327 NULL, // updatedSamplingRate
2328 patch->sources[0].format,
2329 patch->sources[0].channel_mask,
2330 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2331 ALOGV("createAudioPatch() profile not supported for device %08x",
2332 devDesc->mDeviceType);
2333 return INVALID_OPERATION;
2334 }
2335 devices.add(devDesc);
2336 }
2337 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002338 return INVALID_OPERATION;
2339 }
Eric Laurent874c42872014-08-08 15:13:39 -07002340
Eric Laurent6a94d692014-05-20 11:18:06 -07002341 // TODO: reconfigure output format and channels here
2342 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002343 devices.types(), outputDesc->mIoHandle);
2344 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002345 index = mAudioPatches.indexOfKey(*handle);
2346 if (index >= 0) {
2347 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2348 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2349 }
2350 patchDesc = mAudioPatches.valueAt(index);
2351 patchDesc->mUid = uid;
2352 ALOGV("createAudioPatch() success");
2353 } else {
2354 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2355 return INVALID_OPERATION;
2356 }
2357 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2358 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2359 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002360 // only one sink supported when connecting an input device to a mix
2361 if (patch->num_sinks > 1) {
2362 return INVALID_OPERATION;
2363 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002364 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002365 if (inputDesc == NULL) {
2366 return BAD_VALUE;
2367 }
2368 if (patchDesc != 0) {
2369 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2370 return BAD_VALUE;
2371 }
2372 }
2373 sp<DeviceDescriptor> devDesc =
2374 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2375 if (devDesc == 0) {
2376 return BAD_VALUE;
2377 }
2378
Eric Laurent84c70242014-06-23 08:46:27 -07002379 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002380 patch->sinks[0].sample_rate,
2381 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002382 patch->sinks[0].format,
2383 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002384 // FIXME for the parameter type,
2385 // and the NONE
2386 (audio_output_flags_t)
2387 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002388 return INVALID_OPERATION;
2389 }
2390 // TODO: reconfigure output format and channels here
2391 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002392 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002393 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002394 index = mAudioPatches.indexOfKey(*handle);
2395 if (index >= 0) {
2396 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2397 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2398 }
2399 patchDesc = mAudioPatches.valueAt(index);
2400 patchDesc->mUid = uid;
2401 ALOGV("createAudioPatch() success");
2402 } else {
2403 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2404 return INVALID_OPERATION;
2405 }
2406 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2407 // device to device connection
2408 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002409 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002410 return BAD_VALUE;
2411 }
2412 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002413 sp<DeviceDescriptor> srcDeviceDesc =
2414 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002415 if (srcDeviceDesc == 0) {
2416 return BAD_VALUE;
2417 }
Eric Laurent874c42872014-08-08 15:13:39 -07002418
Eric Laurent6a94d692014-05-20 11:18:06 -07002419 //update source and sink with our own data as the data passed in the patch may
2420 // be incomplete.
2421 struct audio_patch newPatch = *patch;
2422 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002423
Eric Laurent874c42872014-08-08 15:13:39 -07002424 for (size_t i = 0; i < patch->num_sinks; i++) {
2425 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2426 ALOGV("createAudioPatch() source device but one sink is not a device");
2427 return INVALID_OPERATION;
2428 }
2429
2430 sp<DeviceDescriptor> sinkDeviceDesc =
2431 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2432 if (sinkDeviceDesc == 0) {
2433 return BAD_VALUE;
2434 }
2435 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2436
2437 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2438 // only one sink supported when connected devices across HW modules
2439 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002440 return INVALID_OPERATION;
2441 }
Eric Laurent874c42872014-08-08 15:13:39 -07002442 SortedVector<audio_io_handle_t> outputs =
2443 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2444 mOutputs);
2445 // if the sink device is reachable via an opened output stream, request to go via
2446 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002447 audio_io_handle_t output = selectOutput(outputs,
2448 AUDIO_OUTPUT_FLAG_NONE,
2449 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002450 if (output != AUDIO_IO_HANDLE_NONE) {
2451 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2452 if (outputDesc->isDuplicated()) {
2453 return INVALID_OPERATION;
2454 }
2455 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2456 newPatch.num_sources = 2;
2457 }
Eric Laurent83b88082014-06-20 18:31:16 -07002458 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002459 }
2460 // TODO: check from routing capabilities in config file and other conflicting patches
2461
2462 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2463 if (index >= 0) {
2464 afPatchHandle = patchDesc->mAfPatchHandle;
2465 }
2466
2467 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2468 &afPatchHandle,
2469 0);
2470 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2471 status, afPatchHandle);
2472 if (status == NO_ERROR) {
2473 if (index < 0) {
2474 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2475 &newPatch, uid);
2476 addAudioPatch(patchDesc->mHandle, patchDesc);
2477 } else {
2478 patchDesc->mPatch = newPatch;
2479 }
2480 patchDesc->mAfPatchHandle = afPatchHandle;
2481 *handle = patchDesc->mHandle;
2482 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002483 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002484 } else {
2485 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2486 status);
2487 return INVALID_OPERATION;
2488 }
2489 } else {
2490 return BAD_VALUE;
2491 }
2492 } else {
2493 return BAD_VALUE;
2494 }
2495 return NO_ERROR;
2496}
2497
2498status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2499 uid_t uid)
2500{
2501 ALOGV("releaseAudioPatch() patch %d", handle);
2502
2503 ssize_t index = mAudioPatches.indexOfKey(handle);
2504
2505 if (index < 0) {
2506 return BAD_VALUE;
2507 }
2508 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2509 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2510 mUidCached, patchDesc->mUid, uid);
2511 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2512 return INVALID_OPERATION;
2513 }
2514
2515 struct audio_patch *patch = &patchDesc->mPatch;
2516 patchDesc->mUid = mUidCached;
2517 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002518 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002519 if (outputDesc == NULL) {
2520 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2521 return BAD_VALUE;
2522 }
2523
2524 setOutputDevice(outputDesc->mIoHandle,
2525 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2526 true,
2527 0,
2528 NULL);
2529 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2530 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002531 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002532 if (inputDesc == NULL) {
2533 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2534 return BAD_VALUE;
2535 }
2536 setInputDevice(inputDesc->mIoHandle,
2537 getNewInputDevice(inputDesc->mIoHandle),
2538 true,
2539 NULL);
2540 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2541 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2542 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2543 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2544 status, patchDesc->mAfPatchHandle);
2545 removeAudioPatch(patchDesc->mHandle);
2546 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002547 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002548 } else {
2549 return BAD_VALUE;
2550 }
2551 } else {
2552 return BAD_VALUE;
2553 }
2554 return NO_ERROR;
2555}
2556
2557status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2558 struct audio_patch *patches,
2559 unsigned int *generation)
2560{
2561 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2562 generation == NULL) {
2563 return BAD_VALUE;
2564 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002565 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002566 *num_patches, patches, mAudioPatches.size());
2567 if (patches == NULL) {
2568 *num_patches = 0;
2569 }
2570
2571 size_t patchesWritten = 0;
2572 size_t patchesMax = *num_patches;
2573 for (size_t i = 0;
2574 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2575 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2576 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002577 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002578 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2579 }
2580 *num_patches = mAudioPatches.size();
2581
2582 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002583 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002584 return NO_ERROR;
2585}
2586
Eric Laurente1715a42014-05-20 11:30:42 -07002587status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002588{
Eric Laurente1715a42014-05-20 11:30:42 -07002589 ALOGV("setAudioPortConfig()");
2590
2591 if (config == NULL) {
2592 return BAD_VALUE;
2593 }
2594 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2595 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002596 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2597 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002598 }
2599
Eric Laurenta121f902014-06-03 13:32:54 -07002600 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002601 if (config->type == AUDIO_PORT_TYPE_MIX) {
2602 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002603 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002604 if (outputDesc == NULL) {
2605 return BAD_VALUE;
2606 }
Eric Laurent84c70242014-06-23 08:46:27 -07002607 ALOG_ASSERT(!outputDesc->isDuplicated(),
2608 "setAudioPortConfig() called on duplicated output %d",
2609 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002610 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002611 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002612 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002613 if (inputDesc == NULL) {
2614 return BAD_VALUE;
2615 }
Eric Laurenta121f902014-06-03 13:32:54 -07002616 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002617 } else {
2618 return BAD_VALUE;
2619 }
2620 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2621 sp<DeviceDescriptor> deviceDesc;
2622 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2623 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2624 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2625 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2626 } else {
2627 return BAD_VALUE;
2628 }
2629 if (deviceDesc == NULL) {
2630 return BAD_VALUE;
2631 }
Eric Laurenta121f902014-06-03 13:32:54 -07002632 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002633 } else {
2634 return BAD_VALUE;
2635 }
2636
Eric Laurenta121f902014-06-03 13:32:54 -07002637 struct audio_port_config backupConfig;
2638 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2639 if (status == NO_ERROR) {
2640 struct audio_port_config newConfig;
2641 audioPortConfig->toAudioPortConfig(&newConfig, config);
2642 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002643 }
Eric Laurenta121f902014-06-03 13:32:54 -07002644 if (status != NO_ERROR) {
2645 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002646 }
Eric Laurente1715a42014-05-20 11:30:42 -07002647
2648 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002649}
2650
2651void AudioPolicyManager::clearAudioPatches(uid_t uid)
2652{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002653 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002654 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2655 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002656 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002657 }
2658 }
2659}
2660
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002661status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2662 audio_io_handle_t *ioHandle,
2663 audio_devices_t *device)
2664{
2665 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2666 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2667 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2668
2669 mSoundTriggerSessions.add(*session, *ioHandle);
2670
2671 return NO_ERROR;
2672}
2673
2674status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2675{
2676 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2677 if (index < 0) {
2678 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2679 return BAD_VALUE;
2680 }
2681
2682 mSoundTriggerSessions.removeItem(session);
2683 return NO_ERROR;
2684}
2685
Eric Laurent6a94d692014-05-20 11:18:06 -07002686status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2687 const sp<AudioPatch>& patch)
2688{
2689 ssize_t index = mAudioPatches.indexOfKey(handle);
2690
2691 if (index >= 0) {
2692 ALOGW("addAudioPatch() patch %d already in", handle);
2693 return ALREADY_EXISTS;
2694 }
2695 mAudioPatches.add(handle, patch);
2696 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2697 "sink handle %d",
2698 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2699 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2700 return NO_ERROR;
2701}
2702
2703status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2704{
2705 ssize_t index = mAudioPatches.indexOfKey(handle);
2706
2707 if (index < 0) {
2708 ALOGW("removeAudioPatch() patch %d not in", handle);
2709 return ALREADY_EXISTS;
2710 }
2711 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2712 mAudioPatches.valueAt(index)->mAfPatchHandle);
2713 mAudioPatches.removeItemsAt(index);
2714 return NO_ERROR;
2715}
2716
Eric Laurente552edb2014-03-10 17:42:56 -07002717// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002718// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002719// ----------------------------------------------------------------------------
2720
Eric Laurent3a4311c2014-03-17 12:00:47 -07002721uint32_t AudioPolicyManager::nextUniqueId()
2722{
2723 return android_atomic_inc(&mNextUniqueId);
2724}
2725
Eric Laurent6a94d692014-05-20 11:18:06 -07002726uint32_t AudioPolicyManager::nextAudioPortGeneration()
2727{
2728 return android_atomic_inc(&mAudioPortGeneration);
2729}
2730
Eric Laurente0720872014-03-11 09:30:41 -07002731AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002732 :
2733#ifdef AUDIO_POLICY_TEST
2734 Thread(false),
2735#endif //AUDIO_POLICY_TEST
2736 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002737 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002738 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2739 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002740 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002741 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002742 mAudioPortGeneration(1),
2743 mBeaconMuteRefCount(0),
2744 mBeaconPlayingRefCount(0),
2745 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002746{
Eric Laurent6a94d692014-05-20 11:18:06 -07002747 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002748 mpClientInterface = clientInterface;
2749
Eric Laurent3b73df72014-03-11 09:06:29 -07002750 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2751 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002752 }
2753
Eric Laurent1afeecb2014-05-14 08:52:28 -07002754 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002755 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2756 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2757 ALOGE("could not load audio policy configuration file, setting defaults");
2758 defaultAudioPolicyConfig();
2759 }
2760 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002761 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002762
2763 // must be done after reading the policy
2764 initializeVolumeCurves();
2765
2766 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002767 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2768 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002769 for (size_t i = 0; i < mHwModules.size(); i++) {
2770 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2771 if (mHwModules[i]->mHandle == 0) {
2772 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2773 continue;
2774 }
2775 // open all output streams needed to access attached devices
2776 // except for direct output streams that are only opened when they are actually
2777 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002778 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002779 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2780 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002781 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002782
Eric Laurent3a4311c2014-03-17 12:00:47 -07002783 if (outProfile->mSupportedDevices.isEmpty()) {
2784 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2785 continue;
2786 }
2787
Eric Laurentd78f1532014-09-16 16:38:20 -07002788 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2789 continue;
2790 }
Eric Laurent83b88082014-06-20 18:31:16 -07002791 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2792 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2793 profileType = mDefaultOutputDevice->mDeviceType;
2794 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002795 // chose first device present in mSupportedDevices also part of
2796 // outputDeviceTypes
2797 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2798 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2799 if ((profileType & outputDeviceTypes) != 0) {
2800 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002801 }
Eric Laurente552edb2014-03-10 17:42:56 -07002802 }
2803 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002804 if ((profileType & outputDeviceTypes) == 0) {
2805 continue;
2806 }
2807 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2808
2809 outputDesc->mDevice = profileType;
2810 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2811 config.sample_rate = outputDesc->mSamplingRate;
2812 config.channel_mask = outputDesc->mChannelMask;
2813 config.format = outputDesc->mFormat;
2814 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2815 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2816 &output,
2817 &config,
2818 &outputDesc->mDevice,
2819 String8(""),
2820 &outputDesc->mLatency,
2821 outputDesc->mFlags);
2822
2823 if (status != NO_ERROR) {
2824 ALOGW("Cannot open output stream for device %08x on hw module %s",
2825 outputDesc->mDevice,
2826 mHwModules[i]->mName);
2827 } else {
2828 outputDesc->mSamplingRate = config.sample_rate;
2829 outputDesc->mChannelMask = config.channel_mask;
2830 outputDesc->mFormat = config.format;
2831
2832 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2833 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2834 ssize_t index =
2835 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2836 // give a valid ID to an attached device once confirmed it is reachable
2837 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2838 mAvailableOutputDevices[index]->mId = nextUniqueId();
2839 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2840 }
2841 }
2842 if (mPrimaryOutput == 0 &&
2843 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2844 mPrimaryOutput = output;
2845 }
2846 addOutput(output, outputDesc);
2847 setOutputDevice(output,
2848 outputDesc->mDevice,
2849 true);
2850 }
Eric Laurente552edb2014-03-10 17:42:56 -07002851 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002852 // open input streams needed to access attached devices to validate
2853 // mAvailableInputDevices list
2854 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2855 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002856 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002857
Eric Laurent3a4311c2014-03-17 12:00:47 -07002858 if (inProfile->mSupportedDevices.isEmpty()) {
2859 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2860 continue;
2861 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002862 // chose first device present in mSupportedDevices also part of
2863 // inputDeviceTypes
2864 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2865 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2866 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2867 if (profileType & inputDeviceTypes) {
2868 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002869 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002870 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002871 if ((profileType & inputDeviceTypes) == 0) {
2872 continue;
2873 }
2874 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2875
2876 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2877 inputDesc->mDevice = profileType;
2878
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002879 // find the address
2880 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
2881 // the inputs vector must be of size 1, but we don't want to crash here
2882 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
2883 : String8("");
2884 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
2885 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
2886
Eric Laurentd78f1532014-09-16 16:38:20 -07002887 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2888 config.sample_rate = inputDesc->mSamplingRate;
2889 config.channel_mask = inputDesc->mChannelMask;
2890 config.format = inputDesc->mFormat;
2891 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2892 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2893 &input,
2894 &config,
2895 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002896 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07002897 AUDIO_SOURCE_MIC,
2898 AUDIO_INPUT_FLAG_NONE);
2899
2900 if (status == NO_ERROR) {
2901 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2902 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2903 ssize_t index =
2904 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2905 // give a valid ID to an attached device once confirmed it is reachable
2906 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2907 mAvailableInputDevices[index]->mId = nextUniqueId();
2908 mAvailableInputDevices[index]->mModule = mHwModules[i];
2909 }
2910 }
2911 mpClientInterface->closeInput(input);
2912 } else {
2913 ALOGW("Cannot open input stream for device %08x on hw module %s",
2914 inputDesc->mDevice,
2915 mHwModules[i]->mName);
2916 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002917 }
2918 }
2919 // make sure all attached devices have been allocated a unique ID
2920 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2921 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002922 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002923 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2924 continue;
2925 }
2926 i++;
2927 }
2928 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2929 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002930 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002931 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2932 continue;
2933 }
2934 i++;
2935 }
2936 // make sure default device is reachable
2937 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002938 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002939 }
Eric Laurente552edb2014-03-10 17:42:56 -07002940
2941 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2942
2943 updateDevicesAndOutputs();
2944
2945#ifdef AUDIO_POLICY_TEST
2946 if (mPrimaryOutput != 0) {
2947 AudioParameter outputCmd = AudioParameter();
2948 outputCmd.addInt(String8("set_id"), 0);
2949 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2950
2951 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2952 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002953 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2954 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002955 mTestLatencyMs = 0;
2956 mCurOutput = 0;
2957 mDirectOutput = false;
2958 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2959 mTestOutputs[i] = 0;
2960 }
2961
2962 const size_t SIZE = 256;
2963 char buffer[SIZE];
2964 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2965 run(buffer, ANDROID_PRIORITY_AUDIO);
2966 }
2967#endif //AUDIO_POLICY_TEST
2968}
2969
Eric Laurente0720872014-03-11 09:30:41 -07002970AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002971{
2972#ifdef AUDIO_POLICY_TEST
2973 exit();
2974#endif //AUDIO_POLICY_TEST
2975 for (size_t i = 0; i < mOutputs.size(); i++) {
2976 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002977 }
2978 for (size_t i = 0; i < mInputs.size(); i++) {
2979 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002980 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002981 mAvailableOutputDevices.clear();
2982 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002983 mOutputs.clear();
2984 mInputs.clear();
2985 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002986}
2987
Eric Laurente0720872014-03-11 09:30:41 -07002988status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002989{
2990 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2991}
2992
2993#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002994bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002995{
2996 ALOGV("entering threadLoop()");
2997 while (!exitPending())
2998 {
2999 String8 command;
3000 int valueInt;
3001 String8 value;
3002
3003 Mutex::Autolock _l(mLock);
3004 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3005
3006 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3007 AudioParameter param = AudioParameter(command);
3008
3009 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3010 valueInt != 0) {
3011 ALOGV("Test command %s received", command.string());
3012 String8 target;
3013 if (param.get(String8("target"), target) != NO_ERROR) {
3014 target = "Manager";
3015 }
3016 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3017 param.remove(String8("test_cmd_policy_output"));
3018 mCurOutput = valueInt;
3019 }
3020 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3021 param.remove(String8("test_cmd_policy_direct"));
3022 if (value == "false") {
3023 mDirectOutput = false;
3024 } else if (value == "true") {
3025 mDirectOutput = true;
3026 }
3027 }
3028 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3029 param.remove(String8("test_cmd_policy_input"));
3030 mTestInput = valueInt;
3031 }
3032
3033 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3034 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003035 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003036 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003037 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003038 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003039 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003040 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003041 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003042 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003043 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003044 if (target == "Manager") {
3045 mTestFormat = format;
3046 } else if (mTestOutputs[mCurOutput] != 0) {
3047 AudioParameter outputParam = AudioParameter();
3048 outputParam.addInt(String8("format"), format);
3049 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3050 }
3051 }
3052 }
3053 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3054 param.remove(String8("test_cmd_policy_channels"));
3055 int channels = 0;
3056
3057 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003058 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003059 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003060 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003061 }
3062 if (channels != 0) {
3063 if (target == "Manager") {
3064 mTestChannels = channels;
3065 } else if (mTestOutputs[mCurOutput] != 0) {
3066 AudioParameter outputParam = AudioParameter();
3067 outputParam.addInt(String8("channels"), channels);
3068 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3069 }
3070 }
3071 }
3072 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3073 param.remove(String8("test_cmd_policy_sampleRate"));
3074 if (valueInt >= 0 && valueInt <= 96000) {
3075 int samplingRate = valueInt;
3076 if (target == "Manager") {
3077 mTestSamplingRate = samplingRate;
3078 } else if (mTestOutputs[mCurOutput] != 0) {
3079 AudioParameter outputParam = AudioParameter();
3080 outputParam.addInt(String8("sampling_rate"), samplingRate);
3081 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3082 }
3083 }
3084 }
3085
3086 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3087 param.remove(String8("test_cmd_policy_reopen"));
3088
Eric Laurent1f2f2232014-06-02 12:01:23 -07003089 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003090 mpClientInterface->closeOutput(mPrimaryOutput);
3091
3092 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3093
Eric Laurente552edb2014-03-10 17:42:56 -07003094 mOutputs.removeItem(mPrimaryOutput);
3095
Eric Laurent1f2f2232014-06-02 12:01:23 -07003096 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003097 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003098 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3099 config.sample_rate = outputDesc->mSamplingRate;
3100 config.channel_mask = outputDesc->mChannelMask;
3101 config.format = outputDesc->mFormat;
3102 status_t status = mpClientInterface->openOutput(moduleHandle,
3103 &mPrimaryOutput,
3104 &config,
3105 &outputDesc->mDevice,
3106 String8(""),
3107 &outputDesc->mLatency,
3108 outputDesc->mFlags);
3109 if (status != NO_ERROR) {
3110 ALOGE("Failed to reopen hardware output stream, "
3111 "samplingRate: %d, format %d, channels %d",
3112 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003113 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003114 outputDesc->mSamplingRate = config.sample_rate;
3115 outputDesc->mChannelMask = config.channel_mask;
3116 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003117 AudioParameter outputCmd = AudioParameter();
3118 outputCmd.addInt(String8("set_id"), 0);
3119 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3120 addOutput(mPrimaryOutput, outputDesc);
3121 }
3122 }
3123
3124
3125 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3126 }
3127 }
3128 return false;
3129}
3130
Eric Laurente0720872014-03-11 09:30:41 -07003131void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003132{
3133 {
3134 AutoMutex _l(mLock);
3135 requestExit();
3136 mWaitWorkCV.signal();
3137 }
3138 requestExitAndWait();
3139}
3140
Eric Laurente0720872014-03-11 09:30:41 -07003141int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003142{
3143 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3144 if (output == mTestOutputs[i]) return i;
3145 }
3146 return 0;
3147}
3148#endif //AUDIO_POLICY_TEST
3149
3150// ---
3151
Eric Laurent1f2f2232014-06-02 12:01:23 -07003152void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003153{
Eric Laurent1c333e22014-05-20 10:48:17 -07003154 outputDesc->mIoHandle = output;
3155 outputDesc->mId = nextUniqueId();
3156 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003157 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003158}
3159
Eric Laurent1f2f2232014-06-02 12:01:23 -07003160void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003161{
Eric Laurent1c333e22014-05-20 10:48:17 -07003162 inputDesc->mIoHandle = input;
3163 inputDesc->mId = nextUniqueId();
3164 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003165 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003166}
Eric Laurente552edb2014-03-10 17:42:56 -07003167
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003168void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3169 const String8 address /*in*/,
3170 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3171 // look for a match on the given address on the addresses of the outputs:
3172 // find the address by finding the patch that maps to this output
3173 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3174 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3175 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3176 if (patchIdx >= 0) {
3177 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3178 const int numSinks = patchDesc->mPatch.num_sinks;
3179 for (ssize_t j=0; j < numSinks; j++) {
3180 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3181 const char* patchAddr =
3182 patchDesc->mPatch.sinks[j].ext.device.address;
3183 if (strncmp(patchAddr,
3184 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003185 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003186 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3187 outputs.add(desc->mIoHandle);
3188 break;
3189 }
3190 }
3191 }
3192 }
3193}
3194
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003195status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003196 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003197 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003198 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003199{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003200 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003201 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003202 // erase all current sample rates, formats and channel masks
3203 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003204
Eric Laurent3b73df72014-03-11 09:06:29 -07003205 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003206 // first list already open outputs that can be routed to this device
3207 for (size_t i = 0; i < mOutputs.size(); i++) {
3208 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003209 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003210 if (!deviceDistinguishesOnAddress(device)) {
3211 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3212 outputs.add(mOutputs.keyAt(i));
3213 } else {
3214 ALOGV(" checking address match due to device 0x%x", device);
3215 findIoHandlesByAddress(desc, address, outputs);
3216 }
Eric Laurente552edb2014-03-10 17:42:56 -07003217 }
3218 }
3219 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003220 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003221 for (size_t i = 0; i < mHwModules.size(); i++)
3222 {
3223 if (mHwModules[i]->mHandle == 0) {
3224 continue;
3225 }
3226 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3227 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003228 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003229 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003230 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3231 }
3232 }
3233 }
3234
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003235 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3236
Eric Laurente552edb2014-03-10 17:42:56 -07003237 if (profiles.isEmpty() && outputs.isEmpty()) {
3238 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3239 return BAD_VALUE;
3240 }
3241
3242 // open outputs for matching profiles if needed. Direct outputs are also opened to
3243 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3244 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003245 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003246
3247 // nothing to do if one output is already opened for this profile
3248 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003249 for (j = 0; j < outputs.size(); j++) {
3250 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003251 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003252 // matching profile: save the sample rates, format and channel masks supported
3253 // by the profile in our device descriptor
3254 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003255 break;
3256 }
3257 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003258 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003259 continue;
3260 }
3261
Eric Laurent83b88082014-06-20 18:31:16 -07003262 ALOGV("opening output for device %08x with params %s profile %p",
3263 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003264 desc = new AudioOutputDescriptor(profile);
3265 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003266 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3267 config.sample_rate = desc->mSamplingRate;
3268 config.channel_mask = desc->mChannelMask;
3269 config.format = desc->mFormat;
3270 config.offload_info.sample_rate = desc->mSamplingRate;
3271 config.offload_info.channel_mask = desc->mChannelMask;
3272 config.offload_info.format = desc->mFormat;
3273 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3274 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3275 &output,
3276 &config,
3277 &desc->mDevice,
3278 address,
3279 &desc->mLatency,
3280 desc->mFlags);
3281 if (status == NO_ERROR) {
3282 desc->mSamplingRate = config.sample_rate;
3283 desc->mChannelMask = config.channel_mask;
3284 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003285
Eric Laurentd4692962014-05-05 18:13:44 -07003286 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003287 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003288 char *param = audio_device_address_to_parameter(device, address);
3289 mpClientInterface->setParameters(output, String8(param));
3290 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003291 }
3292
Eric Laurentd4692962014-05-05 18:13:44 -07003293 // Here is where we step through and resolve any "dynamic" fields
3294 String8 reply;
3295 char *value;
3296 if (profile->mSamplingRates[0] == 0) {
3297 reply = mpClientInterface->getParameters(output,
3298 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003299 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003300 reply.string());
3301 value = strpbrk((char *)reply.string(), "=");
3302 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003303 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003304 }
Eric Laurentd4692962014-05-05 18:13:44 -07003305 }
3306 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3307 reply = mpClientInterface->getParameters(output,
3308 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003309 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003310 reply.string());
3311 value = strpbrk((char *)reply.string(), "=");
3312 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003313 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003314 }
Eric Laurentd4692962014-05-05 18:13:44 -07003315 }
3316 if (profile->mChannelMasks[0] == 0) {
3317 reply = mpClientInterface->getParameters(output,
3318 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003319 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003320 reply.string());
3321 value = strpbrk((char *)reply.string(), "=");
3322 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003323 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003324 }
Eric Laurentd4692962014-05-05 18:13:44 -07003325 }
3326 if (((profile->mSamplingRates[0] == 0) &&
3327 (profile->mSamplingRates.size() < 2)) ||
3328 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3329 (profile->mFormats.size() < 2)) ||
3330 ((profile->mChannelMasks[0] == 0) &&
3331 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003332 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003333 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003334 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003335 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3336 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003337 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003338 config.sample_rate = profile->pickSamplingRate();
3339 config.channel_mask = profile->pickChannelMask();
3340 config.format = profile->pickFormat();
3341 config.offload_info.sample_rate = config.sample_rate;
3342 config.offload_info.channel_mask = config.channel_mask;
3343 config.offload_info.format = config.format;
3344 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3345 &output,
3346 &config,
3347 &desc->mDevice,
3348 address,
3349 &desc->mLatency,
3350 desc->mFlags);
3351 if (status == NO_ERROR) {
3352 desc->mSamplingRate = config.sample_rate;
3353 desc->mChannelMask = config.channel_mask;
3354 desc->mFormat = config.format;
3355 } else {
3356 output = AUDIO_IO_HANDLE_NONE;
3357 }
Eric Laurentd4692962014-05-05 18:13:44 -07003358 }
3359
Eric Laurentcf2c0212014-07-25 16:20:43 -07003360 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003361 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003362 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003363 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003364
Eric Laurentd4692962014-05-05 18:13:44 -07003365 // set initial stream volume for device
3366 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003367
Eric Laurentd4692962014-05-05 18:13:44 -07003368 //TODO: configure audio effect output stage here
3369
3370 // open a duplicating output thread for the new output and the primary output
3371 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3372 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003373 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003374 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003375 sp<AudioOutputDescriptor> dupOutputDesc =
3376 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003377 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3378 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3379 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3380 dupOutputDesc->mFormat = desc->mFormat;
3381 dupOutputDesc->mChannelMask = desc->mChannelMask;
3382 dupOutputDesc->mLatency = desc->mLatency;
3383 addOutput(duplicatedOutput, dupOutputDesc);
3384 applyStreamVolumes(duplicatedOutput, device, 0, true);
3385 } else {
3386 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3387 mPrimaryOutput, output);
3388 mpClientInterface->closeOutput(output);
3389 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003390 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003391 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003392 }
Eric Laurente552edb2014-03-10 17:42:56 -07003393 }
3394 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003395 } else {
3396 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003397 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003398 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003399 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003400 profiles.removeAt(profile_index);
3401 profile_index--;
3402 } else {
3403 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003404 devDesc->importAudioPort(profile);
3405
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003406 if (deviceDistinguishesOnAddress(device)) {
3407 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3408 device, address.string());
3409 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3410 NULL/*patch handle*/, address.string());
3411 }
Eric Laurente552edb2014-03-10 17:42:56 -07003412 ALOGV("checkOutputsForDevice(): adding output %d", output);
3413 }
3414 }
3415
3416 if (profiles.isEmpty()) {
3417 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3418 return BAD_VALUE;
3419 }
Eric Laurentd4692962014-05-05 18:13:44 -07003420 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003421 // check if one opened output is not needed any more after disconnecting one device
3422 for (size_t i = 0; i < mOutputs.size(); i++) {
3423 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003424 if (!desc->isDuplicated()) {
3425 if (!(desc->mProfile->mSupportedDevices.types()
3426 & mAvailableOutputDevices.types())) {
3427 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3428 mOutputs.keyAt(i));
3429 outputs.add(mOutputs.keyAt(i));
3430 } else if (deviceDistinguishesOnAddress(device) &&
3431 // exact match on device
3432 (desc->mProfile->mSupportedDevices.types() == device)) {
3433 findIoHandlesByAddress(desc, address, outputs);
3434 }
Eric Laurente552edb2014-03-10 17:42:56 -07003435 }
3436 }
Eric Laurentd4692962014-05-05 18:13:44 -07003437 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003438 for (size_t i = 0; i < mHwModules.size(); i++)
3439 {
3440 if (mHwModules[i]->mHandle == 0) {
3441 continue;
3442 }
3443 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3444 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003445 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003446 if (profile->mSupportedDevices.types() & device) {
3447 ALOGV("checkOutputsForDevice(): "
3448 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003449 if (profile->mSamplingRates[0] == 0) {
3450 profile->mSamplingRates.clear();
3451 profile->mSamplingRates.add(0);
3452 }
3453 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3454 profile->mFormats.clear();
3455 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3456 }
3457 if (profile->mChannelMasks[0] == 0) {
3458 profile->mChannelMasks.clear();
3459 profile->mChannelMasks.add(0);
3460 }
3461 }
3462 }
3463 }
3464 }
3465 return NO_ERROR;
3466}
3467
Eric Laurentd4692962014-05-05 18:13:44 -07003468status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3469 audio_policy_dev_state_t state,
3470 SortedVector<audio_io_handle_t>& inputs,
3471 const String8 address)
3472{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003473 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003474 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3475 // first list already open inputs that can be routed to this device
3476 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3477 desc = mInputs.valueAt(input_index);
3478 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3479 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3480 inputs.add(mInputs.keyAt(input_index));
3481 }
3482 }
3483
3484 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003485 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003486 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3487 {
3488 if (mHwModules[module_idx]->mHandle == 0) {
3489 continue;
3490 }
3491 for (size_t profile_index = 0;
3492 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3493 profile_index++)
3494 {
3495 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3496 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003497 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003498 profile_index, module_idx);
3499 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3500 }
3501 }
3502 }
3503
3504 if (profiles.isEmpty() && inputs.isEmpty()) {
3505 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3506 return BAD_VALUE;
3507 }
3508
3509 // open inputs for matching profiles if needed. Direct inputs are also opened to
3510 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3511 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3512
Eric Laurent1c333e22014-05-20 10:48:17 -07003513 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003514 // nothing to do if one input is already opened for this profile
3515 size_t input_index;
3516 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3517 desc = mInputs.valueAt(input_index);
3518 if (desc->mProfile == profile) {
3519 break;
3520 }
3521 }
3522 if (input_index != mInputs.size()) {
3523 continue;
3524 }
3525
3526 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3527 desc = new AudioInputDescriptor(profile);
3528 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003529 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3530 config.sample_rate = desc->mSamplingRate;
3531 config.channel_mask = desc->mChannelMask;
3532 config.format = desc->mFormat;
3533 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3534 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3535 &input,
3536 &config,
3537 &desc->mDevice,
3538 address,
3539 AUDIO_SOURCE_MIC,
3540 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003541
Eric Laurentcf2c0212014-07-25 16:20:43 -07003542 if (status == NO_ERROR) {
3543 desc->mSamplingRate = config.sample_rate;
3544 desc->mChannelMask = config.channel_mask;
3545 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003546
Eric Laurentd4692962014-05-05 18:13:44 -07003547 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003548 char *param = audio_device_address_to_parameter(device, address);
3549 mpClientInterface->setParameters(input, String8(param));
3550 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003551 }
3552
3553 // Here is where we step through and resolve any "dynamic" fields
3554 String8 reply;
3555 char *value;
3556 if (profile->mSamplingRates[0] == 0) {
3557 reply = mpClientInterface->getParameters(input,
3558 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3559 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3560 reply.string());
3561 value = strpbrk((char *)reply.string(), "=");
3562 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003563 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003564 }
3565 }
3566 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3567 reply = mpClientInterface->getParameters(input,
3568 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3569 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3570 value = strpbrk((char *)reply.string(), "=");
3571 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003572 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003573 }
3574 }
3575 if (profile->mChannelMasks[0] == 0) {
3576 reply = mpClientInterface->getParameters(input,
3577 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3578 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3579 reply.string());
3580 value = strpbrk((char *)reply.string(), "=");
3581 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003582 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003583 }
3584 }
3585 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3586 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3587 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3588 ALOGW("checkInputsForDevice() direct input missing param");
3589 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003590 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003591 }
3592
3593 if (input != 0) {
3594 addInput(input, desc);
3595 }
3596 } // endif input != 0
3597
Eric Laurentcf2c0212014-07-25 16:20:43 -07003598 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003599 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003600 profiles.removeAt(profile_index);
3601 profile_index--;
3602 } else {
3603 inputs.add(input);
3604 ALOGV("checkInputsForDevice(): adding input %d", input);
3605 }
3606 } // end scan profiles
3607
3608 if (profiles.isEmpty()) {
3609 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3610 return BAD_VALUE;
3611 }
3612 } else {
3613 // Disconnect
3614 // check if one opened input is not needed any more after disconnecting one device
3615 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3616 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003617 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3618 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003619 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3620 mInputs.keyAt(input_index));
3621 inputs.add(mInputs.keyAt(input_index));
3622 }
3623 }
3624 // Clear any profiles associated with the disconnected device.
3625 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3626 if (mHwModules[module_index]->mHandle == 0) {
3627 continue;
3628 }
3629 for (size_t profile_index = 0;
3630 profile_index < mHwModules[module_index]->mInputProfiles.size();
3631 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003632 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003633 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003634 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003635 profile_index, module_index);
3636 if (profile->mSamplingRates[0] == 0) {
3637 profile->mSamplingRates.clear();
3638 profile->mSamplingRates.add(0);
3639 }
3640 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3641 profile->mFormats.clear();
3642 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3643 }
3644 if (profile->mChannelMasks[0] == 0) {
3645 profile->mChannelMasks.clear();
3646 profile->mChannelMasks.add(0);
3647 }
3648 }
3649 }
3650 }
3651 } // end disconnect
3652
3653 return NO_ERROR;
3654}
3655
3656
Eric Laurente0720872014-03-11 09:30:41 -07003657void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003658{
3659 ALOGV("closeOutput(%d)", output);
3660
Eric Laurent1f2f2232014-06-02 12:01:23 -07003661 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003662 if (outputDesc == NULL) {
3663 ALOGW("closeOutput() unknown output %d", output);
3664 return;
3665 }
3666
3667 // look for duplicated outputs connected to the output being removed.
3668 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003669 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003670 if (dupOutputDesc->isDuplicated() &&
3671 (dupOutputDesc->mOutput1 == outputDesc ||
3672 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003673 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003674 if (dupOutputDesc->mOutput1 == outputDesc) {
3675 outputDesc2 = dupOutputDesc->mOutput2;
3676 } else {
3677 outputDesc2 = dupOutputDesc->mOutput1;
3678 }
3679 // As all active tracks on duplicated output will be deleted,
3680 // and as they were also referenced on the other output, the reference
3681 // count for their stream type must be adjusted accordingly on
3682 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003683 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003684 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003685 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003686 }
3687 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3688 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3689
3690 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003691 mOutputs.removeItem(duplicatedOutput);
3692 }
3693 }
3694
Eric Laurent05b90f82014-08-27 15:32:29 -07003695 nextAudioPortGeneration();
3696
3697 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3698 if (index >= 0) {
3699 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3700 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3701 mAudioPatches.removeItemsAt(index);
3702 mpClientInterface->onAudioPatchListUpdate();
3703 }
3704
Eric Laurente552edb2014-03-10 17:42:56 -07003705 AudioParameter param;
3706 param.add(String8("closing"), String8("true"));
3707 mpClientInterface->setParameters(output, param.toString());
3708
3709 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003710 mOutputs.removeItem(output);
3711 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003712}
3713
3714void AudioPolicyManager::closeInput(audio_io_handle_t input)
3715{
3716 ALOGV("closeInput(%d)", input);
3717
3718 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3719 if (inputDesc == NULL) {
3720 ALOGW("closeInput() unknown input %d", input);
3721 return;
3722 }
3723
Eric Laurent6a94d692014-05-20 11:18:06 -07003724 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003725
3726 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3727 if (index >= 0) {
3728 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3729 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3730 mAudioPatches.removeItemsAt(index);
3731 mpClientInterface->onAudioPatchListUpdate();
3732 }
3733
3734 mpClientInterface->closeInput(input);
3735 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003736}
3737
Eric Laurente0720872014-03-11 09:30:41 -07003738SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003739 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003740{
3741 SortedVector<audio_io_handle_t> outputs;
3742
3743 ALOGVV("getOutputsForDevice() device %04x", device);
3744 for (size_t i = 0; i < openOutputs.size(); i++) {
3745 ALOGVV("output %d isDuplicated=%d device=%04x",
3746 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3747 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3748 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3749 outputs.add(openOutputs.keyAt(i));
3750 }
3751 }
3752 return outputs;
3753}
3754
Eric Laurente0720872014-03-11 09:30:41 -07003755bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003756 SortedVector<audio_io_handle_t>& outputs2)
3757{
3758 if (outputs1.size() != outputs2.size()) {
3759 return false;
3760 }
3761 for (size_t i = 0; i < outputs1.size(); i++) {
3762 if (outputs1[i] != outputs2[i]) {
3763 return false;
3764 }
3765 }
3766 return true;
3767}
3768
Eric Laurente0720872014-03-11 09:30:41 -07003769void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003770{
3771 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3772 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3773 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3774 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3775
3776 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3777 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3778 strategy, srcOutputs[0], dstOutputs[0]);
3779 // mute strategy while moving tracks from one output to another
3780 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003781 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003782 if (desc->isStrategyActive(strategy)) {
3783 setStrategyMute(strategy, true, srcOutputs[i]);
3784 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3785 }
3786 }
3787
3788 // Move effects associated to this strategy from previous output to new output
3789 if (strategy == STRATEGY_MEDIA) {
3790 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3791 SortedVector<audio_io_handle_t> moved;
3792 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003793 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3794 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3795 effectDesc->mIo != fxOutput) {
3796 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003797 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3798 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003799 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003800 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003801 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003802 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003803 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003804 }
3805 }
3806 }
3807 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003808 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08003809 if (i == AUDIO_STREAM_PATCH) {
3810 continue;
3811 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003812 if (getStrategy((audio_stream_type_t)i) == strategy) {
3813 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003814 }
3815 }
3816 }
3817}
3818
Eric Laurente0720872014-03-11 09:30:41 -07003819void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003820{
Jon Eklund966095e2014-09-09 15:39:49 -05003821 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3822 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003823 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003824 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3825 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003826 checkOutputForStrategy(STRATEGY_SONIFICATION);
3827 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003828 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07003829 checkOutputForStrategy(STRATEGY_MEDIA);
3830 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003831 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07003832}
3833
Eric Laurente0720872014-03-11 09:30:41 -07003834audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003835{
Eric Laurente552edb2014-03-10 17:42:56 -07003836 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003837 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003838 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3839 return mOutputs.keyAt(i);
3840 }
3841 }
3842
3843 return 0;
3844}
3845
Eric Laurente0720872014-03-11 09:30:41 -07003846void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003847{
Eric Laurente552edb2014-03-10 17:42:56 -07003848 audio_io_handle_t a2dpOutput = getA2dpOutput();
3849 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003850 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003851 return;
3852 }
3853
Eric Laurent3a4311c2014-03-17 12:00:47 -07003854 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08003855 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
3856 ~AUDIO_DEVICE_BIT_IN) != 0) ||
3857 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003858 // suspend A2DP output if:
3859 // (NOT already suspended) &&
3860 // ((SCO device is connected &&
3861 // (forced usage for communication || for record is SCO))) ||
3862 // (phone state is ringing || in call)
3863 //
3864 // restore A2DP output if:
3865 // (Already suspended) &&
3866 // ((SCO device is NOT connected ||
3867 // (forced usage NOT for communication && NOT for record is SCO))) &&
3868 // (phone state is NOT ringing && NOT in call)
3869 //
3870 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003871 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003872 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3873 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3874 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3875 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003876
3877 mpClientInterface->restoreOutput(a2dpOutput);
3878 mA2dpSuspended = false;
3879 }
3880 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003881 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003882 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3883 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3884 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3885 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003886
3887 mpClientInterface->suspendOutput(a2dpOutput);
3888 mA2dpSuspended = true;
3889 }
3890 }
3891}
3892
Eric Laurent1c333e22014-05-20 10:48:17 -07003893audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003894{
3895 audio_devices_t device = AUDIO_DEVICE_NONE;
3896
Eric Laurent1f2f2232014-06-02 12:01:23 -07003897 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003898
3899 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3900 if (index >= 0) {
3901 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3902 if (patchDesc->mUid != mUidCached) {
3903 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3904 outputDesc->device(), outputDesc->mPatchHandle);
3905 return outputDesc->device();
3906 }
3907 }
3908
Eric Laurente552edb2014-03-10 17:42:56 -07003909 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003910 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003911 // use device for strategy enforced audible
3912 // 2: we are in call or the strategy phone is active on the output:
3913 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003914 // 3: the strategy for enforced audible is active but not enforced on the output:
3915 // use the device for strategy enforced audible
3916 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003917 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003918 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003919 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08003920 // 6: the strategy accessibility is active on the output:
3921 // use device for strategy accessibility
3922 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003923 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08003924 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003925 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08003926 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003927 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05003928 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3929 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003930 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3931 } else if (isInCall() ||
3932 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3933 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003934 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3935 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003936 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3937 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3938 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3939 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003940 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
3941 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003942 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3943 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3944 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3945 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003946 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
3947 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003948 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
3949 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003950 }
3951
Eric Laurent1c333e22014-05-20 10:48:17 -07003952 ALOGV("getNewOutputDevice() selected device %x", device);
3953 return device;
3954}
3955
3956audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3957{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003958 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003959
3960 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3961 if (index >= 0) {
3962 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3963 if (patchDesc->mUid != mUidCached) {
3964 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3965 inputDesc->mDevice, inputDesc->mPatchHandle);
3966 return inputDesc->mDevice;
3967 }
3968 }
3969
Eric Laurent1c333e22014-05-20 10:48:17 -07003970 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3971
3972 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003973 return device;
3974}
3975
Eric Laurente0720872014-03-11 09:30:41 -07003976uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003977 return (uint32_t)getStrategy(stream);
3978}
3979
Eric Laurente0720872014-03-11 09:30:41 -07003980audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003981 // By checking the range of stream before calling getStrategy, we avoid
3982 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3983 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08003984 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003985 return AUDIO_DEVICE_NONE;
3986 }
3987 audio_devices_t devices;
3988 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3989 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3990 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3991 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003992 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003993 if (outputDesc->isStrategyActive(strategy)) {
3994 devices = outputDesc->device();
3995 break;
3996 }
Eric Laurente552edb2014-03-10 17:42:56 -07003997 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003998
3999 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4000 and doesn't really need to.*/
4001 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4002 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4003 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4004 }
4005
Eric Laurente552edb2014-03-10 17:42:56 -07004006 return devices;
4007}
4008
Eric Laurente0720872014-03-11 09:30:41 -07004009AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004010 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004011
4012 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4013
Eric Laurente552edb2014-03-10 17:42:56 -07004014 // stream to strategy mapping
4015 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004016 case AUDIO_STREAM_VOICE_CALL:
4017 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004018 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004019 case AUDIO_STREAM_RING:
4020 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004021 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004022 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004023 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004024 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004025 return STRATEGY_DTMF;
4026 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004027 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004028 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004029 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4030 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004031 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004032 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004033 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004034 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004035 case AUDIO_STREAM_TTS:
4036 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004037 case AUDIO_STREAM_ACCESSIBILITY:
4038 return STRATEGY_ACCESSIBILITY;
4039 case AUDIO_STREAM_REROUTING:
4040 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004041 }
4042}
4043
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004044uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4045 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004046 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4047 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4048 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004049 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4050 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4051 }
4052
4053 // usage to strategy mapping
4054 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004055 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4056 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4057 return (uint32_t) STRATEGY_SONIFICATION;
4058 }
4059 if (isInCall()) {
4060 return (uint32_t) STRATEGY_PHONE;
4061 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004062 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004063
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004064 case AUDIO_USAGE_MEDIA:
4065 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004066 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4067 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4068 return (uint32_t) STRATEGY_MEDIA;
4069
4070 case AUDIO_USAGE_VOICE_COMMUNICATION:
4071 return (uint32_t) STRATEGY_PHONE;
4072
4073 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4074 return (uint32_t) STRATEGY_DTMF;
4075
4076 case AUDIO_USAGE_ALARM:
4077 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4078 return (uint32_t) STRATEGY_SONIFICATION;
4079
4080 case AUDIO_USAGE_NOTIFICATION:
4081 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4082 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4083 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4084 case AUDIO_USAGE_NOTIFICATION_EVENT:
4085 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4086
4087 case AUDIO_USAGE_UNKNOWN:
4088 default:
4089 return (uint32_t) STRATEGY_MEDIA;
4090 }
4091}
4092
Eric Laurente0720872014-03-11 09:30:41 -07004093void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004094 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004095 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004096 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4097 updateDevicesAndOutputs();
4098 break;
4099 default:
4100 break;
4101 }
4102}
4103
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004104bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4105 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4106 if (s == (size_t) streamToIgnore) {
4107 continue;
4108 }
4109 for (size_t i = 0; i < mOutputs.size(); i++) {
4110 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4111 if (outputDesc->mRefCount[s] != 0) {
4112 return true;
4113 }
4114 }
4115 }
4116 return false;
4117}
4118
4119uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4120 switch(event) {
4121 case STARTING_OUTPUT:
4122 mBeaconMuteRefCount++;
4123 break;
4124 case STOPPING_OUTPUT:
4125 if (mBeaconMuteRefCount > 0) {
4126 mBeaconMuteRefCount--;
4127 }
4128 break;
4129 case STARTING_BEACON:
4130 mBeaconPlayingRefCount++;
4131 break;
4132 case STOPPING_BEACON:
4133 if (mBeaconPlayingRefCount > 0) {
4134 mBeaconPlayingRefCount--;
4135 }
4136 break;
4137 }
4138
4139 if (mBeaconMuteRefCount > 0) {
4140 // any playback causes beacon to be muted
4141 return setBeaconMute(true);
4142 } else {
4143 // no other playback: unmute when beacon starts playing, mute when it stops
4144 return setBeaconMute(mBeaconPlayingRefCount == 0);
4145 }
4146}
4147
4148uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4149 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4150 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4151 // keep track of muted state to avoid repeating mute/unmute operations
4152 if (mBeaconMuted != mute) {
4153 // mute/unmute AUDIO_STREAM_TTS on all outputs
4154 ALOGV("\t muting %d", mute);
4155 uint32_t maxLatency = 0;
4156 for (size_t i = 0; i < mOutputs.size(); i++) {
4157 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4158 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4159 desc->mIoHandle,
4160 0 /*delay*/, AUDIO_DEVICE_NONE);
4161 const uint32_t latency = desc->latency() * 2;
4162 if (latency > maxLatency) {
4163 maxLatency = latency;
4164 }
4165 }
4166 mBeaconMuted = mute;
4167 return maxLatency;
4168 }
4169 return 0;
4170}
4171
Eric Laurente0720872014-03-11 09:30:41 -07004172audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004173 bool fromCache)
4174{
4175 uint32_t device = AUDIO_DEVICE_NONE;
4176
4177 if (fromCache) {
4178 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4179 strategy, mDeviceForStrategy[strategy]);
4180 return mDeviceForStrategy[strategy];
4181 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004182 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004183 switch (strategy) {
4184
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004185 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4186 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4187 if (!device) {
4188 ALOGE("getDeviceForStrategy() no device found for "\
4189 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4190 }
4191 break;
4192
Eric Laurente552edb2014-03-10 17:42:56 -07004193 case STRATEGY_SONIFICATION_RESPECTFUL:
4194 if (isInCall()) {
4195 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004196 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004197 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4198 // while media is playing on a remote device, use the the sonification behavior.
4199 // Note that we test this usecase before testing if media is playing because
4200 // the isStreamActive() method only informs about the activity of a stream, not
4201 // if it's for local playback. Note also that we use the same delay between both tests
4202 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004203 //user "safe" speaker if available instead of normal speaker to avoid triggering
4204 //other acoustic safety mechanisms for notification
4205 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4206 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004207 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004208 // while media is playing (or has recently played), use the same device
4209 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4210 } else {
4211 // when media is not playing anymore, fall back on the sonification behavior
4212 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004213 //user "safe" speaker if available instead of normal speaker to avoid triggering
4214 //other acoustic safety mechanisms for notification
4215 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4216 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004217 }
4218
4219 break;
4220
4221 case STRATEGY_DTMF:
4222 if (!isInCall()) {
4223 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4224 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4225 break;
4226 }
4227 // when in call, DTMF and PHONE strategies follow the same rules
4228 // FALL THROUGH
4229
4230 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004231 // Force use of only devices on primary output if:
4232 // - in call AND
4233 // - cannot route from voice call RX OR
4234 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4235 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4236 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4237 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4238 if (((mAvailableInputDevices.types() &
4239 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4240 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004241 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004242 AUDIO_DEVICE_API_VERSION_3_0))) {
4243 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4244 }
4245 }
Eric Laurente552edb2014-03-10 17:42:56 -07004246 // for phone strategy, we first consider the forced use and then the available devices by order
4247 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004248 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4249 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004250 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004251 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004252 if (device) break;
4253 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004254 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004255 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004256 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004257 if (device) break;
4258 // if SCO device is requested but no SCO device is available, fall back to default case
4259 // FALL THROUGH
4260
4261 default: // FORCE_NONE
4262 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004263 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004264 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004265 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004266 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004267 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004268 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004269 if (device) break;
4270 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004271 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004272 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004273 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004274 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004275 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4276 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004277 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004278 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004279 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004280 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004281 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004282 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004283 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004284 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004285 if (device) break;
4286 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004287 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004288 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004289 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004290 if (device == AUDIO_DEVICE_NONE) {
4291 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4292 }
4293 break;
4294
Eric Laurent3b73df72014-03-11 09:06:29 -07004295 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004296 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4297 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004298 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004299 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004300 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004301 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004302 if (device) break;
4303 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004304 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004305 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004306 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004307 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004308 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004309 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004310 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004311 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004312 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004313 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004314 if (device) break;
4315 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004316 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4317 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004318 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004319 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004320 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004321 if (device == AUDIO_DEVICE_NONE) {
4322 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4323 }
4324 break;
4325 }
4326 break;
4327
4328 case STRATEGY_SONIFICATION:
4329
4330 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4331 // handleIncallSonification().
4332 if (isInCall()) {
4333 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4334 break;
4335 }
4336 // FALL THROUGH
4337
4338 case STRATEGY_ENFORCED_AUDIBLE:
4339 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4340 // except:
4341 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4342 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4343
4344 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004345 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004346 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004347 if (device == AUDIO_DEVICE_NONE) {
4348 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4349 }
4350 }
4351 // The second device used for sonification is the same as the device used by media strategy
4352 // FALL THROUGH
4353
Eric Laurent223fd5c2014-11-11 13:43:36 -08004354 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4355 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004356 if (strategy == STRATEGY_ACCESSIBILITY) {
4357 // do not route accessibility prompts to a digital output currently configured with a
4358 // compressed format as they would likely not be mixed and dropped.
4359 for (size_t i = 0; i < mOutputs.size(); i++) {
4360 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4361 audio_devices_t devices = desc->device() &
4362 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4363 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4364 devices != AUDIO_DEVICE_NONE) {
4365 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4366 }
4367 }
4368 }
4369 // FALL THROUGH
4370
Eric Laurent223fd5c2014-11-11 13:43:36 -08004371 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004372 case STRATEGY_MEDIA: {
4373 uint32_t device2 = AUDIO_DEVICE_NONE;
4374 if (strategy != STRATEGY_SONIFICATION) {
4375 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004376 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004377 }
4378 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004379 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004380 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004381 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004382 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004383 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004384 }
4385 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004386 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004387 }
4388 }
Hochi Huang327cb702014-09-21 09:47:31 +08004389 if ((device2 == AUDIO_DEVICE_NONE) &&
4390 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4391 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4392 }
Eric Laurente552edb2014-03-10 17:42:56 -07004393 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004394 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004395 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004396 if ((device2 == AUDIO_DEVICE_NONE)) {
4397 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4398 }
Eric Laurente552edb2014-03-10 17:42:56 -07004399 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004400 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004401 }
4402 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004403 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004404 }
4405 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004406 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004407 }
4408 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004409 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004410 }
4411 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4412 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004413 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004414 }
4415 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004416 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004417 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004418 }
4419 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004420 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004421 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004422 int device3 = AUDIO_DEVICE_NONE;
4423 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004424 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004425 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4426 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004427 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004428 }
Eric Laurente552edb2014-03-10 17:42:56 -07004429
Jungshik Jang839e4f32014-06-26 17:23:40 +09004430 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004431 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4432 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4433 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004434
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004435 // If hdmi system audio mode is on, remove speaker out of output list.
4436 if ((strategy == STRATEGY_MEDIA) &&
4437 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4438 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4439 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4440 }
4441
Eric Laurente552edb2014-03-10 17:42:56 -07004442 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004443 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004444 if (device == AUDIO_DEVICE_NONE) {
4445 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4446 }
4447 } break;
4448
4449 default:
4450 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4451 break;
4452 }
4453
4454 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4455 return device;
4456}
4457
Eric Laurente0720872014-03-11 09:30:41 -07004458void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004459{
4460 for (int i = 0; i < NUM_STRATEGIES; i++) {
4461 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4462 }
4463 mPreviousOutputs = mOutputs;
4464}
4465
Eric Laurent1f2f2232014-06-02 12:01:23 -07004466uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004467 audio_devices_t prevDevice,
4468 uint32_t delayMs)
4469{
4470 // mute/unmute strategies using an incompatible device combination
4471 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4472 // if unmuting, unmute only after the specified delay
4473 if (outputDesc->isDuplicated()) {
4474 return 0;
4475 }
4476
4477 uint32_t muteWaitMs = 0;
4478 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004479 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004480
4481 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4482 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004483 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004484 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4485 bool doMute = false;
4486
4487 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4488 doMute = true;
4489 outputDesc->mStrategyMutedByDevice[i] = true;
4490 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4491 doMute = true;
4492 outputDesc->mStrategyMutedByDevice[i] = false;
4493 }
Eric Laurent99401132014-05-07 19:48:15 -07004494 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004495 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004496 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004497 // skip output if it does not share any device with current output
4498 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4499 == AUDIO_DEVICE_NONE) {
4500 continue;
4501 }
4502 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4503 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4504 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4505 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4506 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004507 if (mute) {
4508 // FIXME: should not need to double latency if volume could be applied
4509 // immediately by the audioflinger mixer. We must account for the delay
4510 // between now and the next time the audioflinger thread for this output
4511 // will process a buffer (which corresponds to one buffer size,
4512 // usually 1/2 or 1/4 of the latency).
4513 if (muteWaitMs < desc->latency() * 2) {
4514 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004515 }
4516 }
4517 }
4518 }
4519 }
4520 }
4521
Eric Laurent99401132014-05-07 19:48:15 -07004522 // temporary mute output if device selection changes to avoid volume bursts due to
4523 // different per device volumes
4524 if (outputDesc->isActive() && (device != prevDevice)) {
4525 if (muteWaitMs < outputDesc->latency() * 2) {
4526 muteWaitMs = outputDesc->latency() * 2;
4527 }
4528 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4529 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004530 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004531 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004532 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004533 muteWaitMs *2, device);
4534 }
4535 }
4536 }
4537
Eric Laurente552edb2014-03-10 17:42:56 -07004538 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4539 if (muteWaitMs > delayMs) {
4540 muteWaitMs -= delayMs;
4541 usleep(muteWaitMs * 1000);
4542 return muteWaitMs;
4543 }
4544 return 0;
4545}
4546
Eric Laurente0720872014-03-11 09:30:41 -07004547uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004548 audio_devices_t device,
4549 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004550 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004551 audio_patch_handle_t *patchHandle,
4552 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004553{
4554 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004555 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004556 AudioParameter param;
4557 uint32_t muteWaitMs;
4558
4559 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004560 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4561 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004562 return muteWaitMs;
4563 }
4564 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4565 // output profile
4566 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004567 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004568 return 0;
4569 }
4570
4571 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004572 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004573
4574 audio_devices_t prevDevice = outputDesc->mDevice;
4575
4576 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4577
4578 if (device != AUDIO_DEVICE_NONE) {
4579 outputDesc->mDevice = device;
4580 }
4581 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4582
4583 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004584 // the requested device is AUDIO_DEVICE_NONE
4585 // OR the requested device is the same as current device
4586 // AND force is not specified
4587 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004588 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004589 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4590 outputDesc->mPatchHandle != 0) {
4591 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4592 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004593 return muteWaitMs;
4594 }
4595
4596 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004597
Eric Laurente552edb2014-03-10 17:42:56 -07004598 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004599 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004600 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004601 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004602 DeviceVector deviceList = (address == NULL) ?
4603 mAvailableOutputDevices.getDevicesFromType(device)
4604 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004605 if (!deviceList.isEmpty()) {
4606 struct audio_patch patch;
4607 outputDesc->toAudioPortConfig(&patch.sources[0]);
4608 patch.num_sources = 1;
4609 patch.num_sinks = 0;
4610 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4611 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004612 patch.num_sinks++;
4613 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004614 ssize_t index;
4615 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4616 index = mAudioPatches.indexOfKey(*patchHandle);
4617 } else {
4618 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4619 }
4620 sp< AudioPatch> patchDesc;
4621 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4622 if (index >= 0) {
4623 patchDesc = mAudioPatches.valueAt(index);
4624 afPatchHandle = patchDesc->mAfPatchHandle;
4625 }
4626
Eric Laurent1c333e22014-05-20 10:48:17 -07004627 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004628 &afPatchHandle,
4629 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004630 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4631 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004632 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004633 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004634 if (index < 0) {
4635 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4636 &patch, mUidCached);
4637 addAudioPatch(patchDesc->mHandle, patchDesc);
4638 } else {
4639 patchDesc->mPatch = patch;
4640 }
4641 patchDesc->mAfPatchHandle = afPatchHandle;
4642 patchDesc->mUid = mUidCached;
4643 if (patchHandle) {
4644 *patchHandle = patchDesc->mHandle;
4645 }
4646 outputDesc->mPatchHandle = patchDesc->mHandle;
4647 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004648 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004649 }
4650 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004651
4652 // inform all input as well
4653 for (size_t i = 0; i < mInputs.size(); i++) {
4654 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4655 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4656 AudioParameter inputCmd = AudioParameter();
4657 ALOGV("%s: inform input %d of device:%d", __func__,
4658 inputDescriptor->mIoHandle, device);
4659 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4660 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4661 inputCmd.toString(),
4662 delayMs);
4663 }
4664 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004665 }
Eric Laurente552edb2014-03-10 17:42:56 -07004666
4667 // update stream volumes according to new device
4668 applyStreamVolumes(output, device, delayMs);
4669
4670 return muteWaitMs;
4671}
4672
Eric Laurent1c333e22014-05-20 10:48:17 -07004673status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004674 int delayMs,
4675 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004676{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004677 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004678 ssize_t index;
4679 if (patchHandle) {
4680 index = mAudioPatches.indexOfKey(*patchHandle);
4681 } else {
4682 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4683 }
4684 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004685 return INVALID_OPERATION;
4686 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004687 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4688 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004689 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4690 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004691 removeAudioPatch(patchDesc->mHandle);
4692 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004693 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004694 return status;
4695}
4696
4697status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4698 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004699 bool force,
4700 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004701{
4702 status_t status = NO_ERROR;
4703
Eric Laurent1f2f2232014-06-02 12:01:23 -07004704 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004705 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4706 inputDesc->mDevice = device;
4707
4708 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4709 if (!deviceList.isEmpty()) {
4710 struct audio_patch patch;
4711 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004712 // AUDIO_SOURCE_HOTWORD is for internal use only:
4713 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004714 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4715 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004716 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4717 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004718 patch.num_sinks = 1;
4719 //only one input device for now
4720 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004721 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004722 ssize_t index;
4723 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4724 index = mAudioPatches.indexOfKey(*patchHandle);
4725 } else {
4726 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4727 }
4728 sp< AudioPatch> patchDesc;
4729 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4730 if (index >= 0) {
4731 patchDesc = mAudioPatches.valueAt(index);
4732 afPatchHandle = patchDesc->mAfPatchHandle;
4733 }
4734
Eric Laurent1c333e22014-05-20 10:48:17 -07004735 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004736 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004737 0);
4738 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004740 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004741 if (index < 0) {
4742 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4743 &patch, mUidCached);
4744 addAudioPatch(patchDesc->mHandle, patchDesc);
4745 } else {
4746 patchDesc->mPatch = patch;
4747 }
4748 patchDesc->mAfPatchHandle = afPatchHandle;
4749 patchDesc->mUid = mUidCached;
4750 if (patchHandle) {
4751 *patchHandle = patchDesc->mHandle;
4752 }
4753 inputDesc->mPatchHandle = patchDesc->mHandle;
4754 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004755 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004756 }
4757 }
4758 }
4759 return status;
4760}
4761
Eric Laurent6a94d692014-05-20 11:18:06 -07004762status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4763 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004764{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004765 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004766 ssize_t index;
4767 if (patchHandle) {
4768 index = mAudioPatches.indexOfKey(*patchHandle);
4769 } else {
4770 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4771 }
4772 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004773 return INVALID_OPERATION;
4774 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004775 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4776 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004777 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4778 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004779 removeAudioPatch(patchDesc->mHandle);
4780 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004781 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004782 return status;
4783}
4784
4785sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004786 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004787 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004788 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004789 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004790{
4791 // Choose an input profile based on the requested capture parameters: select the first available
4792 // profile supporting all requested parameters.
4793
4794 for (size_t i = 0; i < mHwModules.size(); i++)
4795 {
4796 if (mHwModules[i]->mHandle == 0) {
4797 continue;
4798 }
4799 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4800 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004801 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004802 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004803 if (profile->isCompatibleProfile(device, samplingRate,
4804 &samplingRate /*updatedSamplingRate*/,
4805 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004806 return profile;
4807 }
4808 }
4809 }
4810 return NULL;
4811}
4812
Eric Laurente0720872014-03-11 09:30:41 -07004813audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004814{
4815 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004816 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4817 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004818 switch (inputSource) {
4819 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004820 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004821 device = AUDIO_DEVICE_IN_VOICE_CALL;
4822 break;
4823 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004824 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004825
4826 case AUDIO_SOURCE_DEFAULT:
4827 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004828 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4829 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004830 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4831 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4832 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4833 device = AUDIO_DEVICE_IN_USB_DEVICE;
4834 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4835 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004836 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004837 break;
4838
4839 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4840 // Allow only use of devices on primary input if in call and HAL does not support routing
4841 // to voice call path.
4842 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4843 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4844 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4845 }
4846
4847 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4848 case AUDIO_POLICY_FORCE_BT_SCO:
4849 // if SCO device is requested but no SCO device is available, fall back to default case
4850 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4851 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4852 break;
4853 }
4854 // FALL THROUGH
4855
4856 default: // FORCE_NONE
4857 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4858 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4859 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4860 device = AUDIO_DEVICE_IN_USB_DEVICE;
4861 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4862 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4863 }
4864 break;
4865
4866 case AUDIO_POLICY_FORCE_SPEAKER:
4867 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4868 device = AUDIO_DEVICE_IN_BACK_MIC;
4869 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4870 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4871 }
4872 break;
4873 }
4874 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004875
Eric Laurente552edb2014-03-10 17:42:56 -07004876 case AUDIO_SOURCE_VOICE_RECOGNITION:
4877 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004878 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004879 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004880 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004881 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004882 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004883 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4884 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004885 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004886 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4887 }
4888 break;
4889 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004890 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004891 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004892 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004893 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4894 }
4895 break;
4896 case AUDIO_SOURCE_VOICE_DOWNLINK:
4897 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004898 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004899 device = AUDIO_DEVICE_IN_VOICE_CALL;
4900 }
4901 break;
4902 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004903 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004904 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4905 }
4906 break;
Hochi Huang327cb702014-09-21 09:47:31 +08004907 case AUDIO_SOURCE_FM_TUNER:
4908 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
4909 device = AUDIO_DEVICE_IN_FM_TUNER;
4910 }
4911 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004912 default:
4913 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4914 break;
4915 }
4916 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4917 return device;
4918}
4919
Eric Laurente0720872014-03-11 09:30:41 -07004920bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004921{
4922 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4923 device &= ~AUDIO_DEVICE_BIT_IN;
4924 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4925 return true;
4926 }
4927 return false;
4928}
4929
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004930bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4931 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4932}
4933
Eric Laurente0720872014-03-11 09:30:41 -07004934audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004935{
4936 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004937 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004938 if ((input_descriptor->mRefCount > 0)
4939 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4940 return mInputs.keyAt(i);
4941 }
4942 }
4943 return 0;
4944}
4945
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004946uint32_t AudioPolicyManager::activeInputsCount() const
4947{
4948 uint32_t count = 0;
4949 for (size_t i = 0; i < mInputs.size(); i++) {
4950 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4951 if (desc->mRefCount > 0) {
4952 return count++;
4953 }
4954 }
4955 return count;
4956}
4957
Eric Laurente552edb2014-03-10 17:42:56 -07004958
Eric Laurente0720872014-03-11 09:30:41 -07004959audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004960{
4961 if (device == AUDIO_DEVICE_NONE) {
4962 // this happens when forcing a route update and no track is active on an output.
4963 // In this case the returned category is not important.
4964 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004965 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004966 // Multiple device selection is either:
4967 // - speaker + one other device: give priority to speaker in this case.
4968 // - one A2DP device + another device: happens with duplicated output. In this case
4969 // retain the device on the A2DP output as the other must not correspond to an active
4970 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004971 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004972 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4973 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004974 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4975 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4976 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4977 device = AUDIO_DEVICE_OUT_AUX_LINE;
4978 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4979 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004980 } else {
4981 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4982 }
4983 }
4984
Jon Eklund11c9fb12014-06-23 14:47:03 -05004985 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4986 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4987 device = AUDIO_DEVICE_OUT_SPEAKER;
4988
Eric Laurent3b73df72014-03-11 09:06:29 -07004989 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004990 "getDeviceForVolume() invalid device combination: %08x",
4991 device);
4992
4993 return device;
4994}
4995
Eric Laurente0720872014-03-11 09:30:41 -07004996AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004997{
4998 switch(getDeviceForVolume(device)) {
4999 case AUDIO_DEVICE_OUT_EARPIECE:
5000 return DEVICE_CATEGORY_EARPIECE;
5001 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5002 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5003 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5004 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5005 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5006 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5007 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005008 case AUDIO_DEVICE_OUT_LINE:
5009 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5010 /*USB? Remote submix?*/
5011 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005012 case AUDIO_DEVICE_OUT_SPEAKER:
5013 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5014 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005015 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5016 case AUDIO_DEVICE_OUT_USB_DEVICE:
5017 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5018 default:
5019 return DEVICE_CATEGORY_SPEAKER;
5020 }
5021}
5022
Eric Laurent223fd5c2014-11-11 13:43:36 -08005023/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005024float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005025 int indexInUi)
5026{
5027 device_category deviceCategory = getDeviceCategory(device);
5028 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5029
5030 // the volume index in the UI is relative to the min and max volume indices for this stream type
5031 int nbSteps = 1 + curve[VOLMAX].mIndex -
5032 curve[VOLMIN].mIndex;
5033 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5034 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5035
5036 // find what part of the curve this index volume belongs to, or if it's out of bounds
5037 int segment = 0;
5038 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5039 return 0.0f;
5040 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5041 segment = 0;
5042 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5043 segment = 1;
5044 } else if (volIdx <= curve[VOLMAX].mIndex) {
5045 segment = 2;
5046 } else { // out of bounds
5047 return 1.0f;
5048 }
5049
5050 // linear interpolation in the attenuation table in dB
5051 float decibels = curve[segment].mDBAttenuation +
5052 ((float)(volIdx - curve[segment].mIndex)) *
5053 ( (curve[segment+1].mDBAttenuation -
5054 curve[segment].mDBAttenuation) /
5055 ((float)(curve[segment+1].mIndex -
5056 curve[segment].mIndex)) );
5057
5058 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5059
5060 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5061 curve[segment].mIndex, volIdx,
5062 curve[segment+1].mIndex,
5063 curve[segment].mDBAttenuation,
5064 decibels,
5065 curve[segment+1].mDBAttenuation,
5066 amplification);
5067
5068 return amplification;
5069}
5070
Eric Laurente0720872014-03-11 09:30:41 -07005071const AudioPolicyManager::VolumeCurvePoint
5072 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005073 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5074};
5075
Eric Laurente0720872014-03-11 09:30:41 -07005076const AudioPolicyManager::VolumeCurvePoint
5077 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005078 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5079};
5080
Eric Laurente0720872014-03-11 09:30:41 -07005081const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005082 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5083 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5084};
5085
5086const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005087 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005088 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5089};
5090
Eric Laurente0720872014-03-11 09:30:41 -07005091const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005092 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005093 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005094};
5095
5096const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005097 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005098 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5099};
5100
Eric Laurente0720872014-03-11 09:30:41 -07005101const AudioPolicyManager::VolumeCurvePoint
5102 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005103 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5104};
5105
5106// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5107// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5108// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5109// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5110
Eric Laurente0720872014-03-11 09:30:41 -07005111const AudioPolicyManager::VolumeCurvePoint
5112 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005113 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5114};
5115
Eric Laurente0720872014-03-11 09:30:41 -07005116const AudioPolicyManager::VolumeCurvePoint
5117 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005118 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5119};
5120
Eric Laurente0720872014-03-11 09:30:41 -07005121const AudioPolicyManager::VolumeCurvePoint
5122 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005123 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5124};
5125
Eric Laurente0720872014-03-11 09:30:41 -07005126const AudioPolicyManager::VolumeCurvePoint
5127 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005128 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5129};
5130
Eric Laurente0720872014-03-11 09:30:41 -07005131const AudioPolicyManager::VolumeCurvePoint
5132 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005133 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5134};
5135
Eric Laurente0720872014-03-11 09:30:41 -07005136const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005137 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5138 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5139};
5140
5141const AudioPolicyManager::VolumeCurvePoint
5142 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5143 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5144};
5145
5146const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005147 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5148 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5149};
5150
5151const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005152 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5153 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005154 { // AUDIO_STREAM_VOICE_CALL
5155 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5156 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005157 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5158 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005159 },
5160 { // AUDIO_STREAM_SYSTEM
5161 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5162 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005163 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5164 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005165 },
5166 { // AUDIO_STREAM_RING
5167 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5168 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005169 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5170 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005171 },
5172 { // AUDIO_STREAM_MUSIC
5173 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5174 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005175 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5176 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005177 },
5178 { // AUDIO_STREAM_ALARM
5179 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5180 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005181 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5182 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005183 },
5184 { // AUDIO_STREAM_NOTIFICATION
5185 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5186 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005187 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5188 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005189 },
5190 { // AUDIO_STREAM_BLUETOOTH_SCO
5191 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5192 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005193 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5194 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005195 },
5196 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5197 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5198 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005199 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5200 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005201 },
5202 { // AUDIO_STREAM_DTMF
5203 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5204 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005205 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5206 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005207 },
5208 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005209 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5210 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5211 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5212 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5213 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005214 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005215 { // AUDIO_STREAM_ACCESSIBILITY
5216 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5217 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5218 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5219 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5220 },
5221 { // AUDIO_STREAM_REROUTING
5222 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5223 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5224 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5225 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5226 },
5227 { // AUDIO_STREAM_PATCH
5228 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5229 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5230 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5231 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5232 },
Eric Laurente552edb2014-03-10 17:42:56 -07005233};
5234
Eric Laurente0720872014-03-11 09:30:41 -07005235void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005236{
5237 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5238 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5239 mStreams[i].mVolumeCurve[j] =
5240 sVolumeProfiles[i][j];
5241 }
5242 }
5243
5244 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5245 if (mSpeakerDrcEnabled) {
5246 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5247 sDefaultSystemVolumeCurveDrc;
5248 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5249 sSpeakerSonificationVolumeCurveDrc;
5250 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5251 sSpeakerSonificationVolumeCurveDrc;
5252 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5253 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005254 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5255 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005256 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5257 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005258 }
5259}
5260
Eric Laurente0720872014-03-11 09:30:41 -07005261float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005262 int index,
5263 audio_io_handle_t output,
5264 audio_devices_t device)
5265{
5266 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005267 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005268 StreamDescriptor &streamDesc = mStreams[stream];
5269
5270 if (device == AUDIO_DEVICE_NONE) {
5271 device = outputDesc->device();
5272 }
5273
Eric Laurente552edb2014-03-10 17:42:56 -07005274 volume = volIndexToAmpl(device, streamDesc, index);
5275
5276 // if a headset is connected, apply the following rules to ring tones and notifications
5277 // to avoid sound level bursts in user's ears:
5278 // - always attenuate ring tones and notifications volume by 6dB
5279 // - if music is playing, always limit the volume to current music volume,
5280 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005281 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005282 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5283 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5284 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5285 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5286 ((stream_strategy == STRATEGY_SONIFICATION)
5287 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005288 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005289 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005290 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005291 streamDesc.mCanBeMuted) {
5292 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5293 // when the phone is ringing we must consider that music could have been paused just before
5294 // by the music application and behave as if music was active if the last music track was
5295 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005296 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005297 mLimitRingtoneVolume) {
5298 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005299 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5300 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005301 output,
5302 musicDevice);
5303 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5304 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5305 if (volume > minVol) {
5306 volume = minVol;
5307 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5308 }
5309 }
5310 }
5311
5312 return volume;
5313}
5314
Eric Laurente0720872014-03-11 09:30:41 -07005315status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005316 int index,
5317 audio_io_handle_t output,
5318 audio_devices_t device,
5319 int delayMs,
5320 bool force)
5321{
5322
5323 // do not change actual stream volume if the stream is muted
5324 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5325 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5326 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5327 return NO_ERROR;
5328 }
5329
5330 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005331 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5332 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5333 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5334 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005335 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005336 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005337 return INVALID_OPERATION;
5338 }
5339
5340 float volume = computeVolume(stream, index, output, device);
5341 // We actually change the volume if:
5342 // - the float value returned by computeVolume() changed
5343 // - the force flag is set
5344 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5345 force) {
5346 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5347 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5348 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5349 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005350 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5351 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005352 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005353 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005354 }
5355
Eric Laurent3b73df72014-03-11 09:06:29 -07005356 if (stream == AUDIO_STREAM_VOICE_CALL ||
5357 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005358 float voiceVolume;
5359 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005360 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005361 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5362 } else {
5363 voiceVolume = 1.0;
5364 }
5365
5366 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5367 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5368 mLastVoiceVolume = voiceVolume;
5369 }
5370 }
5371
5372 return NO_ERROR;
5373}
5374
Eric Laurente0720872014-03-11 09:30:41 -07005375void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005376 audio_devices_t device,
5377 int delayMs,
5378 bool force)
5379{
5380 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5381
Eric Laurent3b73df72014-03-11 09:06:29 -07005382 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005383 if (stream == AUDIO_STREAM_PATCH) {
5384 continue;
5385 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005386 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005387 mStreams[stream].getVolumeIndex(device),
5388 output,
5389 device,
5390 delayMs,
5391 force);
5392 }
5393}
5394
Eric Laurente0720872014-03-11 09:30:41 -07005395void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005396 bool on,
5397 audio_io_handle_t output,
5398 int delayMs,
5399 audio_devices_t device)
5400{
5401 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005402 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005403 if (stream == AUDIO_STREAM_PATCH) {
5404 continue;
5405 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005406 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5407 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005408 }
5409 }
5410}
5411
Eric Laurente0720872014-03-11 09:30:41 -07005412void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005413 bool on,
5414 audio_io_handle_t output,
5415 int delayMs,
5416 audio_devices_t device)
5417{
5418 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005419 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005420 if (device == AUDIO_DEVICE_NONE) {
5421 device = outputDesc->device();
5422 }
5423
5424 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5425 stream, on, output, outputDesc->mMuteCount[stream], device);
5426
5427 if (on) {
5428 if (outputDesc->mMuteCount[stream] == 0) {
5429 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005430 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5431 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005432 checkAndSetVolume(stream, 0, output, device, delayMs);
5433 }
5434 }
5435 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5436 outputDesc->mMuteCount[stream]++;
5437 } else {
5438 if (outputDesc->mMuteCount[stream] == 0) {
5439 ALOGV("setStreamMute() unmuting non muted stream!");
5440 return;
5441 }
5442 if (--outputDesc->mMuteCount[stream] == 0) {
5443 checkAndSetVolume(stream,
5444 streamDesc.getVolumeIndex(device),
5445 output,
5446 device,
5447 delayMs);
5448 }
5449 }
5450}
5451
Eric Laurente0720872014-03-11 09:30:41 -07005452void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005453 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005454{
5455 // if the stream pertains to sonification strategy and we are in call we must
5456 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5457 // in the device used for phone strategy and play the tone if the selected device does not
5458 // interfere with the device used for phone strategy
5459 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5460 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005461 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005462 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5463 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005464 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005465 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5466 stream, starting, outputDesc->mDevice, stateChange);
5467 if (outputDesc->mRefCount[stream]) {
5468 int muteCount = 1;
5469 if (stateChange) {
5470 muteCount = outputDesc->mRefCount[stream];
5471 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005472 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005473 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5474 for (int i = 0; i < muteCount; i++) {
5475 setStreamMute(stream, starting, mPrimaryOutput);
5476 }
5477 } else {
5478 ALOGV("handleIncallSonification() high visibility");
5479 if (outputDesc->device() &
5480 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5481 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5482 for (int i = 0; i < muteCount; i++) {
5483 setStreamMute(stream, starting, mPrimaryOutput);
5484 }
5485 }
5486 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005487 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5488 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005489 } else {
5490 mpClientInterface->stopTone();
5491 }
5492 }
5493 }
5494 }
5495}
5496
Eric Laurente0720872014-03-11 09:30:41 -07005497bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005498{
5499 return isStateInCall(mPhoneState);
5500}
5501
Eric Laurente0720872014-03-11 09:30:41 -07005502bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005503 return ((state == AUDIO_MODE_IN_CALL) ||
5504 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005505}
5506
Eric Laurente0720872014-03-11 09:30:41 -07005507uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005508{
5509 return MAX_EFFECTS_CPU_LOAD;
5510}
5511
Eric Laurente0720872014-03-11 09:30:41 -07005512uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005513{
5514 return MAX_EFFECTS_MEMORY;
5515}
5516
Eric Laurent6a94d692014-05-20 11:18:06 -07005517
Eric Laurente552edb2014-03-10 17:42:56 -07005518// --- AudioOutputDescriptor class implementation
5519
Eric Laurente0720872014-03-11 09:30:41 -07005520AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005521 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005522 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005523 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005524 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5525{
5526 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005527 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005528 mRefCount[i] = 0;
5529 mCurVolume[i] = -1.0;
5530 mMuteCount[i] = 0;
5531 mStopTime[i] = 0;
5532 }
5533 for (int i = 0; i < NUM_STRATEGIES; i++) {
5534 mStrategyMutedByDevice[i] = false;
5535 }
5536 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005537 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005538 mSamplingRate = profile->pickSamplingRate();
5539 mFormat = profile->pickFormat();
5540 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005541 if (profile->mGains.size() > 0) {
5542 profile->mGains[0]->getDefaultConfig(&mGain);
5543 }
Eric Laurente552edb2014-03-10 17:42:56 -07005544 }
5545}
5546
Eric Laurente0720872014-03-11 09:30:41 -07005547audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005548{
5549 if (isDuplicated()) {
5550 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5551 } else {
5552 return mDevice;
5553 }
5554}
5555
Eric Laurente0720872014-03-11 09:30:41 -07005556uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005557{
5558 if (isDuplicated()) {
5559 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5560 } else {
5561 return mLatency;
5562 }
5563}
5564
Eric Laurente0720872014-03-11 09:30:41 -07005565bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005566 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005567{
5568 if (isDuplicated()) {
5569 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5570 } else if (outputDesc->isDuplicated()){
5571 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5572 } else {
5573 return (mProfile->mModule == outputDesc->mProfile->mModule);
5574 }
5575}
5576
Eric Laurente0720872014-03-11 09:30:41 -07005577void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005578 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005579{
5580 // forward usage count change to attached outputs
5581 if (isDuplicated()) {
5582 mOutput1->changeRefCount(stream, delta);
5583 mOutput2->changeRefCount(stream, delta);
5584 }
5585 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005586 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5587 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005588 mRefCount[stream] = 0;
5589 return;
5590 }
5591 mRefCount[stream] += delta;
5592 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5593}
5594
Eric Laurente0720872014-03-11 09:30:41 -07005595audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005596{
5597 if (isDuplicated()) {
5598 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5599 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005600 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005601 }
5602}
5603
Eric Laurente0720872014-03-11 09:30:41 -07005604bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005605{
5606 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5607}
5608
Eric Laurente0720872014-03-11 09:30:41 -07005609bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005610 uint32_t inPastMs,
5611 nsecs_t sysTime) const
5612{
5613 if ((sysTime == 0) && (inPastMs != 0)) {
5614 sysTime = systemTime();
5615 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005616 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005617 if (i == AUDIO_STREAM_PATCH) {
5618 continue;
5619 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005620 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005621 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005622 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005623 return true;
5624 }
5625 }
5626 return false;
5627}
5628
Eric Laurente0720872014-03-11 09:30:41 -07005629bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005630 uint32_t inPastMs,
5631 nsecs_t sysTime) const
5632{
5633 if (mRefCount[stream] != 0) {
5634 return true;
5635 }
5636 if (inPastMs == 0) {
5637 return false;
5638 }
5639 if (sysTime == 0) {
5640 sysTime = systemTime();
5641 }
5642 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5643 return true;
5644 }
5645 return false;
5646}
5647
Eric Laurent1c333e22014-05-20 10:48:17 -07005648void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005649 struct audio_port_config *dstConfig,
5650 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005651{
Eric Laurent84c70242014-06-23 08:46:27 -07005652 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5653
Eric Laurent1f2f2232014-06-02 12:01:23 -07005654 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5655 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5656 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005657 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005658 }
5659 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5660
Eric Laurent6a94d692014-05-20 11:18:06 -07005661 dstConfig->id = mId;
5662 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5663 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005664 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5665 dstConfig->ext.mix.handle = mIoHandle;
5666 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005667}
5668
5669void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5670 struct audio_port *port) const
5671{
Eric Laurent84c70242014-06-23 08:46:27 -07005672 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005673 mProfile->toAudioPort(port);
5674 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005675 toAudioPortConfig(&port->active_config);
5676 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005677 port->ext.mix.handle = mIoHandle;
5678 port->ext.mix.latency_class =
5679 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5680}
Eric Laurente552edb2014-03-10 17:42:56 -07005681
Eric Laurente0720872014-03-11 09:30:41 -07005682status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005683{
5684 const size_t SIZE = 256;
5685 char buffer[SIZE];
5686 String8 result;
5687
Eric Laurent4d416952014-08-10 14:07:09 -07005688 snprintf(buffer, SIZE, " ID: %d\n", mId);
5689 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005690 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5691 result.append(buffer);
5692 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5693 result.append(buffer);
5694 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5695 result.append(buffer);
5696 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5697 result.append(buffer);
5698 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5699 result.append(buffer);
5700 snprintf(buffer, SIZE, " Devices %08x\n", device());
5701 result.append(buffer);
5702 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5703 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005704 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5705 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5706 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005707 result.append(buffer);
5708 }
5709 write(fd, result.string(), result.size());
5710
5711 return NO_ERROR;
5712}
5713
5714// --- AudioInputDescriptor class implementation
5715
Eric Laurent1c333e22014-05-20 10:48:17 -07005716AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005717 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005718 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005719 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005720{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005721 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005722 mSamplingRate = profile->pickSamplingRate();
5723 mFormat = profile->pickFormat();
5724 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005725 if (profile->mGains.size() > 0) {
5726 profile->mGains[0]->getDefaultConfig(&mGain);
5727 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005728 }
Eric Laurente552edb2014-03-10 17:42:56 -07005729}
5730
Eric Laurent1c333e22014-05-20 10:48:17 -07005731void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005732 struct audio_port_config *dstConfig,
5733 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005734{
Eric Laurent84c70242014-06-23 08:46:27 -07005735 ALOG_ASSERT(mProfile != 0,
5736 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005737 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5738 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5739 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005740 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005741 }
5742
5743 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5744
Eric Laurent6a94d692014-05-20 11:18:06 -07005745 dstConfig->id = mId;
5746 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5747 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005748 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5749 dstConfig->ext.mix.handle = mIoHandle;
5750 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005751}
5752
5753void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5754 struct audio_port *port) const
5755{
Eric Laurent84c70242014-06-23 08:46:27 -07005756 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5757
Eric Laurent1c333e22014-05-20 10:48:17 -07005758 mProfile->toAudioPort(port);
5759 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005760 toAudioPortConfig(&port->active_config);
5761 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005762 port->ext.mix.handle = mIoHandle;
5763 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5764}
5765
Eric Laurente0720872014-03-11 09:30:41 -07005766status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005767{
5768 const size_t SIZE = 256;
5769 char buffer[SIZE];
5770 String8 result;
5771
Eric Laurent4d416952014-08-10 14:07:09 -07005772 snprintf(buffer, SIZE, " ID: %d\n", mId);
5773 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005774 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5775 result.append(buffer);
5776 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5777 result.append(buffer);
5778 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5779 result.append(buffer);
5780 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5781 result.append(buffer);
5782 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5783 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005784 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5785 result.append(buffer);
5786
Eric Laurente552edb2014-03-10 17:42:56 -07005787 write(fd, result.string(), result.size());
5788
5789 return NO_ERROR;
5790}
5791
5792// --- StreamDescriptor class implementation
5793
Eric Laurente0720872014-03-11 09:30:41 -07005794AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005795 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5796{
5797 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5798}
5799
Eric Laurente0720872014-03-11 09:30:41 -07005800int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005801{
Eric Laurente0720872014-03-11 09:30:41 -07005802 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005803 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5804 if (mIndexCur.indexOfKey(device) < 0) {
5805 device = AUDIO_DEVICE_OUT_DEFAULT;
5806 }
5807 return mIndexCur.valueFor(device);
5808}
5809
Eric Laurente0720872014-03-11 09:30:41 -07005810void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005811{
5812 const size_t SIZE = 256;
5813 char buffer[SIZE];
5814 String8 result;
5815
5816 snprintf(buffer, SIZE, "%s %02d %02d ",
5817 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5818 result.append(buffer);
5819 for (size_t i = 0; i < mIndexCur.size(); i++) {
5820 snprintf(buffer, SIZE, "%04x : %02d, ",
5821 mIndexCur.keyAt(i),
5822 mIndexCur.valueAt(i));
5823 result.append(buffer);
5824 }
5825 result.append("\n");
5826
5827 write(fd, result.string(), result.size());
5828}
5829
5830// --- EffectDescriptor class implementation
5831
Eric Laurente0720872014-03-11 09:30:41 -07005832status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005833{
5834 const size_t SIZE = 256;
5835 char buffer[SIZE];
5836 String8 result;
5837
5838 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5839 result.append(buffer);
5840 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5841 result.append(buffer);
5842 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5843 result.append(buffer);
5844 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5845 result.append(buffer);
5846 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5847 result.append(buffer);
5848 write(fd, result.string(), result.size());
5849
5850 return NO_ERROR;
5851}
5852
Eric Laurent1c333e22014-05-20 10:48:17 -07005853// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005854
Eric Laurente0720872014-03-11 09:30:41 -07005855AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005856 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5857 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005858{
5859}
5860
Eric Laurente0720872014-03-11 09:30:41 -07005861AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005862{
5863 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005864 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005865 }
5866 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005867 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005868 }
5869 free((void *)mName);
5870}
5871
Eric Laurent1afeecb2014-05-14 08:52:28 -07005872status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5873{
5874 cnode *node = root->first_child;
5875
5876 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5877
5878 while (node) {
5879 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5880 profile->loadSamplingRates((char *)node->value);
5881 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5882 profile->loadFormats((char *)node->value);
5883 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5884 profile->loadInChannels((char *)node->value);
5885 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5886 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5887 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005888 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5889 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005890 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5891 profile->loadGains(node);
5892 }
5893 node = node->next;
5894 }
5895 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5896 "loadInput() invalid supported devices");
5897 ALOGW_IF(profile->mChannelMasks.size() == 0,
5898 "loadInput() invalid supported channel masks");
5899 ALOGW_IF(profile->mSamplingRates.size() == 0,
5900 "loadInput() invalid supported sampling rates");
5901 ALOGW_IF(profile->mFormats.size() == 0,
5902 "loadInput() invalid supported formats");
5903 if (!profile->mSupportedDevices.isEmpty() &&
5904 (profile->mChannelMasks.size() != 0) &&
5905 (profile->mSamplingRates.size() != 0) &&
5906 (profile->mFormats.size() != 0)) {
5907
5908 ALOGV("loadInput() adding input Supported Devices %04x",
5909 profile->mSupportedDevices.types());
5910
5911 mInputProfiles.add(profile);
5912 return NO_ERROR;
5913 } else {
5914 return BAD_VALUE;
5915 }
5916}
5917
5918status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5919{
5920 cnode *node = root->first_child;
5921
5922 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5923
5924 while (node) {
5925 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5926 profile->loadSamplingRates((char *)node->value);
5927 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5928 profile->loadFormats((char *)node->value);
5929 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5930 profile->loadOutChannels((char *)node->value);
5931 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5932 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5933 mDeclaredDevices);
5934 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005935 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005936 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5937 profile->loadGains(node);
5938 }
5939 node = node->next;
5940 }
5941 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5942 "loadOutput() invalid supported devices");
5943 ALOGW_IF(profile->mChannelMasks.size() == 0,
5944 "loadOutput() invalid supported channel masks");
5945 ALOGW_IF(profile->mSamplingRates.size() == 0,
5946 "loadOutput() invalid supported sampling rates");
5947 ALOGW_IF(profile->mFormats.size() == 0,
5948 "loadOutput() invalid supported formats");
5949 if (!profile->mSupportedDevices.isEmpty() &&
5950 (profile->mChannelMasks.size() != 0) &&
5951 (profile->mSamplingRates.size() != 0) &&
5952 (profile->mFormats.size() != 0)) {
5953
5954 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5955 profile->mSupportedDevices.types(), profile->mFlags);
5956
5957 mOutputProfiles.add(profile);
5958 return NO_ERROR;
5959 } else {
5960 return BAD_VALUE;
5961 }
5962}
5963
5964status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5965{
5966 cnode *node = root->first_child;
5967
5968 audio_devices_t type = AUDIO_DEVICE_NONE;
5969 while (node) {
5970 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5971 type = parseDeviceNames((char *)node->value);
5972 break;
5973 }
5974 node = node->next;
5975 }
5976 if (type == AUDIO_DEVICE_NONE ||
5977 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5978 ALOGW("loadDevice() bad type %08x", type);
5979 return BAD_VALUE;
5980 }
5981 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5982 deviceDesc->mModule = this;
5983
5984 node = root->first_child;
5985 while (node) {
5986 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5987 deviceDesc->mAddress = String8((char *)node->value);
5988 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5989 if (audio_is_input_device(type)) {
5990 deviceDesc->loadInChannels((char *)node->value);
5991 } else {
5992 deviceDesc->loadOutChannels((char *)node->value);
5993 }
5994 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5995 deviceDesc->loadGains(node);
5996 }
5997 node = node->next;
5998 }
5999
6000 ALOGV("loadDevice() adding device name %s type %08x address %s",
6001 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6002
6003 mDeclaredDevices.add(deviceDesc);
6004
6005 return NO_ERROR;
6006}
6007
Eric Laurente0720872014-03-11 09:30:41 -07006008void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006009{
6010 const size_t SIZE = 256;
6011 char buffer[SIZE];
6012 String8 result;
6013
6014 snprintf(buffer, SIZE, " - name: %s\n", mName);
6015 result.append(buffer);
6016 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6017 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006018 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6019 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006020 write(fd, result.string(), result.size());
6021 if (mOutputProfiles.size()) {
6022 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6023 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006024 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006025 write(fd, buffer, strlen(buffer));
6026 mOutputProfiles[i]->dump(fd);
6027 }
6028 }
6029 if (mInputProfiles.size()) {
6030 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6031 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006032 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006033 write(fd, buffer, strlen(buffer));
6034 mInputProfiles[i]->dump(fd);
6035 }
6036 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006037 if (mDeclaredDevices.size()) {
6038 write(fd, " - devices:\n", strlen(" - devices:\n"));
6039 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6040 mDeclaredDevices[i]->dump(fd, 4, i);
6041 }
6042 }
Eric Laurente552edb2014-03-10 17:42:56 -07006043}
6044
Eric Laurent1c333e22014-05-20 10:48:17 -07006045// --- AudioPort class implementation
6046
Eric Laurenta121f902014-06-03 13:32:54 -07006047
6048AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6049 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006050 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006051{
6052 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6053 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6054}
6055
Eric Laurent1c333e22014-05-20 10:48:17 -07006056void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6057{
6058 port->role = mRole;
6059 port->type = mType;
6060 unsigned int i;
6061 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006062 if (mSamplingRates[i] != 0) {
6063 port->sample_rates[i] = mSamplingRates[i];
6064 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006065 }
6066 port->num_sample_rates = i;
6067 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006068 if (mChannelMasks[i] != 0) {
6069 port->channel_masks[i] = mChannelMasks[i];
6070 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006071 }
6072 port->num_channel_masks = i;
6073 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006074 if (mFormats[i] != 0) {
6075 port->formats[i] = mFormats[i];
6076 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006077 }
6078 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006079
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006080 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006081
6082 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6083 port->gains[i] = mGains[i]->mGain;
6084 }
6085 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006086}
6087
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006088void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6089 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6090 const uint32_t rate = port->mSamplingRates.itemAt(k);
6091 if (rate != 0) { // skip "dynamic" rates
6092 bool hasRate = false;
6093 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6094 if (rate == mSamplingRates.itemAt(l)) {
6095 hasRate = true;
6096 break;
6097 }
6098 }
6099 if (!hasRate) { // never import a sampling rate twice
6100 mSamplingRates.add(rate);
6101 }
6102 }
6103 }
6104 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6105 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6106 if (mask != 0) { // skip "dynamic" masks
6107 bool hasMask = false;
6108 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6109 if (mask == mChannelMasks.itemAt(l)) {
6110 hasMask = true;
6111 break;
6112 }
6113 }
6114 if (!hasMask) { // never import a channel mask twice
6115 mChannelMasks.add(mask);
6116 }
6117 }
6118 }
6119 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6120 const audio_format_t format = port->mFormats.itemAt(k);
6121 if (format != 0) { // skip "dynamic" formats
6122 bool hasFormat = false;
6123 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6124 if (format == mFormats.itemAt(l)) {
6125 hasFormat = true;
6126 break;
6127 }
6128 }
6129 if (!hasFormat) { // never import a channel mask twice
6130 mFormats.add(format);
6131 }
6132 }
6133 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006134 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6135 sp<AudioGain> gain = port->mGains.itemAt(k);
6136 if (gain != 0) {
6137 bool hasGain = false;
6138 for (size_t l = 0 ; l < mGains.size() ; l++) {
6139 if (gain == mGains.itemAt(l)) {
6140 hasGain = true;
6141 break;
6142 }
6143 }
6144 if (!hasGain) { // never import a gain twice
6145 mGains.add(gain);
6146 }
6147 }
6148 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006149}
6150
6151void AudioPolicyManager::AudioPort::clearCapabilities() {
6152 mChannelMasks.clear();
6153 mFormats.clear();
6154 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006155 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006156}
Eric Laurent1c333e22014-05-20 10:48:17 -07006157
6158void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6159{
6160 char *str = strtok(name, "|");
6161
6162 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6163 // rates should be read from the output stream after it is opened for the first time
6164 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6165 mSamplingRates.add(0);
6166 return;
6167 }
6168
6169 while (str != NULL) {
6170 uint32_t rate = atoi(str);
6171 if (rate != 0) {
6172 ALOGV("loadSamplingRates() adding rate %d", rate);
6173 mSamplingRates.add(rate);
6174 }
6175 str = strtok(NULL, "|");
6176 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006177}
6178
6179void AudioPolicyManager::AudioPort::loadFormats(char *name)
6180{
6181 char *str = strtok(name, "|");
6182
6183 // by convention, "0' in the first entry in mFormats indicates the supported formats
6184 // should be read from the output stream after it is opened for the first time
6185 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6186 mFormats.add(AUDIO_FORMAT_DEFAULT);
6187 return;
6188 }
6189
6190 while (str != NULL) {
6191 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6192 ARRAY_SIZE(sFormatNameToEnumTable),
6193 str);
6194 if (format != AUDIO_FORMAT_DEFAULT) {
6195 mFormats.add(format);
6196 }
6197 str = strtok(NULL, "|");
6198 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006199}
6200
6201void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6202{
6203 const char *str = strtok(name, "|");
6204
6205 ALOGV("loadInChannels() %s", name);
6206
6207 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6208 mChannelMasks.add(0);
6209 return;
6210 }
6211
6212 while (str != NULL) {
6213 audio_channel_mask_t channelMask =
6214 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6215 ARRAY_SIZE(sInChannelsNameToEnumTable),
6216 str);
6217 if (channelMask != 0) {
6218 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6219 mChannelMasks.add(channelMask);
6220 }
6221 str = strtok(NULL, "|");
6222 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006223}
6224
6225void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6226{
6227 const char *str = strtok(name, "|");
6228
6229 ALOGV("loadOutChannels() %s", name);
6230
6231 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6232 // masks should be read from the output stream after it is opened for the first time
6233 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6234 mChannelMasks.add(0);
6235 return;
6236 }
6237
6238 while (str != NULL) {
6239 audio_channel_mask_t channelMask =
6240 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6241 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6242 str);
6243 if (channelMask != 0) {
6244 mChannelMasks.add(channelMask);
6245 }
6246 str = strtok(NULL, "|");
6247 }
6248 return;
6249}
6250
Eric Laurent1afeecb2014-05-14 08:52:28 -07006251audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6252{
6253 const char *str = strtok(name, "|");
6254
6255 ALOGV("loadGainMode() %s", name);
6256 audio_gain_mode_t mode = 0;
6257 while (str != NULL) {
6258 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6259 ARRAY_SIZE(sGainModeNameToEnumTable),
6260 str);
6261 str = strtok(NULL, "|");
6262 }
6263 return mode;
6264}
6265
Eric Laurenta121f902014-06-03 13:32:54 -07006266void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006267{
6268 cnode *node = root->first_child;
6269
Eric Laurenta121f902014-06-03 13:32:54 -07006270 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006271
6272 while (node) {
6273 if (strcmp(node->name, GAIN_MODE) == 0) {
6274 gain->mGain.mode = loadGainMode((char *)node->value);
6275 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006276 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006277 gain->mGain.channel_mask =
6278 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6279 ARRAY_SIZE(sInChannelsNameToEnumTable),
6280 (char *)node->value);
6281 } else {
6282 gain->mGain.channel_mask =
6283 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6284 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6285 (char *)node->value);
6286 }
6287 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6288 gain->mGain.min_value = atoi((char *)node->value);
6289 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6290 gain->mGain.max_value = atoi((char *)node->value);
6291 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6292 gain->mGain.default_value = atoi((char *)node->value);
6293 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6294 gain->mGain.step_value = atoi((char *)node->value);
6295 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6296 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6297 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6298 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6299 }
6300 node = node->next;
6301 }
6302
6303 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6304 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6305
6306 if (gain->mGain.mode == 0) {
6307 return;
6308 }
6309 mGains.add(gain);
6310}
6311
6312void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6313{
6314 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006315 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006316 while (node) {
6317 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006318 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006319 node = node->next;
6320 }
6321}
6322
Glenn Kastencbd48022014-07-24 13:46:44 -07006323status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006324{
6325 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6326 if (mSamplingRates[i] == samplingRate) {
6327 return NO_ERROR;
6328 }
6329 }
6330 return BAD_VALUE;
6331}
6332
Glenn Kastencbd48022014-07-24 13:46:44 -07006333status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6334 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006335{
Glenn Kastencbd48022014-07-24 13:46:44 -07006336 // Search for the closest supported sampling rate that is above (preferred)
6337 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6338 // The sampling rates do not need to be sorted in ascending order.
6339 ssize_t maxBelow = -1;
6340 ssize_t minAbove = -1;
6341 uint32_t candidate;
6342 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6343 candidate = mSamplingRates[i];
6344 if (candidate == samplingRate) {
6345 if (updatedSamplingRate != NULL) {
6346 *updatedSamplingRate = candidate;
6347 }
6348 return NO_ERROR;
6349 }
6350 // candidate < desired
6351 if (candidate < samplingRate) {
6352 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6353 maxBelow = i;
6354 }
6355 // candidate > desired
6356 } else {
6357 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6358 minAbove = i;
6359 }
6360 }
6361 }
6362 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6363 // TODO Move these assumptions out.
6364 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6365 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6366 // due to approximation by an int32_t of the
6367 // phase increments
6368 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6369 if (minAbove >= 0) {
6370 candidate = mSamplingRates[minAbove];
6371 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6372 if (updatedSamplingRate != NULL) {
6373 *updatedSamplingRate = candidate;
6374 }
6375 return NO_ERROR;
6376 }
6377 }
6378 // But if we have to up-sample from a lower sampling rate, that's OK.
6379 if (maxBelow >= 0) {
6380 candidate = mSamplingRates[maxBelow];
6381 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6382 if (updatedSamplingRate != NULL) {
6383 *updatedSamplingRate = candidate;
6384 }
6385 return NO_ERROR;
6386 }
6387 }
6388 // leave updatedSamplingRate unmodified
6389 return BAD_VALUE;
6390}
6391
6392status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6393{
6394 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006395 if (mChannelMasks[i] == channelMask) {
6396 return NO_ERROR;
6397 }
6398 }
6399 return BAD_VALUE;
6400}
6401
Glenn Kastencbd48022014-07-24 13:46:44 -07006402status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6403 const
6404{
6405 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6406 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6407 // FIXME Does not handle multi-channel automatic conversions yet
6408 audio_channel_mask_t supported = mChannelMasks[i];
6409 if (supported == channelMask) {
6410 return NO_ERROR;
6411 }
6412 if (isRecordThread) {
6413 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6414 // FIXME Abstract this out to a table.
6415 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6416 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6417 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6418 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6419 return NO_ERROR;
6420 }
6421 }
6422 }
6423 return BAD_VALUE;
6424}
6425
Eric Laurenta121f902014-06-03 13:32:54 -07006426status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6427{
6428 for (size_t i = 0; i < mFormats.size(); i ++) {
6429 if (mFormats[i] == format) {
6430 return NO_ERROR;
6431 }
6432 }
6433 return BAD_VALUE;
6434}
6435
Eric Laurent1e693b52014-07-09 15:03:28 -07006436
6437uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6438{
6439 // special case for uninitialized dynamic profile
6440 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6441 return 0;
6442 }
6443
Eric Laurent828bcff2014-09-07 12:26:06 -07006444 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6445 // channel count / sampling rate combination chosen will be supported by the connected
6446 // sink
6447 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6448 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6449 uint32_t samplingRate = UINT_MAX;
6450 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6451 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6452 samplingRate = mSamplingRates[i];
6453 }
6454 }
6455 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6456 }
6457
Eric Laurent1e693b52014-07-09 15:03:28 -07006458 uint32_t samplingRate = 0;
6459 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6460
6461 // For mixed output and inputs, use max mixer sampling rates. Do not
6462 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006463 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006464 maxRate = UINT_MAX;
6465 }
6466 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6467 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6468 samplingRate = mSamplingRates[i];
6469 }
6470 }
6471 return samplingRate;
6472}
6473
6474audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6475{
6476 // special case for uninitialized dynamic profile
6477 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6478 return AUDIO_CHANNEL_NONE;
6479 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006480 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006481
6482 // For direct outputs, pick minimum channel count: this helps ensuring that the
6483 // channel count / sampling rate combination chosen will be supported by the connected
6484 // sink
6485 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6486 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6487 uint32_t channelCount = UINT_MAX;
6488 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6489 uint32_t cnlCount;
6490 if (mUseInChannelMask) {
6491 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6492 } else {
6493 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6494 }
6495 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6496 channelMask = mChannelMasks[i];
6497 channelCount = cnlCount;
6498 }
6499 }
6500 return channelMask;
6501 }
6502
Eric Laurent1e693b52014-07-09 15:03:28 -07006503 uint32_t channelCount = 0;
6504 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6505
6506 // For mixed output and inputs, use max mixer channel count. Do not
6507 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006508 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006509 maxCount = UINT_MAX;
6510 }
6511 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6512 uint32_t cnlCount;
6513 if (mUseInChannelMask) {
6514 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6515 } else {
6516 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6517 }
6518 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6519 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006520 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006521 }
6522 }
6523 return channelMask;
6524}
6525
Andy Hung9a605382014-07-28 16:16:31 -07006526/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006527const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6528 AUDIO_FORMAT_DEFAULT,
6529 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006530 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006531 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006532 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006533 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006534};
6535
6536int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6537 audio_format_t format2)
6538{
6539 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6540 // compressed format and better than any PCM format. This is by design of pickFormat()
6541 if (!audio_is_linear_pcm(format1)) {
6542 if (!audio_is_linear_pcm(format2)) {
6543 return 0;
6544 }
6545 return 1;
6546 }
6547 if (!audio_is_linear_pcm(format2)) {
6548 return -1;
6549 }
6550
6551 int index1 = -1, index2 = -1;
6552 for (size_t i = 0;
6553 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6554 i ++) {
6555 if (sPcmFormatCompareTable[i] == format1) {
6556 index1 = i;
6557 }
6558 if (sPcmFormatCompareTable[i] == format2) {
6559 index2 = i;
6560 }
6561 }
6562 // format1 not found => index1 < 0 => format2 > format1
6563 // format2 not found => index2 < 0 => format2 < format1
6564 return index1 - index2;
6565}
6566
6567audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6568{
6569 // special case for uninitialized dynamic profile
6570 if (mFormats.size() == 1 && mFormats[0] == 0) {
6571 return AUDIO_FORMAT_DEFAULT;
6572 }
6573
6574 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006575 audio_format_t bestFormat =
6576 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6577 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006578 // For mixed output and inputs, use best mixer output format. Do not
6579 // limit format otherwise
6580 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6581 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006582 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006583 bestFormat = AUDIO_FORMAT_INVALID;
6584 }
6585
6586 for (size_t i = 0; i < mFormats.size(); i ++) {
6587 if ((compareFormats(mFormats[i], format) > 0) &&
6588 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6589 format = mFormats[i];
6590 }
6591 }
6592 return format;
6593}
6594
Eric Laurenta121f902014-06-03 13:32:54 -07006595status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6596 int index) const
6597{
6598 if (index < 0 || (size_t)index >= mGains.size()) {
6599 return BAD_VALUE;
6600 }
6601 return mGains[index]->checkConfig(gainConfig);
6602}
6603
Eric Laurent1afeecb2014-05-14 08:52:28 -07006604void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6605{
6606 const size_t SIZE = 256;
6607 char buffer[SIZE];
6608 String8 result;
6609
6610 if (mName.size() != 0) {
6611 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6612 result.append(buffer);
6613 }
6614
6615 if (mSamplingRates.size() != 0) {
6616 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6617 result.append(buffer);
6618 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006619 if (i == 0 && mSamplingRates[i] == 0) {
6620 snprintf(buffer, SIZE, "Dynamic");
6621 } else {
6622 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6623 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006624 result.append(buffer);
6625 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6626 }
6627 result.append("\n");
6628 }
6629
6630 if (mChannelMasks.size() != 0) {
6631 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6632 result.append(buffer);
6633 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006634 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6635
6636 if (i == 0 && mChannelMasks[i] == 0) {
6637 snprintf(buffer, SIZE, "Dynamic");
6638 } else {
6639 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6640 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006641 result.append(buffer);
6642 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6643 }
6644 result.append("\n");
6645 }
6646
6647 if (mFormats.size() != 0) {
6648 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6649 result.append(buffer);
6650 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006651 const char *formatStr = enumToString(sFormatNameToEnumTable,
6652 ARRAY_SIZE(sFormatNameToEnumTable),
6653 mFormats[i]);
6654 if (i == 0 && strcmp(formatStr, "") == 0) {
6655 snprintf(buffer, SIZE, "Dynamic");
6656 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006657 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006658 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006659 result.append(buffer);
6660 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6661 }
6662 result.append("\n");
6663 }
6664 write(fd, result.string(), result.size());
6665 if (mGains.size() != 0) {
6666 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6667 write(fd, buffer, strlen(buffer) + 1);
6668 result.append(buffer);
6669 for (size_t i = 0; i < mGains.size(); i++) {
6670 mGains[i]->dump(fd, spaces + 2, i);
6671 }
6672 }
6673}
6674
6675// --- AudioGain class implementation
6676
Eric Laurenta121f902014-06-03 13:32:54 -07006677AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006678{
Eric Laurenta121f902014-06-03 13:32:54 -07006679 mIndex = index;
6680 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006681 memset(&mGain, 0, sizeof(struct audio_gain));
6682}
6683
Eric Laurenta121f902014-06-03 13:32:54 -07006684void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6685{
6686 config->index = mIndex;
6687 config->mode = mGain.mode;
6688 config->channel_mask = mGain.channel_mask;
6689 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6690 config->values[0] = mGain.default_value;
6691 } else {
6692 uint32_t numValues;
6693 if (mUseInChannelMask) {
6694 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6695 } else {
6696 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6697 }
6698 for (size_t i = 0; i < numValues; i++) {
6699 config->values[i] = mGain.default_value;
6700 }
6701 }
6702 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6703 config->ramp_duration_ms = mGain.min_ramp_ms;
6704 }
6705}
6706
6707status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6708{
6709 if ((config->mode & ~mGain.mode) != 0) {
6710 return BAD_VALUE;
6711 }
6712 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6713 if ((config->values[0] < mGain.min_value) ||
6714 (config->values[0] > mGain.max_value)) {
6715 return BAD_VALUE;
6716 }
6717 } else {
6718 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6719 return BAD_VALUE;
6720 }
6721 uint32_t numValues;
6722 if (mUseInChannelMask) {
6723 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6724 } else {
6725 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6726 }
6727 for (size_t i = 0; i < numValues; i++) {
6728 if ((config->values[i] < mGain.min_value) ||
6729 (config->values[i] > mGain.max_value)) {
6730 return BAD_VALUE;
6731 }
6732 }
6733 }
6734 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6735 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6736 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6737 return BAD_VALUE;
6738 }
6739 }
6740 return NO_ERROR;
6741}
6742
Eric Laurent1afeecb2014-05-14 08:52:28 -07006743void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6744{
6745 const size_t SIZE = 256;
6746 char buffer[SIZE];
6747 String8 result;
6748
6749 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6750 result.append(buffer);
6751 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6752 result.append(buffer);
6753 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6754 result.append(buffer);
6755 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6756 result.append(buffer);
6757 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6758 result.append(buffer);
6759 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6760 result.append(buffer);
6761 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6762 result.append(buffer);
6763 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6764 result.append(buffer);
6765 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6766 result.append(buffer);
6767
6768 write(fd, result.string(), result.size());
6769}
6770
Eric Laurent1f2f2232014-06-02 12:01:23 -07006771// --- AudioPortConfig class implementation
6772
6773AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6774{
6775 mSamplingRate = 0;
6776 mChannelMask = AUDIO_CHANNEL_NONE;
6777 mFormat = AUDIO_FORMAT_INVALID;
6778 mGain.index = -1;
6779}
6780
Eric Laurenta121f902014-06-03 13:32:54 -07006781status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6782 const struct audio_port_config *config,
6783 struct audio_port_config *backupConfig)
6784{
6785 struct audio_port_config localBackupConfig;
6786 status_t status = NO_ERROR;
6787
6788 localBackupConfig.config_mask = config->config_mask;
6789 toAudioPortConfig(&localBackupConfig);
6790
Marco Nelissen961ec212014-08-25 15:58:39 -07006791 sp<AudioPort> audioport = getAudioPort();
6792 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006793 status = NO_INIT;
6794 goto exit;
6795 }
6796 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006797 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006798 if (status != NO_ERROR) {
6799 goto exit;
6800 }
6801 mSamplingRate = config->sample_rate;
6802 }
6803 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006804 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006805 if (status != NO_ERROR) {
6806 goto exit;
6807 }
6808 mChannelMask = config->channel_mask;
6809 }
6810 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006811 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006812 if (status != NO_ERROR) {
6813 goto exit;
6814 }
6815 mFormat = config->format;
6816 }
6817 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006818 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006819 if (status != NO_ERROR) {
6820 goto exit;
6821 }
6822 mGain = config->gain;
6823 }
6824
6825exit:
6826 if (status != NO_ERROR) {
6827 applyAudioPortConfig(&localBackupConfig);
6828 }
6829 if (backupConfig != NULL) {
6830 *backupConfig = localBackupConfig;
6831 }
6832 return status;
6833}
6834
Eric Laurent1f2f2232014-06-02 12:01:23 -07006835void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6836 struct audio_port_config *dstConfig,
6837 const struct audio_port_config *srcConfig) const
6838{
6839 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6840 dstConfig->sample_rate = mSamplingRate;
6841 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6842 dstConfig->sample_rate = srcConfig->sample_rate;
6843 }
6844 } else {
6845 dstConfig->sample_rate = 0;
6846 }
6847 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6848 dstConfig->channel_mask = mChannelMask;
6849 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6850 dstConfig->channel_mask = srcConfig->channel_mask;
6851 }
6852 } else {
6853 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6854 }
6855 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6856 dstConfig->format = mFormat;
6857 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6858 dstConfig->format = srcConfig->format;
6859 }
6860 } else {
6861 dstConfig->format = AUDIO_FORMAT_INVALID;
6862 }
6863 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6864 dstConfig->gain = mGain;
6865 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6866 dstConfig->gain = srcConfig->gain;
6867 }
6868 } else {
6869 dstConfig->gain.index = -1;
6870 }
6871 if (dstConfig->gain.index != -1) {
6872 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6873 } else {
6874 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6875 }
6876}
6877
Eric Laurent1c333e22014-05-20 10:48:17 -07006878// --- IOProfile class implementation
6879
Eric Laurent1afeecb2014-05-14 08:52:28 -07006880AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006881 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006882 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006883{
6884}
6885
Eric Laurente0720872014-03-11 09:30:41 -07006886AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006887{
6888}
6889
6890// checks if the IO profile is compatible with specified parameters.
6891// Sampling rate, format and channel mask must be specified in order to
6892// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006893bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006894 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006895 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006896 audio_format_t format,
6897 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006898 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006899{
Glenn Kastencbd48022014-07-24 13:46:44 -07006900 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6901 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6902 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006903
Glenn Kastencbd48022014-07-24 13:46:44 -07006904 if ((mSupportedDevices.types() & device) != device) {
6905 return false;
6906 }
6907
6908 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006909 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006910 }
6911 uint32_t myUpdatedSamplingRate = samplingRate;
6912 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006913 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006914 }
6915 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6916 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006917 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006918 }
6919
6920 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6921 return false;
6922 }
6923
6924 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6925 checkExactChannelMask(channelMask) != NO_ERROR)) {
6926 return false;
6927 }
6928 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6929 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6930 return false;
6931 }
6932
6933 if (isPlaybackThread && (mFlags & flags) != flags) {
6934 return false;
6935 }
6936 // The only input flag that is allowed to be different is the fast flag.
6937 // An existing fast stream is compatible with a normal track request.
6938 // An existing normal stream is compatible with a fast track request,
6939 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006940 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006941 ~AUDIO_INPUT_FLAG_FAST)) {
6942 return false;
6943 }
6944
6945 if (updatedSamplingRate != NULL) {
6946 *updatedSamplingRate = myUpdatedSamplingRate;
6947 }
6948 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006949}
6950
Eric Laurente0720872014-03-11 09:30:41 -07006951void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006952{
6953 const size_t SIZE = 256;
6954 char buffer[SIZE];
6955 String8 result;
6956
Eric Laurent1afeecb2014-05-14 08:52:28 -07006957 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006958
Eric Laurente552edb2014-03-10 17:42:56 -07006959 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6960 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006961 snprintf(buffer, SIZE, " - devices:\n");
6962 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006963 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006964 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6965 mSupportedDevices[i]->dump(fd, 6, i);
6966 }
Eric Laurente552edb2014-03-10 17:42:56 -07006967}
6968
Eric Laurentd4692962014-05-05 18:13:44 -07006969void AudioPolicyManager::IOProfile::log()
6970{
6971 const size_t SIZE = 256;
6972 char buffer[SIZE];
6973 String8 result;
6974
6975 ALOGV(" - sampling rates: ");
6976 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6977 ALOGV(" %d", mSamplingRates[i]);
6978 }
6979
6980 ALOGV(" - channel masks: ");
6981 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6982 ALOGV(" 0x%04x", mChannelMasks[i]);
6983 }
6984
6985 ALOGV(" - formats: ");
6986 for (size_t i = 0; i < mFormats.size(); i++) {
6987 ALOGV(" 0x%08x", mFormats[i]);
6988 }
6989
6990 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6991 ALOGV(" - flags: 0x%04x\n", mFlags);
6992}
6993
6994
Eric Laurent3a4311c2014-03-17 12:00:47 -07006995// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006996
Eric Laurent1f2f2232014-06-02 12:01:23 -07006997
6998AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6999 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7000 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7001 AUDIO_PORT_ROLE_SOURCE,
7002 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007003 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007004{
Eric Laurenta121f902014-06-03 13:32:54 -07007005 if (mGains.size() > 0) {
7006 mGains[0]->getDefaultConfig(&mGain);
7007 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07007008}
7009
Eric Laurent3a4311c2014-03-17 12:00:47 -07007010bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007011{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007012 // Devices are considered equal if they:
7013 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7014 // - have the same address or one device does not specify the address
7015 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007016 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007017 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007018 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007019 mChannelMask == other->mChannelMask);
7020}
7021
7022void AudioPolicyManager::DeviceVector::refreshTypes()
7023{
Eric Laurent1c333e22014-05-20 10:48:17 -07007024 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007025 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007026 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007027 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007028 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007029}
7030
7031ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7032{
7033 for(size_t i = 0; i < size(); i++) {
7034 if (item->equals(itemAt(i))) {
7035 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007036 }
7037 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007038 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007039}
7040
Eric Laurent3a4311c2014-03-17 12:00:47 -07007041ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007042{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007043 ssize_t ret = indexOf(item);
7044
7045 if (ret < 0) {
7046 ret = SortedVector::add(item);
7047 if (ret >= 0) {
7048 refreshTypes();
7049 }
7050 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007051 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007052 ret = -1;
7053 }
7054 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007055}
7056
Eric Laurent3a4311c2014-03-17 12:00:47 -07007057ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7058{
7059 size_t i;
7060 ssize_t ret = indexOf(item);
7061
7062 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007063 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007064 } else {
7065 ret = SortedVector::removeAt(ret);
7066 if (ret >= 0) {
7067 refreshTypes();
7068 }
7069 }
7070 return ret;
7071}
7072
7073void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7074{
7075 DeviceVector deviceList;
7076
7077 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7078 types &= ~role_bit;
7079
7080 while (types) {
7081 uint32_t i = 31 - __builtin_clz(types);
7082 uint32_t type = 1 << i;
7083 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007084 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007085 }
7086}
7087
Eric Laurent1afeecb2014-05-14 08:52:28 -07007088void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7089 const DeviceVector& declaredDevices)
7090{
7091 char *devName = strtok(name, "|");
7092 while (devName != NULL) {
7093 if (strlen(devName) != 0) {
7094 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7095 ARRAY_SIZE(sDeviceNameToEnumTable),
7096 devName);
7097 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007098 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
7099 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
7100 dev->mAddress = String8("0");
7101 }
7102 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007103 } else {
7104 sp<DeviceDescriptor> deviceDesc =
7105 declaredDevices.getDeviceFromName(String8(devName));
7106 if (deviceDesc != 0) {
7107 add(deviceDesc);
7108 }
7109 }
7110 }
7111 devName = strtok(NULL, "|");
7112 }
7113}
7114
Eric Laurent1c333e22014-05-20 10:48:17 -07007115sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7116 audio_devices_t type, String8 address) const
7117{
7118 sp<DeviceDescriptor> device;
7119 for (size_t i = 0; i < size(); i++) {
7120 if (itemAt(i)->mDeviceType == type) {
7121 device = itemAt(i);
7122 if (itemAt(i)->mAddress = address) {
7123 break;
7124 }
7125 }
7126 }
7127 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
7128 type, address.string(), device.get());
7129 return device;
7130}
7131
Eric Laurent6a94d692014-05-20 11:18:06 -07007132sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7133 audio_port_handle_t id) const
7134{
7135 sp<DeviceDescriptor> device;
7136 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007137 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007138 if (itemAt(i)->mId == id) {
7139 device = itemAt(i);
7140 break;
7141 }
7142 }
7143 return device;
7144}
7145
Eric Laurent1c333e22014-05-20 10:48:17 -07007146AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7147 audio_devices_t type) const
7148{
7149 DeviceVector devices;
7150 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7151 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7152 devices.add(itemAt(i));
7153 type &= ~itemAt(i)->mDeviceType;
7154 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7155 itemAt(i)->mDeviceType, itemAt(i).get());
7156 }
7157 }
7158 return devices;
7159}
7160
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007161AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7162 audio_devices_t type, String8 address) const
7163{
7164 DeviceVector devices;
7165 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
7166 for (size_t i = 0; i < size(); i++) {
7167 //ALOGV(" at i=%d: device=%x, addr=%s",
7168 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
7169 if (itemAt(i)->mDeviceType == type) {
7170 if (itemAt(i)->mAddress == address) {
7171 //ALOGV(" found matching address %s", address.string());
7172 devices.add(itemAt(i));
7173 }
7174 }
7175 }
7176 return devices;
7177}
7178
Eric Laurent1afeecb2014-05-14 08:52:28 -07007179sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7180 const String8& name) const
7181{
7182 sp<DeviceDescriptor> device;
7183 for (size_t i = 0; i < size(); i++) {
7184 if (itemAt(i)->mName == name) {
7185 device = itemAt(i);
7186 break;
7187 }
7188 }
7189 return device;
7190}
7191
Eric Laurent6a94d692014-05-20 11:18:06 -07007192void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7193 struct audio_port_config *dstConfig,
7194 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007195{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007196 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7197 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007198 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007199 }
7200
7201 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7202
Eric Laurent6a94d692014-05-20 11:18:06 -07007203 dstConfig->id = mId;
7204 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007205 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007206 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007207 dstConfig->ext.device.type = mDeviceType;
7208 dstConfig->ext.device.hw_module = mModule->mHandle;
7209 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007210}
7211
7212void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7213{
Eric Laurent83b88082014-06-20 18:31:16 -07007214 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007215 AudioPort::toAudioPort(port);
7216 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007217 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007218 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007219 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007220 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7221}
7222
Eric Laurent1afeecb2014-05-14 08:52:28 -07007223status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007224{
7225 const size_t SIZE = 256;
7226 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007227 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007228
Eric Laurent1afeecb2014-05-14 08:52:28 -07007229 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7230 result.append(buffer);
7231 if (mId != 0) {
7232 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7233 result.append(buffer);
7234 }
7235 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7236 enumToString(sDeviceNameToEnumTable,
7237 ARRAY_SIZE(sDeviceNameToEnumTable),
7238 mDeviceType));
7239 result.append(buffer);
7240 if (mAddress.size() != 0) {
7241 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7242 result.append(buffer);
7243 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007244 write(fd, result.string(), result.size());
7245 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007246
7247 return NO_ERROR;
7248}
7249
Eric Laurent4d416952014-08-10 14:07:09 -07007250status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7251{
7252 const size_t SIZE = 256;
7253 char buffer[SIZE];
7254 String8 result;
7255
7256
7257 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7258 result.append(buffer);
7259 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7260 result.append(buffer);
7261 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7262 result.append(buffer);
7263 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7264 result.append(buffer);
7265 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7266 result.append(buffer);
7267 for (size_t i = 0; i < mPatch.num_sources; i++) {
7268 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7269 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7270 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7271 ARRAY_SIZE(sDeviceNameToEnumTable),
7272 mPatch.sources[i].ext.device.type));
7273 } else {
7274 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7275 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7276 }
7277 result.append(buffer);
7278 }
7279 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7280 result.append(buffer);
7281 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7282 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7283 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7284 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7285 ARRAY_SIZE(sDeviceNameToEnumTable),
7286 mPatch.sinks[i].ext.device.type));
7287 } else {
7288 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7289 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7290 }
7291 result.append(buffer);
7292 }
7293
7294 write(fd, result.string(), result.size());
7295 return NO_ERROR;
7296}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007297
7298// --- audio_policy.conf file parsing
7299
Eric Laurent5dbe4712014-09-19 19:04:57 -07007300uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007301{
7302 uint32_t flag = 0;
7303
7304 // it is OK to cast name to non const here as we are not going to use it after
7305 // strtok() modifies it
7306 char *flagName = strtok(name, "|");
7307 while (flagName != NULL) {
7308 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007309 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7310 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007311 flagName);
7312 }
7313 flagName = strtok(NULL, "|");
7314 }
7315 //force direct flag if offload flag is set: offloading implies a direct output stream
7316 // and all common behaviors are driven by checking only the direct flag
7317 // this should normally be set appropriately in the policy configuration file
7318 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7319 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7320 }
7321
Eric Laurent5dbe4712014-09-19 19:04:57 -07007322 return flag;
7323}
7324
7325uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7326{
7327 uint32_t flag = 0;
7328
7329 // it is OK to cast name to non const here as we are not going to use it after
7330 // strtok() modifies it
7331 char *flagName = strtok(name, "|");
7332 while (flagName != NULL) {
7333 if (strlen(flagName) != 0) {
7334 flag |= stringToEnum(sInputFlagNameToEnumTable,
7335 ARRAY_SIZE(sInputFlagNameToEnumTable),
7336 flagName);
7337 }
7338 flagName = strtok(NULL, "|");
7339 }
7340 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007341}
7342
Eric Laurente0720872014-03-11 09:30:41 -07007343audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007344{
7345 uint32_t device = 0;
7346
7347 char *devName = strtok(name, "|");
7348 while (devName != NULL) {
7349 if (strlen(devName) != 0) {
7350 device |= stringToEnum(sDeviceNameToEnumTable,
7351 ARRAY_SIZE(sDeviceNameToEnumTable),
7352 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007353 }
Eric Laurente552edb2014-03-10 17:42:56 -07007354 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007355 }
Eric Laurente552edb2014-03-10 17:42:56 -07007356 return device;
7357}
7358
Eric Laurente0720872014-03-11 09:30:41 -07007359void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007360{
Eric Laurente552edb2014-03-10 17:42:56 -07007361 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007362 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007363 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007364
Eric Laurent1afeecb2014-05-14 08:52:28 -07007365 node = config_find(root, DEVICES_TAG);
7366 if (node != NULL) {
7367 node = node->first_child;
7368 while (node) {
7369 ALOGV("loadHwModule() loading device %s", node->name);
7370 status_t tmpStatus = module->loadDevice(node);
7371 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7372 status = tmpStatus;
7373 }
7374 node = node->next;
7375 }
7376 }
7377 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007378 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007379 node = node->first_child;
7380 while (node) {
7381 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007382 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007383 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7384 status = tmpStatus;
7385 }
7386 node = node->next;
7387 }
7388 }
7389 node = config_find(root, INPUTS_TAG);
7390 if (node != NULL) {
7391 node = node->first_child;
7392 while (node) {
7393 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007394 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007395 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7396 status = tmpStatus;
7397 }
7398 node = node->next;
7399 }
7400 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007401 loadGlobalConfig(root, module);
7402
Eric Laurente552edb2014-03-10 17:42:56 -07007403 if (status == NO_ERROR) {
7404 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007405 }
7406}
7407
Eric Laurente0720872014-03-11 09:30:41 -07007408void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007409{
7410 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7411 if (node == NULL) {
7412 return;
7413 }
7414
7415 node = node->first_child;
7416 while (node) {
7417 ALOGV("loadHwModules() loading module %s", node->name);
7418 loadHwModule(node);
7419 node = node->next;
7420 }
7421}
7422
Eric Laurent1f2f2232014-06-02 12:01:23 -07007423void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007424{
7425 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007426
Eric Laurente552edb2014-03-10 17:42:56 -07007427 if (node == NULL) {
7428 return;
7429 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007430 DeviceVector declaredDevices;
7431 if (module != NULL) {
7432 declaredDevices = module->mDeclaredDevices;
7433 }
7434
Eric Laurente552edb2014-03-10 17:42:56 -07007435 node = node->first_child;
7436 while (node) {
7437 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007438 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7439 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007440 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7441 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007442 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007443 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007444 ARRAY_SIZE(sDeviceNameToEnumTable),
7445 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007446 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007447 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007448 } else {
7449 ALOGW("loadGlobalConfig() default device not specified");
7450 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007451 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007452 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007453 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7454 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007455 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007456 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7457 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7458 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007459 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7460 uint32_t major, minor;
7461 sscanf((char *)node->value, "%u.%u", &major, &minor);
7462 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7463 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7464 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007465 }
7466 node = node->next;
7467 }
7468}
7469
Eric Laurente0720872014-03-11 09:30:41 -07007470status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007471{
7472 cnode *root;
7473 char *data;
7474
7475 data = (char *)load_file(path, NULL);
7476 if (data == NULL) {
7477 return -ENODEV;
7478 }
7479 root = config_node("", "");
7480 config_load(root, data);
7481
Eric Laurente552edb2014-03-10 17:42:56 -07007482 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007483 // legacy audio_policy.conf files have one global_configuration section
7484 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007485 config_free(root);
7486 free(root);
7487 free(data);
7488
7489 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7490
7491 return NO_ERROR;
7492}
7493
Eric Laurente0720872014-03-11 09:30:41 -07007494void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007495{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007496 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007497 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007498 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7499 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007500 mAvailableOutputDevices.add(mDefaultOutputDevice);
7501 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007502
7503 module = new HwModule("primary");
7504
Eric Laurent1afeecb2014-05-14 08:52:28 -07007505 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007506 profile->mSamplingRates.add(44100);
7507 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7508 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007509 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007510 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7511 module->mOutputProfiles.add(profile);
7512
Eric Laurent1afeecb2014-05-14 08:52:28 -07007513 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007514 profile->mSamplingRates.add(8000);
7515 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7516 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007517 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007518 module->mInputProfiles.add(profile);
7519
7520 mHwModules.add(module);
7521}
7522
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007523audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7524{
7525 // flags to stream type mapping
7526 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7527 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7528 }
7529 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7530 return AUDIO_STREAM_BLUETOOTH_SCO;
7531 }
7532
7533 // usage to stream type mapping
7534 switch (attr->usage) {
7535 case AUDIO_USAGE_MEDIA:
7536 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007537 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7538 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007539 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007540 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7541 return AUDIO_STREAM_ALARM;
7542 }
7543 if (isStreamActive(AUDIO_STREAM_RING)) {
7544 return AUDIO_STREAM_RING;
7545 }
7546 if (isInCall()) {
7547 return AUDIO_STREAM_VOICE_CALL;
7548 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08007549 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007550 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7551 return AUDIO_STREAM_SYSTEM;
7552 case AUDIO_USAGE_VOICE_COMMUNICATION:
7553 return AUDIO_STREAM_VOICE_CALL;
7554
7555 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7556 return AUDIO_STREAM_DTMF;
7557
7558 case AUDIO_USAGE_ALARM:
7559 return AUDIO_STREAM_ALARM;
7560 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7561 return AUDIO_STREAM_RING;
7562
7563 case AUDIO_USAGE_NOTIFICATION:
7564 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7565 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7566 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7567 case AUDIO_USAGE_NOTIFICATION_EVENT:
7568 return AUDIO_STREAM_NOTIFICATION;
7569
7570 case AUDIO_USAGE_UNKNOWN:
7571 default:
7572 return AUDIO_STREAM_MUSIC;
7573 }
7574}
Eric Laurente83b55d2014-11-14 10:06:21 -08007575
7576bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
7577 // has flags that map to a strategy?
7578 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7579 return true;
7580 }
7581
7582 // has known usage?
7583 switch (paa->usage) {
7584 case AUDIO_USAGE_UNKNOWN:
7585 case AUDIO_USAGE_MEDIA:
7586 case AUDIO_USAGE_VOICE_COMMUNICATION:
7587 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7588 case AUDIO_USAGE_ALARM:
7589 case AUDIO_USAGE_NOTIFICATION:
7590 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7591 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7592 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7593 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7594 case AUDIO_USAGE_NOTIFICATION_EVENT:
7595 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7596 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7597 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7598 case AUDIO_USAGE_GAME:
7599 break;
7600 default:
7601 return false;
7602 }
7603 return true;
7604}
7605
Eric Laurente552edb2014-03-10 17:42:56 -07007606}; // namespace android