blob: cd8df2f35b5c235102a506524da2b07f330d0dc2 [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 Laurente83b55d2014-11-14 10:06:21 -0800903 audio_session_t session,
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,
1297 audio_stream_type_t stream,
1298 audio_session_t session)
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 Laurente0720872014-03-11 09:30:41 -07001341audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001342 uint32_t samplingRate,
1343 audio_format_t format,
1344 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001345 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001346 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001347{
Eric Laurent4dc68062014-07-28 17:26:49 -07001348 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001349 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001350 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001351
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001352 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001353
1354 if (device == AUDIO_DEVICE_NONE) {
1355 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001356 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001357 }
1358
1359 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001360 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001361 case AUDIO_SOURCE_VOICE_UPLINK:
1362 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1363 break;
1364 case AUDIO_SOURCE_VOICE_DOWNLINK:
1365 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1366 break;
1367 case AUDIO_SOURCE_VOICE_CALL:
1368 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1369 break;
1370 default:
1371 break;
1372 }
1373
Eric Laurent5dbe4712014-09-19 19:04:57 -07001374 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1375 bool isSoundTrigger = false;
1376 audio_source_t halInputSource = inputSource;
1377 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1378 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1379 if (index >= 0) {
1380 input = mSoundTriggerSessions.valueFor(session);
1381 isSoundTrigger = true;
1382 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1383 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1384 } else {
1385 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1386 }
1387 }
1388
Eric Laurent1c333e22014-05-20 10:48:17 -07001389 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001390 samplingRate,
1391 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001392 channelMask,
1393 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001394 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001395 //retry without flags
1396 audio_input_flags_t log_flags = flags;
1397 flags = AUDIO_INPUT_FLAG_NONE;
1398 profile = getInputProfile(device,
1399 samplingRate,
1400 format,
1401 channelMask,
1402 flags);
1403 if (profile == 0) {
1404 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1405 "channelMask 0x%X, flags %#x",
1406 device, samplingRate, format, channelMask, log_flags);
1407 return AUDIO_IO_HANDLE_NONE;
1408 }
Eric Laurente552edb2014-03-10 17:42:56 -07001409 }
1410
1411 if (profile->mModule->mHandle == 0) {
1412 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001413 return AUDIO_IO_HANDLE_NONE;
1414 }
1415
1416 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1417 config.sample_rate = samplingRate;
1418 config.channel_mask = channelMask;
1419 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001420
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001421 // handle legacy remote submix case where the address was not always specified
1422 String8 address = deviceDistinguishesOnAddress(device) ? String8("0") : String8("");
1423
Eric Laurentcf2c0212014-07-25 16:20:43 -07001424 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1425 &input,
1426 &config,
1427 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001428 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001429 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001430 flags);
1431
1432 // only accept input with the exact requested set of parameters
1433 if (status != NO_ERROR ||
1434 (samplingRate != config.sample_rate) ||
1435 (format != config.format) ||
1436 (channelMask != config.channel_mask)) {
1437 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1438 samplingRate, format, channelMask);
1439 if (input != AUDIO_IO_HANDLE_NONE) {
1440 mpClientInterface->closeInput(input);
1441 }
1442 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001443 }
1444
Eric Laurent1f2f2232014-06-02 12:01:23 -07001445 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001446 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001447 inputDesc->mRefCount = 0;
1448 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001449 inputDesc->mSamplingRate = samplingRate;
1450 inputDesc->mFormat = format;
1451 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001452 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001453 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001454 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001455
Eric Laurentd4692962014-05-05 18:13:44 -07001456 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001457 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001458 return input;
1459}
1460
Eric Laurent4dc68062014-07-28 17:26:49 -07001461status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1462 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001463{
1464 ALOGV("startInput() input %d", input);
1465 ssize_t index = mInputs.indexOfKey(input);
1466 if (index < 0) {
1467 ALOGW("startInput() unknown input %d", input);
1468 return BAD_VALUE;
1469 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001470 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001471
Eric Laurent4dc68062014-07-28 17:26:49 -07001472 index = inputDesc->mSessions.indexOf(session);
1473 if (index < 0) {
1474 ALOGW("startInput() unknown session %d on input %d", session, input);
1475 return BAD_VALUE;
1476 }
1477
Glenn Kasten74a8e252014-07-24 14:09:55 -07001478 // virtual input devices are compatible with other input devices
1479 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1480
1481 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001482 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001483 if (activeInput != 0 && activeInput != input) {
1484
1485 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1486 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001487 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001488 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001489 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001490 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1491 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001492 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001493 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001494 return INVALID_OPERATION;
1495 }
1496 }
1497 }
1498
Glenn Kasten74a8e252014-07-24 14:09:55 -07001499 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001500 if (activeInputsCount() == 0) {
1501 SoundTrigger::setCaptureState(true);
1502 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001503 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001504
Glenn Kasten74a8e252014-07-24 14:09:55 -07001505 // Automatically enable the remote submix output when input is started.
1506 // For remote submix (a virtual device), we open only one input per capture request.
1507 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1508 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1509 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1510 }
Eric Laurente552edb2014-03-10 17:42:56 -07001511 }
1512
Eric Laurente552edb2014-03-10 17:42:56 -07001513 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1514
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001515 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001516 return NO_ERROR;
1517}
1518
Eric Laurent4dc68062014-07-28 17:26:49 -07001519status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1520 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001521{
1522 ALOGV("stopInput() input %d", input);
1523 ssize_t index = mInputs.indexOfKey(input);
1524 if (index < 0) {
1525 ALOGW("stopInput() unknown input %d", input);
1526 return BAD_VALUE;
1527 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001528 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001529
Eric Laurent4dc68062014-07-28 17:26:49 -07001530 index = inputDesc->mSessions.indexOf(session);
1531 if (index < 0) {
1532 ALOGW("stopInput() unknown session %d on input %d", session, input);
1533 return BAD_VALUE;
1534 }
1535
Eric Laurente552edb2014-03-10 17:42:56 -07001536 if (inputDesc->mRefCount == 0) {
1537 ALOGW("stopInput() input %d already stopped", input);
1538 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001539 }
1540
1541 inputDesc->mRefCount--;
1542 if (inputDesc->mRefCount == 0) {
1543
Eric Laurente552edb2014-03-10 17:42:56 -07001544 // automatically disable the remote submix output when input is stopped
1545 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1546 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001547 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001548 }
1549
Eric Laurent1c333e22014-05-20 10:48:17 -07001550 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001551
1552 if (activeInputsCount() == 0) {
1553 SoundTrigger::setCaptureState(false);
1554 }
Eric Laurente552edb2014-03-10 17:42:56 -07001555 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001556 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001557}
1558
Eric Laurent4dc68062014-07-28 17:26:49 -07001559void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1560 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001561{
1562 ALOGV("releaseInput() %d", input);
1563 ssize_t index = mInputs.indexOfKey(input);
1564 if (index < 0) {
1565 ALOGW("releaseInput() releasing unknown input %d", input);
1566 return;
1567 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001568 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1569 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001570
1571 index = inputDesc->mSessions.indexOf(session);
1572 if (index < 0) {
1573 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1574 return;
1575 }
1576 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001577 if (inputDesc->mOpenRefCount == 0) {
1578 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1579 return;
1580 }
1581 inputDesc->mOpenRefCount--;
1582 if (inputDesc->mOpenRefCount > 0) {
1583 ALOGV("releaseInput() exit > 0");
1584 return;
1585 }
1586
Eric Laurent05b90f82014-08-27 15:32:29 -07001587 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001588 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001589 ALOGV("releaseInput() exit");
1590}
1591
Eric Laurentd4692962014-05-05 18:13:44 -07001592void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001593 bool patchRemoved = false;
1594
Eric Laurentd4692962014-05-05 18:13:44 -07001595 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001596 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1597 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1598 if (patch_index >= 0) {
1599 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1600 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1601 mAudioPatches.removeItemsAt(patch_index);
1602 patchRemoved = true;
1603 }
Eric Laurentd4692962014-05-05 18:13:44 -07001604 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1605 }
1606 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001607 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001608
1609 if (patchRemoved) {
1610 mpClientInterface->onAudioPatchListUpdate();
1611 }
Eric Laurentd4692962014-05-05 18:13:44 -07001612}
1613
Eric Laurente0720872014-03-11 09:30:41 -07001614void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001615 int indexMin,
1616 int indexMax)
1617{
1618 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1619 if (indexMin < 0 || indexMin >= indexMax) {
1620 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1621 return;
1622 }
1623 mStreams[stream].mIndexMin = indexMin;
1624 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001625 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1626 if (stream == AUDIO_STREAM_MUSIC) {
1627 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1628 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1629 }
Eric Laurente552edb2014-03-10 17:42:56 -07001630}
1631
Eric Laurente0720872014-03-11 09:30:41 -07001632status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001633 int index,
1634 audio_devices_t device)
1635{
1636
1637 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1638 return BAD_VALUE;
1639 }
1640 if (!audio_is_output_device(device)) {
1641 return BAD_VALUE;
1642 }
1643
1644 // Force max volume if stream cannot be muted
1645 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1646
1647 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1648 stream, device, index);
1649
1650 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1651 // clear all device specific values
1652 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1653 mStreams[stream].mIndexCur.clear();
1654 }
1655 mStreams[stream].mIndexCur.add(device, index);
1656
Eric Laurent31551f82014-10-10 18:21:56 -07001657 // update volume on all outputs whose current device is also selected by the same
1658 // strategy as the device specified by the caller
1659 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001660
1661
1662 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1663 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1664 if (stream == AUDIO_STREAM_MUSIC) {
1665 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1666 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1667 }
1668 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1669 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001670 return NO_ERROR;
1671 }
Eric Laurente552edb2014-03-10 17:42:56 -07001672 status_t status = NO_ERROR;
1673 for (size_t i = 0; i < mOutputs.size(); i++) {
1674 audio_devices_t curDevice =
1675 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001676 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001677 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1678 if (volStatus != NO_ERROR) {
1679 status = volStatus;
1680 }
1681 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001682 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1683 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1684 index, mOutputs.keyAt(i), curDevice);
1685 }
Eric Laurente552edb2014-03-10 17:42:56 -07001686 }
1687 return status;
1688}
1689
Eric Laurente0720872014-03-11 09:30:41 -07001690status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001691 int *index,
1692 audio_devices_t device)
1693{
1694 if (index == NULL) {
1695 return BAD_VALUE;
1696 }
1697 if (!audio_is_output_device(device)) {
1698 return BAD_VALUE;
1699 }
1700 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1701 // the strategy the stream belongs to.
1702 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1703 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1704 }
1705 device = getDeviceForVolume(device);
1706
1707 *index = mStreams[stream].getVolumeIndex(device);
1708 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1709 return NO_ERROR;
1710}
1711
Eric Laurente0720872014-03-11 09:30:41 -07001712audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001713 const SortedVector<audio_io_handle_t>& outputs)
1714{
1715 // select one output among several suitable for global effects.
1716 // The priority is as follows:
1717 // 1: An offloaded output. If the effect ends up not being offloadable,
1718 // AudioFlinger will invalidate the track and the offloaded output
1719 // will be closed causing the effect to be moved to a PCM output.
1720 // 2: A deep buffer output
1721 // 3: the first output in the list
1722
1723 if (outputs.size() == 0) {
1724 return 0;
1725 }
1726
1727 audio_io_handle_t outputOffloaded = 0;
1728 audio_io_handle_t outputDeepBuffer = 0;
1729
1730 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001731 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001732 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001733 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1734 outputOffloaded = outputs[i];
1735 }
1736 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1737 outputDeepBuffer = outputs[i];
1738 }
1739 }
1740
1741 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1742 outputOffloaded, outputDeepBuffer);
1743 if (outputOffloaded != 0) {
1744 return outputOffloaded;
1745 }
1746 if (outputDeepBuffer != 0) {
1747 return outputDeepBuffer;
1748 }
1749
1750 return outputs[0];
1751}
1752
Eric Laurente0720872014-03-11 09:30:41 -07001753audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001754{
1755 // apply simple rule where global effects are attached to the same output as MUSIC streams
1756
Eric Laurent3b73df72014-03-11 09:06:29 -07001757 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001758 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1759 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1760
1761 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1762 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1763 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1764
1765 return output;
1766}
1767
Eric Laurente0720872014-03-11 09:30:41 -07001768status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001769 audio_io_handle_t io,
1770 uint32_t strategy,
1771 int session,
1772 int id)
1773{
1774 ssize_t index = mOutputs.indexOfKey(io);
1775 if (index < 0) {
1776 index = mInputs.indexOfKey(io);
1777 if (index < 0) {
1778 ALOGW("registerEffect() unknown io %d", io);
1779 return INVALID_OPERATION;
1780 }
1781 }
1782
1783 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1784 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1785 desc->name, desc->memoryUsage);
1786 return INVALID_OPERATION;
1787 }
1788 mTotalEffectsMemory += desc->memoryUsage;
1789 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1790 desc->name, io, strategy, session, id);
1791 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1792
Eric Laurent1f2f2232014-06-02 12:01:23 -07001793 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1794 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1795 effectDesc->mIo = io;
1796 effectDesc->mStrategy = (routing_strategy)strategy;
1797 effectDesc->mSession = session;
1798 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001799
Eric Laurent1f2f2232014-06-02 12:01:23 -07001800 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001801
1802 return NO_ERROR;
1803}
1804
Eric Laurente0720872014-03-11 09:30:41 -07001805status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001806{
1807 ssize_t index = mEffects.indexOfKey(id);
1808 if (index < 0) {
1809 ALOGW("unregisterEffect() unknown effect ID %d", id);
1810 return INVALID_OPERATION;
1811 }
1812
Eric Laurent1f2f2232014-06-02 12:01:23 -07001813 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001814
Eric Laurent1f2f2232014-06-02 12:01:23 -07001815 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001816
Eric Laurent1f2f2232014-06-02 12:01:23 -07001817 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001818 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001819 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1820 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001821 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001822 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001823 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001824 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001825
1826 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001827
1828 return NO_ERROR;
1829}
1830
Eric Laurente0720872014-03-11 09:30:41 -07001831status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001832{
1833 ssize_t index = mEffects.indexOfKey(id);
1834 if (index < 0) {
1835 ALOGW("unregisterEffect() unknown effect ID %d", id);
1836 return INVALID_OPERATION;
1837 }
1838
1839 return setEffectEnabled(mEffects.valueAt(index), enabled);
1840}
1841
Eric Laurent1f2f2232014-06-02 12:01:23 -07001842status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001843{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001844 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001845 ALOGV("setEffectEnabled(%s) effect already %s",
1846 enabled?"true":"false", enabled?"enabled":"disabled");
1847 return INVALID_OPERATION;
1848 }
1849
1850 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001851 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001852 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001853 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001854 return INVALID_OPERATION;
1855 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001856 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001857 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1858 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001859 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001860 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001861 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1862 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001863 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001864 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001865 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1866 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001867 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001868 return NO_ERROR;
1869}
1870
Eric Laurente0720872014-03-11 09:30:41 -07001871bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001872{
1873 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001874 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1875 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1876 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001877 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001878 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001879 return true;
1880 }
1881 }
1882 return false;
1883}
1884
Eric Laurente0720872014-03-11 09:30:41 -07001885bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001886{
1887 nsecs_t sysTime = systemTime();
1888 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001889 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001890 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001891 return true;
1892 }
1893 }
1894 return false;
1895}
1896
Eric Laurente0720872014-03-11 09:30:41 -07001897bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001898 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001899{
1900 nsecs_t sysTime = systemTime();
1901 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001902 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001903 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001904 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001905 return true;
1906 }
1907 }
1908 return false;
1909}
1910
Eric Laurente0720872014-03-11 09:30:41 -07001911bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001912{
1913 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001914 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001915 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001916 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001917 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1918 && (inputDescriptor->mRefCount > 0)) {
1919 return true;
1920 }
1921 }
1922 return false;
1923}
1924
1925
Eric Laurente0720872014-03-11 09:30:41 -07001926status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001927{
1928 const size_t SIZE = 256;
1929 char buffer[SIZE];
1930 String8 result;
1931
1932 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1933 result.append(buffer);
1934
1935 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1936 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001937 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1938 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001939 snprintf(buffer, SIZE, " Force use for communications %d\n",
1940 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001941 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001942 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001943 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001944 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001945 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001946 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001947 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001948 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001949 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001950 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1951 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1952 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001953
Eric Laurent3a4311c2014-03-17 12:00:47 -07001954 snprintf(buffer, SIZE, " Available output devices:\n");
1955 result.append(buffer);
1956 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001957 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001958 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001959 }
1960 snprintf(buffer, SIZE, "\n Available input devices:\n");
1961 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001962 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001963 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001964 }
Eric Laurente552edb2014-03-10 17:42:56 -07001965
1966 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1967 write(fd, buffer, strlen(buffer));
1968 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001969 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001970 write(fd, buffer, strlen(buffer));
1971 mHwModules[i]->dump(fd);
1972 }
1973
1974 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1975 write(fd, buffer, strlen(buffer));
1976 for (size_t i = 0; i < mOutputs.size(); i++) {
1977 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1978 write(fd, buffer, strlen(buffer));
1979 mOutputs.valueAt(i)->dump(fd);
1980 }
1981
1982 snprintf(buffer, SIZE, "\nInputs dump:\n");
1983 write(fd, buffer, strlen(buffer));
1984 for (size_t i = 0; i < mInputs.size(); i++) {
1985 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1986 write(fd, buffer, strlen(buffer));
1987 mInputs.valueAt(i)->dump(fd);
1988 }
1989
1990 snprintf(buffer, SIZE, "\nStreams dump:\n");
1991 write(fd, buffer, strlen(buffer));
1992 snprintf(buffer, SIZE,
1993 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1994 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001995 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001996 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001997 write(fd, buffer, strlen(buffer));
1998 mStreams[i].dump(fd);
1999 }
2000
2001 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2002 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2003 write(fd, buffer, strlen(buffer));
2004
2005 snprintf(buffer, SIZE, "Registered effects:\n");
2006 write(fd, buffer, strlen(buffer));
2007 for (size_t i = 0; i < mEffects.size(); i++) {
2008 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2009 write(fd, buffer, strlen(buffer));
2010 mEffects.valueAt(i)->dump(fd);
2011 }
2012
Eric Laurent4d416952014-08-10 14:07:09 -07002013 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2014 write(fd, buffer, strlen(buffer));
2015 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2016 mAudioPatches[i]->dump(fd, 2, i);
2017 }
Eric Laurente552edb2014-03-10 17:42:56 -07002018
2019 return NO_ERROR;
2020}
2021
2022// This function checks for the parameters which can be offloaded.
2023// This can be enhanced depending on the capability of the DSP and policy
2024// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002025bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002026{
2027 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002028 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002029 offloadInfo.sample_rate, offloadInfo.channel_mask,
2030 offloadInfo.format,
2031 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2032 offloadInfo.has_video);
2033
2034 // Check if offload has been disabled
2035 char propValue[PROPERTY_VALUE_MAX];
2036 if (property_get("audio.offload.disable", propValue, "0")) {
2037 if (atoi(propValue) != 0) {
2038 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2039 return false;
2040 }
2041 }
2042
2043 // Check if stream type is music, then only allow offload as of now.
2044 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2045 {
2046 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2047 return false;
2048 }
2049
2050 //TODO: enable audio offloading with video when ready
2051 if (offloadInfo.has_video)
2052 {
2053 ALOGV("isOffloadSupported: has_video == true, returning false");
2054 return false;
2055 }
2056
2057 //If duration is less than minimum value defined in property, return false
2058 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2059 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2060 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2061 return false;
2062 }
2063 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2064 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2065 return false;
2066 }
2067
2068 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2069 // creating an offloaded track and tearing it down immediately after start when audioflinger
2070 // detects there is an active non offloadable effect.
2071 // FIXME: We should check the audio session here but we do not have it in this context.
2072 // This may prevent offloading in rare situations where effects are left active by apps
2073 // in the background.
2074 if (isNonOffloadableEffectEnabled()) {
2075 return false;
2076 }
2077
2078 // See if there is a profile to support this.
2079 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002080 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002081 offloadInfo.sample_rate,
2082 offloadInfo.format,
2083 offloadInfo.channel_mask,
2084 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002085 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2086 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002087}
2088
Eric Laurent6a94d692014-05-20 11:18:06 -07002089status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2090 audio_port_type_t type,
2091 unsigned int *num_ports,
2092 struct audio_port *ports,
2093 unsigned int *generation)
2094{
2095 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2096 generation == NULL) {
2097 return BAD_VALUE;
2098 }
2099 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2100 if (ports == NULL) {
2101 *num_ports = 0;
2102 }
2103
2104 size_t portsWritten = 0;
2105 size_t portsMax = *num_ports;
2106 *num_ports = 0;
2107 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2108 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2109 for (size_t i = 0;
2110 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2111 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2112 }
2113 *num_ports += mAvailableOutputDevices.size();
2114 }
2115 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2116 for (size_t i = 0;
2117 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2118 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2119 }
2120 *num_ports += mAvailableInputDevices.size();
2121 }
2122 }
2123 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2124 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2125 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2126 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2127 }
2128 *num_ports += mInputs.size();
2129 }
2130 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002131 size_t numOutputs = 0;
2132 for (size_t i = 0; i < mOutputs.size(); i++) {
2133 if (!mOutputs[i]->isDuplicated()) {
2134 numOutputs++;
2135 if (portsWritten < portsMax) {
2136 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2137 }
2138 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002139 }
Eric Laurent84c70242014-06-23 08:46:27 -07002140 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002141 }
2142 }
2143 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002144 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002145 return NO_ERROR;
2146}
2147
2148status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2149{
2150 return NO_ERROR;
2151}
2152
Eric Laurent1f2f2232014-06-02 12:01:23 -07002153sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002154 audio_port_handle_t id) const
2155{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002156 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002157 for (size_t i = 0; i < mOutputs.size(); i++) {
2158 outputDesc = mOutputs.valueAt(i);
2159 if (outputDesc->mId == id) {
2160 break;
2161 }
2162 }
2163 return outputDesc;
2164}
2165
Eric Laurent1f2f2232014-06-02 12:01:23 -07002166sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002167 audio_port_handle_t id) const
2168{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002169 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002170 for (size_t i = 0; i < mInputs.size(); i++) {
2171 inputDesc = mInputs.valueAt(i);
2172 if (inputDesc->mId == id) {
2173 break;
2174 }
2175 }
2176 return inputDesc;
2177}
2178
Eric Laurent1f2f2232014-06-02 12:01:23 -07002179sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2180 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002181{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002182 sp <HwModule> module;
2183
Eric Laurent6a94d692014-05-20 11:18:06 -07002184 for (size_t i = 0; i < mHwModules.size(); i++) {
2185 if (mHwModules[i]->mHandle == 0) {
2186 continue;
2187 }
2188 if (audio_is_output_device(device)) {
2189 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2190 {
2191 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2192 return mHwModules[i];
2193 }
2194 }
2195 } else {
2196 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2197 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2198 device & ~AUDIO_DEVICE_BIT_IN) {
2199 return mHwModules[i];
2200 }
2201 }
2202 }
2203 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002204 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002205}
2206
Eric Laurent1f2f2232014-06-02 12:01:23 -07002207sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002208{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002209 sp <HwModule> module;
2210
Eric Laurent1afeecb2014-05-14 08:52:28 -07002211 for (size_t i = 0; i < mHwModules.size(); i++)
2212 {
2213 if (strcmp(mHwModules[i]->mName, name) == 0) {
2214 return mHwModules[i];
2215 }
2216 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002217 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002218}
2219
Eric Laurentc2730ba2014-07-20 15:47:07 -07002220audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2221{
2222 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2223 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2224 return devices & mAvailableOutputDevices.types();
2225}
2226
2227audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2228{
2229 audio_module_handle_t primaryHandle =
2230 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2231 audio_devices_t devices = AUDIO_DEVICE_NONE;
2232 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2233 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2234 devices |= mAvailableInputDevices[i]->mDeviceType;
2235 }
2236 }
2237 return devices;
2238}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002239
Eric Laurent6a94d692014-05-20 11:18:06 -07002240status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2241 audio_patch_handle_t *handle,
2242 uid_t uid)
2243{
2244 ALOGV("createAudioPatch()");
2245
2246 if (handle == NULL || patch == NULL) {
2247 return BAD_VALUE;
2248 }
2249 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2250
Eric Laurent874c42872014-08-08 15:13:39 -07002251 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2252 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2253 return BAD_VALUE;
2254 }
2255 // only one source per audio patch supported for now
2256 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002257 return INVALID_OPERATION;
2258 }
Eric Laurent874c42872014-08-08 15:13:39 -07002259
2260 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002261 return INVALID_OPERATION;
2262 }
Eric Laurent874c42872014-08-08 15:13:39 -07002263 for (size_t i = 0; i < patch->num_sinks; i++) {
2264 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2265 return INVALID_OPERATION;
2266 }
2267 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002268
2269 sp<AudioPatch> patchDesc;
2270 ssize_t index = mAudioPatches.indexOfKey(*handle);
2271
Eric Laurent6a94d692014-05-20 11:18:06 -07002272 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2273 patch->sources[0].role,
2274 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002275#if LOG_NDEBUG == 0
2276 for (size_t i = 0; i < patch->num_sinks; i++) {
2277 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2278 patch->sinks[i].role,
2279 patch->sinks[i].type);
2280 }
2281#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002282
2283 if (index >= 0) {
2284 patchDesc = mAudioPatches.valueAt(index);
2285 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2286 mUidCached, patchDesc->mUid, uid);
2287 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2288 return INVALID_OPERATION;
2289 }
2290 } else {
2291 *handle = 0;
2292 }
2293
2294 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002295 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002296 if (outputDesc == NULL) {
2297 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2298 return BAD_VALUE;
2299 }
Eric Laurent84c70242014-06-23 08:46:27 -07002300 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2301 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002302 if (patchDesc != 0) {
2303 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2304 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2305 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2306 return BAD_VALUE;
2307 }
2308 }
Eric Laurent874c42872014-08-08 15:13:39 -07002309 DeviceVector devices;
2310 for (size_t i = 0; i < patch->num_sinks; i++) {
2311 // Only support mix to devices connection
2312 // TODO add support for mix to mix connection
2313 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2314 ALOGV("createAudioPatch() source mix but sink is not a device");
2315 return INVALID_OPERATION;
2316 }
2317 sp<DeviceDescriptor> devDesc =
2318 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2319 if (devDesc == 0) {
2320 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2321 return BAD_VALUE;
2322 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002323
Eric Laurent874c42872014-08-08 15:13:39 -07002324 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2325 patch->sources[0].sample_rate,
2326 NULL, // updatedSamplingRate
2327 patch->sources[0].format,
2328 patch->sources[0].channel_mask,
2329 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2330 ALOGV("createAudioPatch() profile not supported for device %08x",
2331 devDesc->mDeviceType);
2332 return INVALID_OPERATION;
2333 }
2334 devices.add(devDesc);
2335 }
2336 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002337 return INVALID_OPERATION;
2338 }
Eric Laurent874c42872014-08-08 15:13:39 -07002339
Eric Laurent6a94d692014-05-20 11:18:06 -07002340 // TODO: reconfigure output format and channels here
2341 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002342 devices.types(), outputDesc->mIoHandle);
2343 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002344 index = mAudioPatches.indexOfKey(*handle);
2345 if (index >= 0) {
2346 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2347 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2348 }
2349 patchDesc = mAudioPatches.valueAt(index);
2350 patchDesc->mUid = uid;
2351 ALOGV("createAudioPatch() success");
2352 } else {
2353 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2354 return INVALID_OPERATION;
2355 }
2356 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2357 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2358 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002359 // only one sink supported when connecting an input device to a mix
2360 if (patch->num_sinks > 1) {
2361 return INVALID_OPERATION;
2362 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002363 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002364 if (inputDesc == NULL) {
2365 return BAD_VALUE;
2366 }
2367 if (patchDesc != 0) {
2368 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2369 return BAD_VALUE;
2370 }
2371 }
2372 sp<DeviceDescriptor> devDesc =
2373 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2374 if (devDesc == 0) {
2375 return BAD_VALUE;
2376 }
2377
Eric Laurent84c70242014-06-23 08:46:27 -07002378 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002379 patch->sinks[0].sample_rate,
2380 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002381 patch->sinks[0].format,
2382 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002383 // FIXME for the parameter type,
2384 // and the NONE
2385 (audio_output_flags_t)
2386 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002387 return INVALID_OPERATION;
2388 }
2389 // TODO: reconfigure output format and channels here
2390 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002391 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002392 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002393 index = mAudioPatches.indexOfKey(*handle);
2394 if (index >= 0) {
2395 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2396 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2397 }
2398 patchDesc = mAudioPatches.valueAt(index);
2399 patchDesc->mUid = uid;
2400 ALOGV("createAudioPatch() success");
2401 } else {
2402 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2403 return INVALID_OPERATION;
2404 }
2405 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2406 // device to device connection
2407 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002408 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002409 return BAD_VALUE;
2410 }
2411 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002412 sp<DeviceDescriptor> srcDeviceDesc =
2413 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002414 if (srcDeviceDesc == 0) {
2415 return BAD_VALUE;
2416 }
Eric Laurent874c42872014-08-08 15:13:39 -07002417
Eric Laurent6a94d692014-05-20 11:18:06 -07002418 //update source and sink with our own data as the data passed in the patch may
2419 // be incomplete.
2420 struct audio_patch newPatch = *patch;
2421 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002422
Eric Laurent874c42872014-08-08 15:13:39 -07002423 for (size_t i = 0; i < patch->num_sinks; i++) {
2424 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2425 ALOGV("createAudioPatch() source device but one sink is not a device");
2426 return INVALID_OPERATION;
2427 }
2428
2429 sp<DeviceDescriptor> sinkDeviceDesc =
2430 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2431 if (sinkDeviceDesc == 0) {
2432 return BAD_VALUE;
2433 }
2434 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2435
2436 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2437 // only one sink supported when connected devices across HW modules
2438 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002439 return INVALID_OPERATION;
2440 }
Eric Laurent874c42872014-08-08 15:13:39 -07002441 SortedVector<audio_io_handle_t> outputs =
2442 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2443 mOutputs);
2444 // if the sink device is reachable via an opened output stream, request to go via
2445 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002446 audio_io_handle_t output = selectOutput(outputs,
2447 AUDIO_OUTPUT_FLAG_NONE,
2448 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002449 if (output != AUDIO_IO_HANDLE_NONE) {
2450 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2451 if (outputDesc->isDuplicated()) {
2452 return INVALID_OPERATION;
2453 }
2454 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2455 newPatch.num_sources = 2;
2456 }
Eric Laurent83b88082014-06-20 18:31:16 -07002457 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002458 }
2459 // TODO: check from routing capabilities in config file and other conflicting patches
2460
2461 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2462 if (index >= 0) {
2463 afPatchHandle = patchDesc->mAfPatchHandle;
2464 }
2465
2466 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2467 &afPatchHandle,
2468 0);
2469 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2470 status, afPatchHandle);
2471 if (status == NO_ERROR) {
2472 if (index < 0) {
2473 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2474 &newPatch, uid);
2475 addAudioPatch(patchDesc->mHandle, patchDesc);
2476 } else {
2477 patchDesc->mPatch = newPatch;
2478 }
2479 patchDesc->mAfPatchHandle = afPatchHandle;
2480 *handle = patchDesc->mHandle;
2481 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002482 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002483 } else {
2484 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2485 status);
2486 return INVALID_OPERATION;
2487 }
2488 } else {
2489 return BAD_VALUE;
2490 }
2491 } else {
2492 return BAD_VALUE;
2493 }
2494 return NO_ERROR;
2495}
2496
2497status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2498 uid_t uid)
2499{
2500 ALOGV("releaseAudioPatch() patch %d", handle);
2501
2502 ssize_t index = mAudioPatches.indexOfKey(handle);
2503
2504 if (index < 0) {
2505 return BAD_VALUE;
2506 }
2507 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2508 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2509 mUidCached, patchDesc->mUid, uid);
2510 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2511 return INVALID_OPERATION;
2512 }
2513
2514 struct audio_patch *patch = &patchDesc->mPatch;
2515 patchDesc->mUid = mUidCached;
2516 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002517 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002518 if (outputDesc == NULL) {
2519 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2520 return BAD_VALUE;
2521 }
2522
2523 setOutputDevice(outputDesc->mIoHandle,
2524 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2525 true,
2526 0,
2527 NULL);
2528 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2529 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002530 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002531 if (inputDesc == NULL) {
2532 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2533 return BAD_VALUE;
2534 }
2535 setInputDevice(inputDesc->mIoHandle,
2536 getNewInputDevice(inputDesc->mIoHandle),
2537 true,
2538 NULL);
2539 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2540 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2541 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2542 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2543 status, patchDesc->mAfPatchHandle);
2544 removeAudioPatch(patchDesc->mHandle);
2545 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002546 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002547 } else {
2548 return BAD_VALUE;
2549 }
2550 } else {
2551 return BAD_VALUE;
2552 }
2553 return NO_ERROR;
2554}
2555
2556status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2557 struct audio_patch *patches,
2558 unsigned int *generation)
2559{
2560 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2561 generation == NULL) {
2562 return BAD_VALUE;
2563 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002564 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002565 *num_patches, patches, mAudioPatches.size());
2566 if (patches == NULL) {
2567 *num_patches = 0;
2568 }
2569
2570 size_t patchesWritten = 0;
2571 size_t patchesMax = *num_patches;
2572 for (size_t i = 0;
2573 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2574 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2575 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002576 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002577 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2578 }
2579 *num_patches = mAudioPatches.size();
2580
2581 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002582 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002583 return NO_ERROR;
2584}
2585
Eric Laurente1715a42014-05-20 11:30:42 -07002586status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002587{
Eric Laurente1715a42014-05-20 11:30:42 -07002588 ALOGV("setAudioPortConfig()");
2589
2590 if (config == NULL) {
2591 return BAD_VALUE;
2592 }
2593 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2594 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002595 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2596 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002597 }
2598
Eric Laurenta121f902014-06-03 13:32:54 -07002599 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002600 if (config->type == AUDIO_PORT_TYPE_MIX) {
2601 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002602 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002603 if (outputDesc == NULL) {
2604 return BAD_VALUE;
2605 }
Eric Laurent84c70242014-06-23 08:46:27 -07002606 ALOG_ASSERT(!outputDesc->isDuplicated(),
2607 "setAudioPortConfig() called on duplicated output %d",
2608 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002609 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002610 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002611 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002612 if (inputDesc == NULL) {
2613 return BAD_VALUE;
2614 }
Eric Laurenta121f902014-06-03 13:32:54 -07002615 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002616 } else {
2617 return BAD_VALUE;
2618 }
2619 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2620 sp<DeviceDescriptor> deviceDesc;
2621 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2622 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2623 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2624 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2625 } else {
2626 return BAD_VALUE;
2627 }
2628 if (deviceDesc == NULL) {
2629 return BAD_VALUE;
2630 }
Eric Laurenta121f902014-06-03 13:32:54 -07002631 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002632 } else {
2633 return BAD_VALUE;
2634 }
2635
Eric Laurenta121f902014-06-03 13:32:54 -07002636 struct audio_port_config backupConfig;
2637 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2638 if (status == NO_ERROR) {
2639 struct audio_port_config newConfig;
2640 audioPortConfig->toAudioPortConfig(&newConfig, config);
2641 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002642 }
Eric Laurenta121f902014-06-03 13:32:54 -07002643 if (status != NO_ERROR) {
2644 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002645 }
Eric Laurente1715a42014-05-20 11:30:42 -07002646
2647 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002648}
2649
2650void AudioPolicyManager::clearAudioPatches(uid_t uid)
2651{
2652 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2653 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2654 if (patchDesc->mUid == uid) {
2655 // releaseAudioPatch() removes the patch from mAudioPatches
2656 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2657 i--;
2658 }
2659 }
2660 }
2661}
2662
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002663status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2664 audio_io_handle_t *ioHandle,
2665 audio_devices_t *device)
2666{
2667 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2668 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2669 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2670
2671 mSoundTriggerSessions.add(*session, *ioHandle);
2672
2673 return NO_ERROR;
2674}
2675
2676status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2677{
2678 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2679 if (index < 0) {
2680 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2681 return BAD_VALUE;
2682 }
2683
2684 mSoundTriggerSessions.removeItem(session);
2685 return NO_ERROR;
2686}
2687
Eric Laurent6a94d692014-05-20 11:18:06 -07002688status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2689 const sp<AudioPatch>& patch)
2690{
2691 ssize_t index = mAudioPatches.indexOfKey(handle);
2692
2693 if (index >= 0) {
2694 ALOGW("addAudioPatch() patch %d already in", handle);
2695 return ALREADY_EXISTS;
2696 }
2697 mAudioPatches.add(handle, patch);
2698 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2699 "sink handle %d",
2700 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2701 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2702 return NO_ERROR;
2703}
2704
2705status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2706{
2707 ssize_t index = mAudioPatches.indexOfKey(handle);
2708
2709 if (index < 0) {
2710 ALOGW("removeAudioPatch() patch %d not in", handle);
2711 return ALREADY_EXISTS;
2712 }
2713 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2714 mAudioPatches.valueAt(index)->mAfPatchHandle);
2715 mAudioPatches.removeItemsAt(index);
2716 return NO_ERROR;
2717}
2718
Eric Laurente552edb2014-03-10 17:42:56 -07002719// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002720// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002721// ----------------------------------------------------------------------------
2722
Eric Laurent3a4311c2014-03-17 12:00:47 -07002723uint32_t AudioPolicyManager::nextUniqueId()
2724{
2725 return android_atomic_inc(&mNextUniqueId);
2726}
2727
Eric Laurent6a94d692014-05-20 11:18:06 -07002728uint32_t AudioPolicyManager::nextAudioPortGeneration()
2729{
2730 return android_atomic_inc(&mAudioPortGeneration);
2731}
2732
Eric Laurente0720872014-03-11 09:30:41 -07002733AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002734 :
2735#ifdef AUDIO_POLICY_TEST
2736 Thread(false),
2737#endif //AUDIO_POLICY_TEST
2738 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002739 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002740 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2741 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002742 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002743 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002744 mAudioPortGeneration(1),
2745 mBeaconMuteRefCount(0),
2746 mBeaconPlayingRefCount(0),
2747 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002748{
Eric Laurent6a94d692014-05-20 11:18:06 -07002749 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002750 mpClientInterface = clientInterface;
2751
Eric Laurent3b73df72014-03-11 09:06:29 -07002752 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2753 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002754 }
2755
Eric Laurent1afeecb2014-05-14 08:52:28 -07002756 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002757 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2758 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2759 ALOGE("could not load audio policy configuration file, setting defaults");
2760 defaultAudioPolicyConfig();
2761 }
2762 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002763 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002764
2765 // must be done after reading the policy
2766 initializeVolumeCurves();
2767
2768 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002769 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2770 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002771 for (size_t i = 0; i < mHwModules.size(); i++) {
2772 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2773 if (mHwModules[i]->mHandle == 0) {
2774 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2775 continue;
2776 }
2777 // open all output streams needed to access attached devices
2778 // except for direct output streams that are only opened when they are actually
2779 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002780 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002781 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2782 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002783 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002784
Eric Laurent3a4311c2014-03-17 12:00:47 -07002785 if (outProfile->mSupportedDevices.isEmpty()) {
2786 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2787 continue;
2788 }
2789
Eric Laurentd78f1532014-09-16 16:38:20 -07002790 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2791 continue;
2792 }
Eric Laurent83b88082014-06-20 18:31:16 -07002793 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2794 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2795 profileType = mDefaultOutputDevice->mDeviceType;
2796 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002797 // chose first device present in mSupportedDevices also part of
2798 // outputDeviceTypes
2799 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2800 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2801 if ((profileType & outputDeviceTypes) != 0) {
2802 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002803 }
Eric Laurente552edb2014-03-10 17:42:56 -07002804 }
2805 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002806 if ((profileType & outputDeviceTypes) == 0) {
2807 continue;
2808 }
2809 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2810
2811 outputDesc->mDevice = profileType;
2812 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2813 config.sample_rate = outputDesc->mSamplingRate;
2814 config.channel_mask = outputDesc->mChannelMask;
2815 config.format = outputDesc->mFormat;
2816 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2817 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2818 &output,
2819 &config,
2820 &outputDesc->mDevice,
2821 String8(""),
2822 &outputDesc->mLatency,
2823 outputDesc->mFlags);
2824
2825 if (status != NO_ERROR) {
2826 ALOGW("Cannot open output stream for device %08x on hw module %s",
2827 outputDesc->mDevice,
2828 mHwModules[i]->mName);
2829 } else {
2830 outputDesc->mSamplingRate = config.sample_rate;
2831 outputDesc->mChannelMask = config.channel_mask;
2832 outputDesc->mFormat = config.format;
2833
2834 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2835 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2836 ssize_t index =
2837 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2838 // give a valid ID to an attached device once confirmed it is reachable
2839 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2840 mAvailableOutputDevices[index]->mId = nextUniqueId();
2841 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2842 }
2843 }
2844 if (mPrimaryOutput == 0 &&
2845 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2846 mPrimaryOutput = output;
2847 }
2848 addOutput(output, outputDesc);
2849 setOutputDevice(output,
2850 outputDesc->mDevice,
2851 true);
2852 }
Eric Laurente552edb2014-03-10 17:42:56 -07002853 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002854 // open input streams needed to access attached devices to validate
2855 // mAvailableInputDevices list
2856 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2857 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002858 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002859
Eric Laurent3a4311c2014-03-17 12:00:47 -07002860 if (inProfile->mSupportedDevices.isEmpty()) {
2861 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2862 continue;
2863 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002864 // chose first device present in mSupportedDevices also part of
2865 // inputDeviceTypes
2866 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2867 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2868 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2869 if (profileType & inputDeviceTypes) {
2870 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002871 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002872 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002873 if ((profileType & inputDeviceTypes) == 0) {
2874 continue;
2875 }
2876 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2877
2878 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2879 inputDesc->mDevice = profileType;
2880
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002881 // find the address
2882 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
2883 // the inputs vector must be of size 1, but we don't want to crash here
2884 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
2885 : String8("");
2886 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
2887 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
2888
Eric Laurentd78f1532014-09-16 16:38:20 -07002889 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2890 config.sample_rate = inputDesc->mSamplingRate;
2891 config.channel_mask = inputDesc->mChannelMask;
2892 config.format = inputDesc->mFormat;
2893 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2894 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2895 &input,
2896 &config,
2897 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002898 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07002899 AUDIO_SOURCE_MIC,
2900 AUDIO_INPUT_FLAG_NONE);
2901
2902 if (status == NO_ERROR) {
2903 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2904 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2905 ssize_t index =
2906 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2907 // give a valid ID to an attached device once confirmed it is reachable
2908 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2909 mAvailableInputDevices[index]->mId = nextUniqueId();
2910 mAvailableInputDevices[index]->mModule = mHwModules[i];
2911 }
2912 }
2913 mpClientInterface->closeInput(input);
2914 } else {
2915 ALOGW("Cannot open input stream for device %08x on hw module %s",
2916 inputDesc->mDevice,
2917 mHwModules[i]->mName);
2918 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002919 }
2920 }
2921 // make sure all attached devices have been allocated a unique ID
2922 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2923 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002924 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002925 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2926 continue;
2927 }
2928 i++;
2929 }
2930 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2931 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002932 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002933 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2934 continue;
2935 }
2936 i++;
2937 }
2938 // make sure default device is reachable
2939 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002940 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002941 }
Eric Laurente552edb2014-03-10 17:42:56 -07002942
2943 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2944
2945 updateDevicesAndOutputs();
2946
2947#ifdef AUDIO_POLICY_TEST
2948 if (mPrimaryOutput != 0) {
2949 AudioParameter outputCmd = AudioParameter();
2950 outputCmd.addInt(String8("set_id"), 0);
2951 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2952
2953 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2954 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002955 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2956 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002957 mTestLatencyMs = 0;
2958 mCurOutput = 0;
2959 mDirectOutput = false;
2960 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2961 mTestOutputs[i] = 0;
2962 }
2963
2964 const size_t SIZE = 256;
2965 char buffer[SIZE];
2966 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2967 run(buffer, ANDROID_PRIORITY_AUDIO);
2968 }
2969#endif //AUDIO_POLICY_TEST
2970}
2971
Eric Laurente0720872014-03-11 09:30:41 -07002972AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002973{
2974#ifdef AUDIO_POLICY_TEST
2975 exit();
2976#endif //AUDIO_POLICY_TEST
2977 for (size_t i = 0; i < mOutputs.size(); i++) {
2978 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002979 }
2980 for (size_t i = 0; i < mInputs.size(); i++) {
2981 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002982 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002983 mAvailableOutputDevices.clear();
2984 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002985 mOutputs.clear();
2986 mInputs.clear();
2987 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002988}
2989
Eric Laurente0720872014-03-11 09:30:41 -07002990status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002991{
2992 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2993}
2994
2995#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002996bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002997{
2998 ALOGV("entering threadLoop()");
2999 while (!exitPending())
3000 {
3001 String8 command;
3002 int valueInt;
3003 String8 value;
3004
3005 Mutex::Autolock _l(mLock);
3006 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3007
3008 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3009 AudioParameter param = AudioParameter(command);
3010
3011 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3012 valueInt != 0) {
3013 ALOGV("Test command %s received", command.string());
3014 String8 target;
3015 if (param.get(String8("target"), target) != NO_ERROR) {
3016 target = "Manager";
3017 }
3018 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3019 param.remove(String8("test_cmd_policy_output"));
3020 mCurOutput = valueInt;
3021 }
3022 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3023 param.remove(String8("test_cmd_policy_direct"));
3024 if (value == "false") {
3025 mDirectOutput = false;
3026 } else if (value == "true") {
3027 mDirectOutput = true;
3028 }
3029 }
3030 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3031 param.remove(String8("test_cmd_policy_input"));
3032 mTestInput = valueInt;
3033 }
3034
3035 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3036 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003037 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003038 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003039 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003040 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003041 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003042 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003043 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003044 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003045 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003046 if (target == "Manager") {
3047 mTestFormat = format;
3048 } else if (mTestOutputs[mCurOutput] != 0) {
3049 AudioParameter outputParam = AudioParameter();
3050 outputParam.addInt(String8("format"), format);
3051 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3052 }
3053 }
3054 }
3055 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3056 param.remove(String8("test_cmd_policy_channels"));
3057 int channels = 0;
3058
3059 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003060 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003061 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003062 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003063 }
3064 if (channels != 0) {
3065 if (target == "Manager") {
3066 mTestChannels = channels;
3067 } else if (mTestOutputs[mCurOutput] != 0) {
3068 AudioParameter outputParam = AudioParameter();
3069 outputParam.addInt(String8("channels"), channels);
3070 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3071 }
3072 }
3073 }
3074 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3075 param.remove(String8("test_cmd_policy_sampleRate"));
3076 if (valueInt >= 0 && valueInt <= 96000) {
3077 int samplingRate = valueInt;
3078 if (target == "Manager") {
3079 mTestSamplingRate = samplingRate;
3080 } else if (mTestOutputs[mCurOutput] != 0) {
3081 AudioParameter outputParam = AudioParameter();
3082 outputParam.addInt(String8("sampling_rate"), samplingRate);
3083 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3084 }
3085 }
3086 }
3087
3088 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3089 param.remove(String8("test_cmd_policy_reopen"));
3090
Eric Laurent1f2f2232014-06-02 12:01:23 -07003091 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003092 mpClientInterface->closeOutput(mPrimaryOutput);
3093
3094 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3095
Eric Laurente552edb2014-03-10 17:42:56 -07003096 mOutputs.removeItem(mPrimaryOutput);
3097
Eric Laurent1f2f2232014-06-02 12:01:23 -07003098 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003099 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003100 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3101 config.sample_rate = outputDesc->mSamplingRate;
3102 config.channel_mask = outputDesc->mChannelMask;
3103 config.format = outputDesc->mFormat;
3104 status_t status = mpClientInterface->openOutput(moduleHandle,
3105 &mPrimaryOutput,
3106 &config,
3107 &outputDesc->mDevice,
3108 String8(""),
3109 &outputDesc->mLatency,
3110 outputDesc->mFlags);
3111 if (status != NO_ERROR) {
3112 ALOGE("Failed to reopen hardware output stream, "
3113 "samplingRate: %d, format %d, channels %d",
3114 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003115 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003116 outputDesc->mSamplingRate = config.sample_rate;
3117 outputDesc->mChannelMask = config.channel_mask;
3118 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003119 AudioParameter outputCmd = AudioParameter();
3120 outputCmd.addInt(String8("set_id"), 0);
3121 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3122 addOutput(mPrimaryOutput, outputDesc);
3123 }
3124 }
3125
3126
3127 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3128 }
3129 }
3130 return false;
3131}
3132
Eric Laurente0720872014-03-11 09:30:41 -07003133void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003134{
3135 {
3136 AutoMutex _l(mLock);
3137 requestExit();
3138 mWaitWorkCV.signal();
3139 }
3140 requestExitAndWait();
3141}
3142
Eric Laurente0720872014-03-11 09:30:41 -07003143int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003144{
3145 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3146 if (output == mTestOutputs[i]) return i;
3147 }
3148 return 0;
3149}
3150#endif //AUDIO_POLICY_TEST
3151
3152// ---
3153
Eric Laurent1f2f2232014-06-02 12:01:23 -07003154void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003155{
Eric Laurent1c333e22014-05-20 10:48:17 -07003156 outputDesc->mIoHandle = output;
3157 outputDesc->mId = nextUniqueId();
3158 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003159 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003160}
3161
Eric Laurent1f2f2232014-06-02 12:01:23 -07003162void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003163{
Eric Laurent1c333e22014-05-20 10:48:17 -07003164 inputDesc->mIoHandle = input;
3165 inputDesc->mId = nextUniqueId();
3166 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003167 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003168}
Eric Laurente552edb2014-03-10 17:42:56 -07003169
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003170void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3171 const String8 address /*in*/,
3172 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3173 // look for a match on the given address on the addresses of the outputs:
3174 // find the address by finding the patch that maps to this output
3175 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3176 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3177 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3178 if (patchIdx >= 0) {
3179 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3180 const int numSinks = patchDesc->mPatch.num_sinks;
3181 for (ssize_t j=0; j < numSinks; j++) {
3182 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3183 const char* patchAddr =
3184 patchDesc->mPatch.sinks[j].ext.device.address;
3185 if (strncmp(patchAddr,
3186 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003187 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003188 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3189 outputs.add(desc->mIoHandle);
3190 break;
3191 }
3192 }
3193 }
3194 }
3195}
3196
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003197status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003198 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003199 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003200 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003201{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003202 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003203 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003204 // erase all current sample rates, formats and channel masks
3205 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003206
Eric Laurent3b73df72014-03-11 09:06:29 -07003207 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003208 // first list already open outputs that can be routed to this device
3209 for (size_t i = 0; i < mOutputs.size(); i++) {
3210 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003211 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003212 if (!deviceDistinguishesOnAddress(device)) {
3213 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3214 outputs.add(mOutputs.keyAt(i));
3215 } else {
3216 ALOGV(" checking address match due to device 0x%x", device);
3217 findIoHandlesByAddress(desc, address, outputs);
3218 }
Eric Laurente552edb2014-03-10 17:42:56 -07003219 }
3220 }
3221 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003222 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003223 for (size_t i = 0; i < mHwModules.size(); i++)
3224 {
3225 if (mHwModules[i]->mHandle == 0) {
3226 continue;
3227 }
3228 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3229 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003230 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003231 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003232 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3233 }
3234 }
3235 }
3236
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003237 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3238
Eric Laurente552edb2014-03-10 17:42:56 -07003239 if (profiles.isEmpty() && outputs.isEmpty()) {
3240 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3241 return BAD_VALUE;
3242 }
3243
3244 // open outputs for matching profiles if needed. Direct outputs are also opened to
3245 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3246 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003247 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003248
3249 // nothing to do if one output is already opened for this profile
3250 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003251 for (j = 0; j < outputs.size(); j++) {
3252 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003253 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003254 // matching profile: save the sample rates, format and channel masks supported
3255 // by the profile in our device descriptor
3256 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003257 break;
3258 }
3259 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003260 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003261 continue;
3262 }
3263
Eric Laurent83b88082014-06-20 18:31:16 -07003264 ALOGV("opening output for device %08x with params %s profile %p",
3265 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003266 desc = new AudioOutputDescriptor(profile);
3267 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003268 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3269 config.sample_rate = desc->mSamplingRate;
3270 config.channel_mask = desc->mChannelMask;
3271 config.format = desc->mFormat;
3272 config.offload_info.sample_rate = desc->mSamplingRate;
3273 config.offload_info.channel_mask = desc->mChannelMask;
3274 config.offload_info.format = desc->mFormat;
3275 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3276 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3277 &output,
3278 &config,
3279 &desc->mDevice,
3280 address,
3281 &desc->mLatency,
3282 desc->mFlags);
3283 if (status == NO_ERROR) {
3284 desc->mSamplingRate = config.sample_rate;
3285 desc->mChannelMask = config.channel_mask;
3286 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003287
Eric Laurentd4692962014-05-05 18:13:44 -07003288 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003289 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003290 char *param = audio_device_address_to_parameter(device, address);
3291 mpClientInterface->setParameters(output, String8(param));
3292 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003293 }
3294
Eric Laurentd4692962014-05-05 18:13:44 -07003295 // Here is where we step through and resolve any "dynamic" fields
3296 String8 reply;
3297 char *value;
3298 if (profile->mSamplingRates[0] == 0) {
3299 reply = mpClientInterface->getParameters(output,
3300 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003301 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003302 reply.string());
3303 value = strpbrk((char *)reply.string(), "=");
3304 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003305 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003306 }
Eric Laurentd4692962014-05-05 18:13:44 -07003307 }
3308 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3309 reply = mpClientInterface->getParameters(output,
3310 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003311 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003312 reply.string());
3313 value = strpbrk((char *)reply.string(), "=");
3314 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003315 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003316 }
Eric Laurentd4692962014-05-05 18:13:44 -07003317 }
3318 if (profile->mChannelMasks[0] == 0) {
3319 reply = mpClientInterface->getParameters(output,
3320 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003321 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003322 reply.string());
3323 value = strpbrk((char *)reply.string(), "=");
3324 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003325 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003326 }
Eric Laurentd4692962014-05-05 18:13:44 -07003327 }
3328 if (((profile->mSamplingRates[0] == 0) &&
3329 (profile->mSamplingRates.size() < 2)) ||
3330 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3331 (profile->mFormats.size() < 2)) ||
3332 ((profile->mChannelMasks[0] == 0) &&
3333 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003334 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003335 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003336 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003337 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3338 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003339 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003340 config.sample_rate = profile->pickSamplingRate();
3341 config.channel_mask = profile->pickChannelMask();
3342 config.format = profile->pickFormat();
3343 config.offload_info.sample_rate = config.sample_rate;
3344 config.offload_info.channel_mask = config.channel_mask;
3345 config.offload_info.format = config.format;
3346 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3347 &output,
3348 &config,
3349 &desc->mDevice,
3350 address,
3351 &desc->mLatency,
3352 desc->mFlags);
3353 if (status == NO_ERROR) {
3354 desc->mSamplingRate = config.sample_rate;
3355 desc->mChannelMask = config.channel_mask;
3356 desc->mFormat = config.format;
3357 } else {
3358 output = AUDIO_IO_HANDLE_NONE;
3359 }
Eric Laurentd4692962014-05-05 18:13:44 -07003360 }
3361
Eric Laurentcf2c0212014-07-25 16:20:43 -07003362 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003363 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003364 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003365 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003366
Eric Laurentd4692962014-05-05 18:13:44 -07003367 // set initial stream volume for device
3368 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003369
Eric Laurentd4692962014-05-05 18:13:44 -07003370 //TODO: configure audio effect output stage here
3371
3372 // open a duplicating output thread for the new output and the primary output
3373 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3374 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003375 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003376 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003377 sp<AudioOutputDescriptor> dupOutputDesc =
3378 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003379 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3380 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3381 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3382 dupOutputDesc->mFormat = desc->mFormat;
3383 dupOutputDesc->mChannelMask = desc->mChannelMask;
3384 dupOutputDesc->mLatency = desc->mLatency;
3385 addOutput(duplicatedOutput, dupOutputDesc);
3386 applyStreamVolumes(duplicatedOutput, device, 0, true);
3387 } else {
3388 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3389 mPrimaryOutput, output);
3390 mpClientInterface->closeOutput(output);
3391 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003392 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003393 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003394 }
Eric Laurente552edb2014-03-10 17:42:56 -07003395 }
3396 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003397 } else {
3398 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003399 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003400 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003401 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003402 profiles.removeAt(profile_index);
3403 profile_index--;
3404 } else {
3405 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003406 devDesc->importAudioPort(profile);
3407
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003408 if (deviceDistinguishesOnAddress(device)) {
3409 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3410 device, address.string());
3411 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3412 NULL/*patch handle*/, address.string());
3413 }
Eric Laurente552edb2014-03-10 17:42:56 -07003414 ALOGV("checkOutputsForDevice(): adding output %d", output);
3415 }
3416 }
3417
3418 if (profiles.isEmpty()) {
3419 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3420 return BAD_VALUE;
3421 }
Eric Laurentd4692962014-05-05 18:13:44 -07003422 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003423 // check if one opened output is not needed any more after disconnecting one device
3424 for (size_t i = 0; i < mOutputs.size(); i++) {
3425 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003426 if (!desc->isDuplicated()) {
3427 if (!(desc->mProfile->mSupportedDevices.types()
3428 & mAvailableOutputDevices.types())) {
3429 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3430 mOutputs.keyAt(i));
3431 outputs.add(mOutputs.keyAt(i));
3432 } else if (deviceDistinguishesOnAddress(device) &&
3433 // exact match on device
3434 (desc->mProfile->mSupportedDevices.types() == device)) {
3435 findIoHandlesByAddress(desc, address, outputs);
3436 }
Eric Laurente552edb2014-03-10 17:42:56 -07003437 }
3438 }
Eric Laurentd4692962014-05-05 18:13:44 -07003439 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003440 for (size_t i = 0; i < mHwModules.size(); i++)
3441 {
3442 if (mHwModules[i]->mHandle == 0) {
3443 continue;
3444 }
3445 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3446 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003447 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003448 if (profile->mSupportedDevices.types() & device) {
3449 ALOGV("checkOutputsForDevice(): "
3450 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003451 if (profile->mSamplingRates[0] == 0) {
3452 profile->mSamplingRates.clear();
3453 profile->mSamplingRates.add(0);
3454 }
3455 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3456 profile->mFormats.clear();
3457 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3458 }
3459 if (profile->mChannelMasks[0] == 0) {
3460 profile->mChannelMasks.clear();
3461 profile->mChannelMasks.add(0);
3462 }
3463 }
3464 }
3465 }
3466 }
3467 return NO_ERROR;
3468}
3469
Eric Laurentd4692962014-05-05 18:13:44 -07003470status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3471 audio_policy_dev_state_t state,
3472 SortedVector<audio_io_handle_t>& inputs,
3473 const String8 address)
3474{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003475 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003476 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3477 // first list already open inputs that can be routed to this device
3478 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3479 desc = mInputs.valueAt(input_index);
3480 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3481 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3482 inputs.add(mInputs.keyAt(input_index));
3483 }
3484 }
3485
3486 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003487 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003488 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3489 {
3490 if (mHwModules[module_idx]->mHandle == 0) {
3491 continue;
3492 }
3493 for (size_t profile_index = 0;
3494 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3495 profile_index++)
3496 {
3497 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3498 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003499 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003500 profile_index, module_idx);
3501 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3502 }
3503 }
3504 }
3505
3506 if (profiles.isEmpty() && inputs.isEmpty()) {
3507 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3508 return BAD_VALUE;
3509 }
3510
3511 // open inputs for matching profiles if needed. Direct inputs are also opened to
3512 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3513 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3514
Eric Laurent1c333e22014-05-20 10:48:17 -07003515 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003516 // nothing to do if one input is already opened for this profile
3517 size_t input_index;
3518 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3519 desc = mInputs.valueAt(input_index);
3520 if (desc->mProfile == profile) {
3521 break;
3522 }
3523 }
3524 if (input_index != mInputs.size()) {
3525 continue;
3526 }
3527
3528 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3529 desc = new AudioInputDescriptor(profile);
3530 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003531 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3532 config.sample_rate = desc->mSamplingRate;
3533 config.channel_mask = desc->mChannelMask;
3534 config.format = desc->mFormat;
3535 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3536 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3537 &input,
3538 &config,
3539 &desc->mDevice,
3540 address,
3541 AUDIO_SOURCE_MIC,
3542 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003543
Eric Laurentcf2c0212014-07-25 16:20:43 -07003544 if (status == NO_ERROR) {
3545 desc->mSamplingRate = config.sample_rate;
3546 desc->mChannelMask = config.channel_mask;
3547 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003548
Eric Laurentd4692962014-05-05 18:13:44 -07003549 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003550 char *param = audio_device_address_to_parameter(device, address);
3551 mpClientInterface->setParameters(input, String8(param));
3552 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003553 }
3554
3555 // Here is where we step through and resolve any "dynamic" fields
3556 String8 reply;
3557 char *value;
3558 if (profile->mSamplingRates[0] == 0) {
3559 reply = mpClientInterface->getParameters(input,
3560 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3561 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3562 reply.string());
3563 value = strpbrk((char *)reply.string(), "=");
3564 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003565 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003566 }
3567 }
3568 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3569 reply = mpClientInterface->getParameters(input,
3570 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3571 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3572 value = strpbrk((char *)reply.string(), "=");
3573 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003574 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003575 }
3576 }
3577 if (profile->mChannelMasks[0] == 0) {
3578 reply = mpClientInterface->getParameters(input,
3579 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3580 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3581 reply.string());
3582 value = strpbrk((char *)reply.string(), "=");
3583 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003584 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003585 }
3586 }
3587 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3588 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3589 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3590 ALOGW("checkInputsForDevice() direct input missing param");
3591 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003592 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003593 }
3594
3595 if (input != 0) {
3596 addInput(input, desc);
3597 }
3598 } // endif input != 0
3599
Eric Laurentcf2c0212014-07-25 16:20:43 -07003600 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003601 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003602 profiles.removeAt(profile_index);
3603 profile_index--;
3604 } else {
3605 inputs.add(input);
3606 ALOGV("checkInputsForDevice(): adding input %d", input);
3607 }
3608 } // end scan profiles
3609
3610 if (profiles.isEmpty()) {
3611 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3612 return BAD_VALUE;
3613 }
3614 } else {
3615 // Disconnect
3616 // check if one opened input is not needed any more after disconnecting one device
3617 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3618 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003619 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3620 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003621 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3622 mInputs.keyAt(input_index));
3623 inputs.add(mInputs.keyAt(input_index));
3624 }
3625 }
3626 // Clear any profiles associated with the disconnected device.
3627 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3628 if (mHwModules[module_index]->mHandle == 0) {
3629 continue;
3630 }
3631 for (size_t profile_index = 0;
3632 profile_index < mHwModules[module_index]->mInputProfiles.size();
3633 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003634 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003635 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003636 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003637 profile_index, module_index);
3638 if (profile->mSamplingRates[0] == 0) {
3639 profile->mSamplingRates.clear();
3640 profile->mSamplingRates.add(0);
3641 }
3642 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3643 profile->mFormats.clear();
3644 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3645 }
3646 if (profile->mChannelMasks[0] == 0) {
3647 profile->mChannelMasks.clear();
3648 profile->mChannelMasks.add(0);
3649 }
3650 }
3651 }
3652 }
3653 } // end disconnect
3654
3655 return NO_ERROR;
3656}
3657
3658
Eric Laurente0720872014-03-11 09:30:41 -07003659void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003660{
3661 ALOGV("closeOutput(%d)", output);
3662
Eric Laurent1f2f2232014-06-02 12:01:23 -07003663 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003664 if (outputDesc == NULL) {
3665 ALOGW("closeOutput() unknown output %d", output);
3666 return;
3667 }
3668
3669 // look for duplicated outputs connected to the output being removed.
3670 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003671 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003672 if (dupOutputDesc->isDuplicated() &&
3673 (dupOutputDesc->mOutput1 == outputDesc ||
3674 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003675 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003676 if (dupOutputDesc->mOutput1 == outputDesc) {
3677 outputDesc2 = dupOutputDesc->mOutput2;
3678 } else {
3679 outputDesc2 = dupOutputDesc->mOutput1;
3680 }
3681 // As all active tracks on duplicated output will be deleted,
3682 // and as they were also referenced on the other output, the reference
3683 // count for their stream type must be adjusted accordingly on
3684 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003685 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003686 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003687 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003688 }
3689 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3690 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3691
3692 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003693 mOutputs.removeItem(duplicatedOutput);
3694 }
3695 }
3696
Eric Laurent05b90f82014-08-27 15:32:29 -07003697 nextAudioPortGeneration();
3698
3699 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3700 if (index >= 0) {
3701 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3702 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3703 mAudioPatches.removeItemsAt(index);
3704 mpClientInterface->onAudioPatchListUpdate();
3705 }
3706
Eric Laurente552edb2014-03-10 17:42:56 -07003707 AudioParameter param;
3708 param.add(String8("closing"), String8("true"));
3709 mpClientInterface->setParameters(output, param.toString());
3710
3711 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003712 mOutputs.removeItem(output);
3713 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003714}
3715
3716void AudioPolicyManager::closeInput(audio_io_handle_t input)
3717{
3718 ALOGV("closeInput(%d)", input);
3719
3720 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3721 if (inputDesc == NULL) {
3722 ALOGW("closeInput() unknown input %d", input);
3723 return;
3724 }
3725
Eric Laurent6a94d692014-05-20 11:18:06 -07003726 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003727
3728 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3729 if (index >= 0) {
3730 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3731 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3732 mAudioPatches.removeItemsAt(index);
3733 mpClientInterface->onAudioPatchListUpdate();
3734 }
3735
3736 mpClientInterface->closeInput(input);
3737 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003738}
3739
Eric Laurente0720872014-03-11 09:30:41 -07003740SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003741 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003742{
3743 SortedVector<audio_io_handle_t> outputs;
3744
3745 ALOGVV("getOutputsForDevice() device %04x", device);
3746 for (size_t i = 0; i < openOutputs.size(); i++) {
3747 ALOGVV("output %d isDuplicated=%d device=%04x",
3748 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3749 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3750 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3751 outputs.add(openOutputs.keyAt(i));
3752 }
3753 }
3754 return outputs;
3755}
3756
Eric Laurente0720872014-03-11 09:30:41 -07003757bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003758 SortedVector<audio_io_handle_t>& outputs2)
3759{
3760 if (outputs1.size() != outputs2.size()) {
3761 return false;
3762 }
3763 for (size_t i = 0; i < outputs1.size(); i++) {
3764 if (outputs1[i] != outputs2[i]) {
3765 return false;
3766 }
3767 }
3768 return true;
3769}
3770
Eric Laurente0720872014-03-11 09:30:41 -07003771void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003772{
3773 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3774 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3775 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3776 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3777
3778 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3779 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3780 strategy, srcOutputs[0], dstOutputs[0]);
3781 // mute strategy while moving tracks from one output to another
3782 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003783 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003784 if (desc->isStrategyActive(strategy)) {
3785 setStrategyMute(strategy, true, srcOutputs[i]);
3786 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3787 }
3788 }
3789
3790 // Move effects associated to this strategy from previous output to new output
3791 if (strategy == STRATEGY_MEDIA) {
3792 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3793 SortedVector<audio_io_handle_t> moved;
3794 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003795 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3796 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3797 effectDesc->mIo != fxOutput) {
3798 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003799 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3800 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003801 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003802 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003803 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003804 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003805 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003806 }
3807 }
3808 }
3809 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003810 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08003811 if (i == AUDIO_STREAM_PATCH) {
3812 continue;
3813 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003814 if (getStrategy((audio_stream_type_t)i) == strategy) {
3815 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003816 }
3817 }
3818 }
3819}
3820
Eric Laurente0720872014-03-11 09:30:41 -07003821void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003822{
Jon Eklund966095e2014-09-09 15:39:49 -05003823 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3824 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003825 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003826 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3827 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003828 checkOutputForStrategy(STRATEGY_SONIFICATION);
3829 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003830 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07003831 checkOutputForStrategy(STRATEGY_MEDIA);
3832 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003833 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07003834}
3835
Eric Laurente0720872014-03-11 09:30:41 -07003836audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003837{
Eric Laurente552edb2014-03-10 17:42:56 -07003838 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003839 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003840 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3841 return mOutputs.keyAt(i);
3842 }
3843 }
3844
3845 return 0;
3846}
3847
Eric Laurente0720872014-03-11 09:30:41 -07003848void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003849{
Eric Laurente552edb2014-03-10 17:42:56 -07003850 audio_io_handle_t a2dpOutput = getA2dpOutput();
3851 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003852 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003853 return;
3854 }
3855
Eric Laurent3a4311c2014-03-17 12:00:47 -07003856 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08003857 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
3858 ~AUDIO_DEVICE_BIT_IN) != 0) ||
3859 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003860 // suspend A2DP output if:
3861 // (NOT already suspended) &&
3862 // ((SCO device is connected &&
3863 // (forced usage for communication || for record is SCO))) ||
3864 // (phone state is ringing || in call)
3865 //
3866 // restore A2DP output if:
3867 // (Already suspended) &&
3868 // ((SCO device is NOT connected ||
3869 // (forced usage NOT for communication && NOT for record is SCO))) &&
3870 // (phone state is NOT ringing && NOT in call)
3871 //
3872 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003873 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003874 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3875 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3876 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3877 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003878
3879 mpClientInterface->restoreOutput(a2dpOutput);
3880 mA2dpSuspended = false;
3881 }
3882 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003883 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003884 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3885 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3886 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3887 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003888
3889 mpClientInterface->suspendOutput(a2dpOutput);
3890 mA2dpSuspended = true;
3891 }
3892 }
3893}
3894
Eric Laurent1c333e22014-05-20 10:48:17 -07003895audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003896{
3897 audio_devices_t device = AUDIO_DEVICE_NONE;
3898
Eric Laurent1f2f2232014-06-02 12:01:23 -07003899 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003900
3901 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3902 if (index >= 0) {
3903 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3904 if (patchDesc->mUid != mUidCached) {
3905 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3906 outputDesc->device(), outputDesc->mPatchHandle);
3907 return outputDesc->device();
3908 }
3909 }
3910
Eric Laurente552edb2014-03-10 17:42:56 -07003911 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003912 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003913 // use device for strategy enforced audible
3914 // 2: we are in call or the strategy phone is active on the output:
3915 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003916 // 3: the strategy for enforced audible is active but not enforced on the output:
3917 // use the device for strategy enforced audible
3918 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003919 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003920 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003921 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08003922 // 6: the strategy accessibility is active on the output:
3923 // use device for strategy accessibility
3924 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003925 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08003926 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003927 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08003928 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003929 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05003930 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3931 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003932 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3933 } else if (isInCall() ||
3934 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3935 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003936 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3937 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003938 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3939 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3940 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3941 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003942 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
3943 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003944 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3945 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3946 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3947 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003948 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
3949 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003950 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
3951 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003952 }
3953
Eric Laurent1c333e22014-05-20 10:48:17 -07003954 ALOGV("getNewOutputDevice() selected device %x", device);
3955 return device;
3956}
3957
3958audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3959{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003960 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003961
3962 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3963 if (index >= 0) {
3964 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3965 if (patchDesc->mUid != mUidCached) {
3966 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3967 inputDesc->mDevice, inputDesc->mPatchHandle);
3968 return inputDesc->mDevice;
3969 }
3970 }
3971
Eric Laurent1c333e22014-05-20 10:48:17 -07003972 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3973
3974 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003975 return device;
3976}
3977
Eric Laurente0720872014-03-11 09:30:41 -07003978uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003979 return (uint32_t)getStrategy(stream);
3980}
3981
Eric Laurente0720872014-03-11 09:30:41 -07003982audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003983 // By checking the range of stream before calling getStrategy, we avoid
3984 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3985 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08003986 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003987 return AUDIO_DEVICE_NONE;
3988 }
3989 audio_devices_t devices;
3990 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3991 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3992 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3993 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003994 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003995 if (outputDesc->isStrategyActive(strategy)) {
3996 devices = outputDesc->device();
3997 break;
3998 }
Eric Laurente552edb2014-03-10 17:42:56 -07003999 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004000
4001 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4002 and doesn't really need to.*/
4003 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4004 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4005 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4006 }
4007
Eric Laurente552edb2014-03-10 17:42:56 -07004008 return devices;
4009}
4010
Eric Laurente0720872014-03-11 09:30:41 -07004011AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004012 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004013
4014 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4015
Eric Laurente552edb2014-03-10 17:42:56 -07004016 // stream to strategy mapping
4017 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004018 case AUDIO_STREAM_VOICE_CALL:
4019 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004020 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004021 case AUDIO_STREAM_RING:
4022 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004023 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004024 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004025 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004026 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004027 return STRATEGY_DTMF;
4028 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004029 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004030 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004031 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4032 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004033 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004034 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004035 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004036 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004037 case AUDIO_STREAM_TTS:
4038 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004039 case AUDIO_STREAM_ACCESSIBILITY:
4040 return STRATEGY_ACCESSIBILITY;
4041 case AUDIO_STREAM_REROUTING:
4042 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004043 }
4044}
4045
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004046uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4047 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004048 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4049 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4050 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004051 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4052 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4053 }
4054
4055 // usage to strategy mapping
4056 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004057 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4058 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4059 return (uint32_t) STRATEGY_SONIFICATION;
4060 }
4061 if (isInCall()) {
4062 return (uint32_t) STRATEGY_PHONE;
4063 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004064 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004065
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004066 case AUDIO_USAGE_MEDIA:
4067 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004068 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4069 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4070 return (uint32_t) STRATEGY_MEDIA;
4071
4072 case AUDIO_USAGE_VOICE_COMMUNICATION:
4073 return (uint32_t) STRATEGY_PHONE;
4074
4075 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4076 return (uint32_t) STRATEGY_DTMF;
4077
4078 case AUDIO_USAGE_ALARM:
4079 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4080 return (uint32_t) STRATEGY_SONIFICATION;
4081
4082 case AUDIO_USAGE_NOTIFICATION:
4083 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4084 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4085 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4086 case AUDIO_USAGE_NOTIFICATION_EVENT:
4087 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4088
4089 case AUDIO_USAGE_UNKNOWN:
4090 default:
4091 return (uint32_t) STRATEGY_MEDIA;
4092 }
4093}
4094
Eric Laurente0720872014-03-11 09:30:41 -07004095void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004096 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004097 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004098 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4099 updateDevicesAndOutputs();
4100 break;
4101 default:
4102 break;
4103 }
4104}
4105
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004106bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4107 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4108 if (s == (size_t) streamToIgnore) {
4109 continue;
4110 }
4111 for (size_t i = 0; i < mOutputs.size(); i++) {
4112 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4113 if (outputDesc->mRefCount[s] != 0) {
4114 return true;
4115 }
4116 }
4117 }
4118 return false;
4119}
4120
4121uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4122 switch(event) {
4123 case STARTING_OUTPUT:
4124 mBeaconMuteRefCount++;
4125 break;
4126 case STOPPING_OUTPUT:
4127 if (mBeaconMuteRefCount > 0) {
4128 mBeaconMuteRefCount--;
4129 }
4130 break;
4131 case STARTING_BEACON:
4132 mBeaconPlayingRefCount++;
4133 break;
4134 case STOPPING_BEACON:
4135 if (mBeaconPlayingRefCount > 0) {
4136 mBeaconPlayingRefCount--;
4137 }
4138 break;
4139 }
4140
4141 if (mBeaconMuteRefCount > 0) {
4142 // any playback causes beacon to be muted
4143 return setBeaconMute(true);
4144 } else {
4145 // no other playback: unmute when beacon starts playing, mute when it stops
4146 return setBeaconMute(mBeaconPlayingRefCount == 0);
4147 }
4148}
4149
4150uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4151 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4152 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4153 // keep track of muted state to avoid repeating mute/unmute operations
4154 if (mBeaconMuted != mute) {
4155 // mute/unmute AUDIO_STREAM_TTS on all outputs
4156 ALOGV("\t muting %d", mute);
4157 uint32_t maxLatency = 0;
4158 for (size_t i = 0; i < mOutputs.size(); i++) {
4159 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4160 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4161 desc->mIoHandle,
4162 0 /*delay*/, AUDIO_DEVICE_NONE);
4163 const uint32_t latency = desc->latency() * 2;
4164 if (latency > maxLatency) {
4165 maxLatency = latency;
4166 }
4167 }
4168 mBeaconMuted = mute;
4169 return maxLatency;
4170 }
4171 return 0;
4172}
4173
Eric Laurente0720872014-03-11 09:30:41 -07004174audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004175 bool fromCache)
4176{
4177 uint32_t device = AUDIO_DEVICE_NONE;
4178
4179 if (fromCache) {
4180 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4181 strategy, mDeviceForStrategy[strategy]);
4182 return mDeviceForStrategy[strategy];
4183 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004184 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004185 switch (strategy) {
4186
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004187 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4188 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4189 if (!device) {
4190 ALOGE("getDeviceForStrategy() no device found for "\
4191 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4192 }
4193 break;
4194
Eric Laurente552edb2014-03-10 17:42:56 -07004195 case STRATEGY_SONIFICATION_RESPECTFUL:
4196 if (isInCall()) {
4197 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004198 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004199 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4200 // while media is playing on a remote device, use the the sonification behavior.
4201 // Note that we test this usecase before testing if media is playing because
4202 // the isStreamActive() method only informs about the activity of a stream, not
4203 // if it's for local playback. Note also that we use the same delay between both tests
4204 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004205 //user "safe" speaker if available instead of normal speaker to avoid triggering
4206 //other acoustic safety mechanisms for notification
4207 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4208 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004209 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004210 // while media is playing (or has recently played), use the same device
4211 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4212 } else {
4213 // when media is not playing anymore, fall back on the sonification behavior
4214 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004215 //user "safe" speaker if available instead of normal speaker to avoid triggering
4216 //other acoustic safety mechanisms for notification
4217 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4218 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004219 }
4220
4221 break;
4222
4223 case STRATEGY_DTMF:
4224 if (!isInCall()) {
4225 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4226 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4227 break;
4228 }
4229 // when in call, DTMF and PHONE strategies follow the same rules
4230 // FALL THROUGH
4231
4232 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004233 // Force use of only devices on primary output if:
4234 // - in call AND
4235 // - cannot route from voice call RX OR
4236 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4237 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4238 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4239 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4240 if (((mAvailableInputDevices.types() &
4241 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4242 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004243 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004244 AUDIO_DEVICE_API_VERSION_3_0))) {
4245 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4246 }
4247 }
Eric Laurente552edb2014-03-10 17:42:56 -07004248 // for phone strategy, we first consider the forced use and then the available devices by order
4249 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004250 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4251 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004252 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004253 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004254 if (device) break;
4255 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004256 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004257 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004258 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004259 if (device) break;
4260 // if SCO device is requested but no SCO device is available, fall back to default case
4261 // FALL THROUGH
4262
4263 default: // FORCE_NONE
4264 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004265 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004266 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004267 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004268 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004269 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004270 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004271 if (device) break;
4272 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004273 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004274 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004275 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004276 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004277 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4278 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004279 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004280 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004281 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004282 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004283 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004284 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004285 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004286 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004287 if (device) break;
4288 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004289 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004290 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004291 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004292 if (device == AUDIO_DEVICE_NONE) {
4293 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4294 }
4295 break;
4296
Eric Laurent3b73df72014-03-11 09:06:29 -07004297 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004298 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4299 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004300 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004301 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004302 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004303 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004304 if (device) break;
4305 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004306 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004307 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004308 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004309 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004310 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004311 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004312 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004313 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004314 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004315 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004316 if (device) break;
4317 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004318 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4319 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004320 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004321 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004322 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004323 if (device == AUDIO_DEVICE_NONE) {
4324 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4325 }
4326 break;
4327 }
4328 break;
4329
4330 case STRATEGY_SONIFICATION:
4331
4332 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4333 // handleIncallSonification().
4334 if (isInCall()) {
4335 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4336 break;
4337 }
4338 // FALL THROUGH
4339
4340 case STRATEGY_ENFORCED_AUDIBLE:
4341 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4342 // except:
4343 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4344 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4345
4346 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004347 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004348 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004349 if (device == AUDIO_DEVICE_NONE) {
4350 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4351 }
4352 }
4353 // The second device used for sonification is the same as the device used by media strategy
4354 // FALL THROUGH
4355
Eric Laurent223fd5c2014-11-11 13:43:36 -08004356 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4357 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004358 if (strategy == STRATEGY_ACCESSIBILITY) {
4359 // do not route accessibility prompts to a digital output currently configured with a
4360 // compressed format as they would likely not be mixed and dropped.
4361 for (size_t i = 0; i < mOutputs.size(); i++) {
4362 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4363 audio_devices_t devices = desc->device() &
4364 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4365 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4366 devices != AUDIO_DEVICE_NONE) {
4367 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4368 }
4369 }
4370 }
4371 // FALL THROUGH
4372
Eric Laurent223fd5c2014-11-11 13:43:36 -08004373 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004374 case STRATEGY_MEDIA: {
4375 uint32_t device2 = AUDIO_DEVICE_NONE;
4376 if (strategy != STRATEGY_SONIFICATION) {
4377 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004378 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004379 }
4380 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004381 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004382 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004383 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004384 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004385 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004386 }
4387 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004388 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004389 }
4390 }
Hochi Huang327cb702014-09-21 09:47:31 +08004391 if ((device2 == AUDIO_DEVICE_NONE) &&
4392 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4393 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4394 }
Eric Laurente552edb2014-03-10 17:42:56 -07004395 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004396 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004397 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004398 if ((device2 == AUDIO_DEVICE_NONE)) {
4399 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4400 }
Eric Laurente552edb2014-03-10 17:42:56 -07004401 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004402 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004403 }
4404 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004405 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004406 }
4407 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004408 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004409 }
4410 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004411 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004412 }
4413 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4414 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004415 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004416 }
4417 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004418 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004419 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004420 }
4421 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004422 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004423 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004424 int device3 = AUDIO_DEVICE_NONE;
4425 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004426 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004427 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4428 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004429 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004430 }
Eric Laurente552edb2014-03-10 17:42:56 -07004431
Jungshik Jang839e4f32014-06-26 17:23:40 +09004432 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004433 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4434 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4435 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004436
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004437 // If hdmi system audio mode is on, remove speaker out of output list.
4438 if ((strategy == STRATEGY_MEDIA) &&
4439 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4440 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4441 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4442 }
4443
Eric Laurente552edb2014-03-10 17:42:56 -07004444 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004445 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004446 if (device == AUDIO_DEVICE_NONE) {
4447 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4448 }
4449 } break;
4450
4451 default:
4452 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4453 break;
4454 }
4455
4456 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4457 return device;
4458}
4459
Eric Laurente0720872014-03-11 09:30:41 -07004460void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004461{
4462 for (int i = 0; i < NUM_STRATEGIES; i++) {
4463 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4464 }
4465 mPreviousOutputs = mOutputs;
4466}
4467
Eric Laurent1f2f2232014-06-02 12:01:23 -07004468uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004469 audio_devices_t prevDevice,
4470 uint32_t delayMs)
4471{
4472 // mute/unmute strategies using an incompatible device combination
4473 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4474 // if unmuting, unmute only after the specified delay
4475 if (outputDesc->isDuplicated()) {
4476 return 0;
4477 }
4478
4479 uint32_t muteWaitMs = 0;
4480 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004481 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004482
4483 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4484 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004485 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004486 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4487 bool doMute = false;
4488
4489 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4490 doMute = true;
4491 outputDesc->mStrategyMutedByDevice[i] = true;
4492 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4493 doMute = true;
4494 outputDesc->mStrategyMutedByDevice[i] = false;
4495 }
Eric Laurent99401132014-05-07 19:48:15 -07004496 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004497 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004498 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004499 // skip output if it does not share any device with current output
4500 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4501 == AUDIO_DEVICE_NONE) {
4502 continue;
4503 }
4504 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4505 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4506 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4507 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4508 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004509 if (mute) {
4510 // FIXME: should not need to double latency if volume could be applied
4511 // immediately by the audioflinger mixer. We must account for the delay
4512 // between now and the next time the audioflinger thread for this output
4513 // will process a buffer (which corresponds to one buffer size,
4514 // usually 1/2 or 1/4 of the latency).
4515 if (muteWaitMs < desc->latency() * 2) {
4516 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004517 }
4518 }
4519 }
4520 }
4521 }
4522 }
4523
Eric Laurent99401132014-05-07 19:48:15 -07004524 // temporary mute output if device selection changes to avoid volume bursts due to
4525 // different per device volumes
4526 if (outputDesc->isActive() && (device != prevDevice)) {
4527 if (muteWaitMs < outputDesc->latency() * 2) {
4528 muteWaitMs = outputDesc->latency() * 2;
4529 }
4530 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4531 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004532 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004533 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004534 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004535 muteWaitMs *2, device);
4536 }
4537 }
4538 }
4539
Eric Laurente552edb2014-03-10 17:42:56 -07004540 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4541 if (muteWaitMs > delayMs) {
4542 muteWaitMs -= delayMs;
4543 usleep(muteWaitMs * 1000);
4544 return muteWaitMs;
4545 }
4546 return 0;
4547}
4548
Eric Laurente0720872014-03-11 09:30:41 -07004549uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004550 audio_devices_t device,
4551 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004552 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004553 audio_patch_handle_t *patchHandle,
4554 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004555{
4556 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004557 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004558 AudioParameter param;
4559 uint32_t muteWaitMs;
4560
4561 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004562 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4563 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004564 return muteWaitMs;
4565 }
4566 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4567 // output profile
4568 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004569 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004570 return 0;
4571 }
4572
4573 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004574 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004575
4576 audio_devices_t prevDevice = outputDesc->mDevice;
4577
4578 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4579
4580 if (device != AUDIO_DEVICE_NONE) {
4581 outputDesc->mDevice = device;
4582 }
4583 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4584
4585 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004586 // the requested device is AUDIO_DEVICE_NONE
4587 // OR the requested device is the same as current device
4588 // AND force is not specified
4589 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004590 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004591 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4592 outputDesc->mPatchHandle != 0) {
4593 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4594 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004595 return muteWaitMs;
4596 }
4597
4598 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004599
Eric Laurente552edb2014-03-10 17:42:56 -07004600 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004601 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004602 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004603 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004604 DeviceVector deviceList = (address == NULL) ?
4605 mAvailableOutputDevices.getDevicesFromType(device)
4606 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004607 if (!deviceList.isEmpty()) {
4608 struct audio_patch patch;
4609 outputDesc->toAudioPortConfig(&patch.sources[0]);
4610 patch.num_sources = 1;
4611 patch.num_sinks = 0;
4612 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4613 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004614 patch.num_sinks++;
4615 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004616 ssize_t index;
4617 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4618 index = mAudioPatches.indexOfKey(*patchHandle);
4619 } else {
4620 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4621 }
4622 sp< AudioPatch> patchDesc;
4623 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4624 if (index >= 0) {
4625 patchDesc = mAudioPatches.valueAt(index);
4626 afPatchHandle = patchDesc->mAfPatchHandle;
4627 }
4628
Eric Laurent1c333e22014-05-20 10:48:17 -07004629 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004630 &afPatchHandle,
4631 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004632 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4633 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004634 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004635 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004636 if (index < 0) {
4637 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4638 &patch, mUidCached);
4639 addAudioPatch(patchDesc->mHandle, patchDesc);
4640 } else {
4641 patchDesc->mPatch = patch;
4642 }
4643 patchDesc->mAfPatchHandle = afPatchHandle;
4644 patchDesc->mUid = mUidCached;
4645 if (patchHandle) {
4646 *patchHandle = patchDesc->mHandle;
4647 }
4648 outputDesc->mPatchHandle = patchDesc->mHandle;
4649 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004650 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004651 }
4652 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004653
4654 // inform all input as well
4655 for (size_t i = 0; i < mInputs.size(); i++) {
4656 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4657 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4658 AudioParameter inputCmd = AudioParameter();
4659 ALOGV("%s: inform input %d of device:%d", __func__,
4660 inputDescriptor->mIoHandle, device);
4661 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4662 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4663 inputCmd.toString(),
4664 delayMs);
4665 }
4666 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004667 }
Eric Laurente552edb2014-03-10 17:42:56 -07004668
4669 // update stream volumes according to new device
4670 applyStreamVolumes(output, device, delayMs);
4671
4672 return muteWaitMs;
4673}
4674
Eric Laurent1c333e22014-05-20 10:48:17 -07004675status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004676 int delayMs,
4677 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004678{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004679 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004680 ssize_t index;
4681 if (patchHandle) {
4682 index = mAudioPatches.indexOfKey(*patchHandle);
4683 } else {
4684 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4685 }
4686 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004687 return INVALID_OPERATION;
4688 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004689 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4690 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004691 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4692 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004693 removeAudioPatch(patchDesc->mHandle);
4694 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004695 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004696 return status;
4697}
4698
4699status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4700 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004701 bool force,
4702 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004703{
4704 status_t status = NO_ERROR;
4705
Eric Laurent1f2f2232014-06-02 12:01:23 -07004706 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004707 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4708 inputDesc->mDevice = device;
4709
4710 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4711 if (!deviceList.isEmpty()) {
4712 struct audio_patch patch;
4713 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004714 // AUDIO_SOURCE_HOTWORD is for internal use only:
4715 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004716 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4717 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004718 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4719 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004720 patch.num_sinks = 1;
4721 //only one input device for now
4722 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004723 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004724 ssize_t index;
4725 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4726 index = mAudioPatches.indexOfKey(*patchHandle);
4727 } else {
4728 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4729 }
4730 sp< AudioPatch> patchDesc;
4731 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4732 if (index >= 0) {
4733 patchDesc = mAudioPatches.valueAt(index);
4734 afPatchHandle = patchDesc->mAfPatchHandle;
4735 }
4736
Eric Laurent1c333e22014-05-20 10:48:17 -07004737 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004738 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004739 0);
4740 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004741 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004742 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004743 if (index < 0) {
4744 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4745 &patch, mUidCached);
4746 addAudioPatch(patchDesc->mHandle, patchDesc);
4747 } else {
4748 patchDesc->mPatch = patch;
4749 }
4750 patchDesc->mAfPatchHandle = afPatchHandle;
4751 patchDesc->mUid = mUidCached;
4752 if (patchHandle) {
4753 *patchHandle = patchDesc->mHandle;
4754 }
4755 inputDesc->mPatchHandle = patchDesc->mHandle;
4756 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004757 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004758 }
4759 }
4760 }
4761 return status;
4762}
4763
Eric Laurent6a94d692014-05-20 11:18:06 -07004764status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4765 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004766{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004767 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004768 ssize_t index;
4769 if (patchHandle) {
4770 index = mAudioPatches.indexOfKey(*patchHandle);
4771 } else {
4772 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4773 }
4774 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004775 return INVALID_OPERATION;
4776 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004777 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4778 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004779 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4780 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004781 removeAudioPatch(patchDesc->mHandle);
4782 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004783 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004784 return status;
4785}
4786
4787sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004788 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004789 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004790 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004791 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004792{
4793 // Choose an input profile based on the requested capture parameters: select the first available
4794 // profile supporting all requested parameters.
4795
4796 for (size_t i = 0; i < mHwModules.size(); i++)
4797 {
4798 if (mHwModules[i]->mHandle == 0) {
4799 continue;
4800 }
4801 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4802 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004803 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004804 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004805 if (profile->isCompatibleProfile(device, samplingRate,
4806 &samplingRate /*updatedSamplingRate*/,
4807 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004808 return profile;
4809 }
4810 }
4811 }
4812 return NULL;
4813}
4814
Eric Laurente0720872014-03-11 09:30:41 -07004815audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004816{
4817 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004818 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4819 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004820 switch (inputSource) {
4821 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004822 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004823 device = AUDIO_DEVICE_IN_VOICE_CALL;
4824 break;
4825 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004826 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004827
4828 case AUDIO_SOURCE_DEFAULT:
4829 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004830 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4831 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004832 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4833 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4834 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4835 device = AUDIO_DEVICE_IN_USB_DEVICE;
4836 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4837 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004838 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004839 break;
4840
4841 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4842 // Allow only use of devices on primary input if in call and HAL does not support routing
4843 // to voice call path.
4844 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4845 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4846 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4847 }
4848
4849 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4850 case AUDIO_POLICY_FORCE_BT_SCO:
4851 // if SCO device is requested but no SCO device is available, fall back to default case
4852 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4853 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4854 break;
4855 }
4856 // FALL THROUGH
4857
4858 default: // FORCE_NONE
4859 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4860 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4861 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4862 device = AUDIO_DEVICE_IN_USB_DEVICE;
4863 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4864 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4865 }
4866 break;
4867
4868 case AUDIO_POLICY_FORCE_SPEAKER:
4869 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4870 device = AUDIO_DEVICE_IN_BACK_MIC;
4871 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4872 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4873 }
4874 break;
4875 }
4876 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004877
Eric Laurente552edb2014-03-10 17:42:56 -07004878 case AUDIO_SOURCE_VOICE_RECOGNITION:
4879 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004880 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004881 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004882 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004883 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004884 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004885 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4886 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004887 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004888 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4889 }
4890 break;
4891 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004892 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004893 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004894 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004895 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4896 }
4897 break;
4898 case AUDIO_SOURCE_VOICE_DOWNLINK:
4899 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004900 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004901 device = AUDIO_DEVICE_IN_VOICE_CALL;
4902 }
4903 break;
4904 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004905 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004906 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4907 }
4908 break;
Hochi Huang327cb702014-09-21 09:47:31 +08004909 case AUDIO_SOURCE_FM_TUNER:
4910 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
4911 device = AUDIO_DEVICE_IN_FM_TUNER;
4912 }
4913 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004914 default:
4915 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4916 break;
4917 }
4918 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4919 return device;
4920}
4921
Eric Laurente0720872014-03-11 09:30:41 -07004922bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004923{
4924 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4925 device &= ~AUDIO_DEVICE_BIT_IN;
4926 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4927 return true;
4928 }
4929 return false;
4930}
4931
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004932bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4933 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4934}
4935
Eric Laurente0720872014-03-11 09:30:41 -07004936audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004937{
4938 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004939 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004940 if ((input_descriptor->mRefCount > 0)
4941 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4942 return mInputs.keyAt(i);
4943 }
4944 }
4945 return 0;
4946}
4947
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004948uint32_t AudioPolicyManager::activeInputsCount() const
4949{
4950 uint32_t count = 0;
4951 for (size_t i = 0; i < mInputs.size(); i++) {
4952 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4953 if (desc->mRefCount > 0) {
4954 return count++;
4955 }
4956 }
4957 return count;
4958}
4959
Eric Laurente552edb2014-03-10 17:42:56 -07004960
Eric Laurente0720872014-03-11 09:30:41 -07004961audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004962{
4963 if (device == AUDIO_DEVICE_NONE) {
4964 // this happens when forcing a route update and no track is active on an output.
4965 // In this case the returned category is not important.
4966 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004967 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004968 // Multiple device selection is either:
4969 // - speaker + one other device: give priority to speaker in this case.
4970 // - one A2DP device + another device: happens with duplicated output. In this case
4971 // retain the device on the A2DP output as the other must not correspond to an active
4972 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004973 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004974 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4975 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004976 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4977 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4978 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4979 device = AUDIO_DEVICE_OUT_AUX_LINE;
4980 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4981 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004982 } else {
4983 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4984 }
4985 }
4986
Jon Eklund11c9fb12014-06-23 14:47:03 -05004987 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4988 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4989 device = AUDIO_DEVICE_OUT_SPEAKER;
4990
Eric Laurent3b73df72014-03-11 09:06:29 -07004991 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004992 "getDeviceForVolume() invalid device combination: %08x",
4993 device);
4994
4995 return device;
4996}
4997
Eric Laurente0720872014-03-11 09:30:41 -07004998AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004999{
5000 switch(getDeviceForVolume(device)) {
5001 case AUDIO_DEVICE_OUT_EARPIECE:
5002 return DEVICE_CATEGORY_EARPIECE;
5003 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5004 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5005 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5006 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5007 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5008 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5009 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005010 case AUDIO_DEVICE_OUT_LINE:
5011 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5012 /*USB? Remote submix?*/
5013 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005014 case AUDIO_DEVICE_OUT_SPEAKER:
5015 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5016 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005017 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5018 case AUDIO_DEVICE_OUT_USB_DEVICE:
5019 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5020 default:
5021 return DEVICE_CATEGORY_SPEAKER;
5022 }
5023}
5024
Eric Laurent223fd5c2014-11-11 13:43:36 -08005025/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005026float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005027 int indexInUi)
5028{
5029 device_category deviceCategory = getDeviceCategory(device);
5030 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5031
5032 // the volume index in the UI is relative to the min and max volume indices for this stream type
5033 int nbSteps = 1 + curve[VOLMAX].mIndex -
5034 curve[VOLMIN].mIndex;
5035 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5036 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5037
5038 // find what part of the curve this index volume belongs to, or if it's out of bounds
5039 int segment = 0;
5040 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5041 return 0.0f;
5042 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5043 segment = 0;
5044 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5045 segment = 1;
5046 } else if (volIdx <= curve[VOLMAX].mIndex) {
5047 segment = 2;
5048 } else { // out of bounds
5049 return 1.0f;
5050 }
5051
5052 // linear interpolation in the attenuation table in dB
5053 float decibels = curve[segment].mDBAttenuation +
5054 ((float)(volIdx - curve[segment].mIndex)) *
5055 ( (curve[segment+1].mDBAttenuation -
5056 curve[segment].mDBAttenuation) /
5057 ((float)(curve[segment+1].mIndex -
5058 curve[segment].mIndex)) );
5059
5060 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5061
5062 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5063 curve[segment].mIndex, volIdx,
5064 curve[segment+1].mIndex,
5065 curve[segment].mDBAttenuation,
5066 decibels,
5067 curve[segment+1].mDBAttenuation,
5068 amplification);
5069
5070 return amplification;
5071}
5072
Eric Laurente0720872014-03-11 09:30:41 -07005073const AudioPolicyManager::VolumeCurvePoint
5074 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005075 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5076};
5077
Eric Laurente0720872014-03-11 09:30:41 -07005078const AudioPolicyManager::VolumeCurvePoint
5079 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005080 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5081};
5082
Eric Laurente0720872014-03-11 09:30:41 -07005083const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005084 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5085 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5086};
5087
5088const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005089 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005090 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5091};
5092
Eric Laurente0720872014-03-11 09:30:41 -07005093const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005094 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005095 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005096};
5097
5098const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005099 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005100 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5101};
5102
Eric Laurente0720872014-03-11 09:30:41 -07005103const AudioPolicyManager::VolumeCurvePoint
5104 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005105 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5106};
5107
5108// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5109// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5110// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5111// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5112
Eric Laurente0720872014-03-11 09:30:41 -07005113const AudioPolicyManager::VolumeCurvePoint
5114 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005115 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5116};
5117
Eric Laurente0720872014-03-11 09:30:41 -07005118const AudioPolicyManager::VolumeCurvePoint
5119 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005120 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5121};
5122
Eric Laurente0720872014-03-11 09:30:41 -07005123const AudioPolicyManager::VolumeCurvePoint
5124 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005125 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5126};
5127
Eric Laurente0720872014-03-11 09:30:41 -07005128const AudioPolicyManager::VolumeCurvePoint
5129 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005130 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5131};
5132
Eric Laurente0720872014-03-11 09:30:41 -07005133const AudioPolicyManager::VolumeCurvePoint
5134 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005135 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5136};
5137
Eric Laurente0720872014-03-11 09:30:41 -07005138const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005139 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5140 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5141};
5142
5143const AudioPolicyManager::VolumeCurvePoint
5144 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5145 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5146};
5147
5148const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005149 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5150 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5151};
5152
5153const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005154 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5155 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005156 { // AUDIO_STREAM_VOICE_CALL
5157 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5158 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005159 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5160 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005161 },
5162 { // AUDIO_STREAM_SYSTEM
5163 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5164 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005165 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5166 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005167 },
5168 { // AUDIO_STREAM_RING
5169 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5170 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005171 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5172 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005173 },
5174 { // AUDIO_STREAM_MUSIC
5175 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5176 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005177 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5178 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005179 },
5180 { // AUDIO_STREAM_ALARM
5181 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5182 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005183 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5184 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005185 },
5186 { // AUDIO_STREAM_NOTIFICATION
5187 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5188 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005189 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5190 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005191 },
5192 { // AUDIO_STREAM_BLUETOOTH_SCO
5193 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5194 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005195 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5196 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005197 },
5198 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5199 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5200 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005201 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5202 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005203 },
5204 { // AUDIO_STREAM_DTMF
5205 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5206 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005207 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5208 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005209 },
5210 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005211 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5212 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5213 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5214 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5215 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005216 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005217 { // AUDIO_STREAM_ACCESSIBILITY
5218 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5219 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5220 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5221 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5222 },
5223 { // AUDIO_STREAM_REROUTING
5224 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5225 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5226 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5227 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5228 },
5229 { // AUDIO_STREAM_PATCH
5230 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5231 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5232 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5233 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5234 },
Eric Laurente552edb2014-03-10 17:42:56 -07005235};
5236
Eric Laurente0720872014-03-11 09:30:41 -07005237void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005238{
5239 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5240 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5241 mStreams[i].mVolumeCurve[j] =
5242 sVolumeProfiles[i][j];
5243 }
5244 }
5245
5246 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5247 if (mSpeakerDrcEnabled) {
5248 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5249 sDefaultSystemVolumeCurveDrc;
5250 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5251 sSpeakerSonificationVolumeCurveDrc;
5252 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5253 sSpeakerSonificationVolumeCurveDrc;
5254 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5255 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005256 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5257 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005258 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5259 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005260 }
5261}
5262
Eric Laurente0720872014-03-11 09:30:41 -07005263float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005264 int index,
5265 audio_io_handle_t output,
5266 audio_devices_t device)
5267{
5268 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005269 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005270 StreamDescriptor &streamDesc = mStreams[stream];
5271
5272 if (device == AUDIO_DEVICE_NONE) {
5273 device = outputDesc->device();
5274 }
5275
Eric Laurente552edb2014-03-10 17:42:56 -07005276 volume = volIndexToAmpl(device, streamDesc, index);
5277
5278 // if a headset is connected, apply the following rules to ring tones and notifications
5279 // to avoid sound level bursts in user's ears:
5280 // - always attenuate ring tones and notifications volume by 6dB
5281 // - if music is playing, always limit the volume to current music volume,
5282 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005283 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005284 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5285 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5286 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5287 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5288 ((stream_strategy == STRATEGY_SONIFICATION)
5289 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005290 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005291 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005292 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005293 streamDesc.mCanBeMuted) {
5294 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5295 // when the phone is ringing we must consider that music could have been paused just before
5296 // by the music application and behave as if music was active if the last music track was
5297 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005298 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005299 mLimitRingtoneVolume) {
5300 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005301 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5302 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005303 output,
5304 musicDevice);
5305 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5306 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5307 if (volume > minVol) {
5308 volume = minVol;
5309 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5310 }
5311 }
5312 }
5313
5314 return volume;
5315}
5316
Eric Laurente0720872014-03-11 09:30:41 -07005317status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005318 int index,
5319 audio_io_handle_t output,
5320 audio_devices_t device,
5321 int delayMs,
5322 bool force)
5323{
5324
5325 // do not change actual stream volume if the stream is muted
5326 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5327 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5328 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5329 return NO_ERROR;
5330 }
5331
5332 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005333 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5334 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5335 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5336 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005337 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005338 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005339 return INVALID_OPERATION;
5340 }
5341
5342 float volume = computeVolume(stream, index, output, device);
5343 // We actually change the volume if:
5344 // - the float value returned by computeVolume() changed
5345 // - the force flag is set
5346 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5347 force) {
5348 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5349 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5350 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5351 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005352 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5353 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005354 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005355 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005356 }
5357
Eric Laurent3b73df72014-03-11 09:06:29 -07005358 if (stream == AUDIO_STREAM_VOICE_CALL ||
5359 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005360 float voiceVolume;
5361 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005362 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005363 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5364 } else {
5365 voiceVolume = 1.0;
5366 }
5367
5368 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5369 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5370 mLastVoiceVolume = voiceVolume;
5371 }
5372 }
5373
5374 return NO_ERROR;
5375}
5376
Eric Laurente0720872014-03-11 09:30:41 -07005377void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005378 audio_devices_t device,
5379 int delayMs,
5380 bool force)
5381{
5382 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5383
Eric Laurent3b73df72014-03-11 09:06:29 -07005384 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005385 if (stream == AUDIO_STREAM_PATCH) {
5386 continue;
5387 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005388 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005389 mStreams[stream].getVolumeIndex(device),
5390 output,
5391 device,
5392 delayMs,
5393 force);
5394 }
5395}
5396
Eric Laurente0720872014-03-11 09:30:41 -07005397void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005398 bool on,
5399 audio_io_handle_t output,
5400 int delayMs,
5401 audio_devices_t device)
5402{
5403 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005404 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005405 if (stream == AUDIO_STREAM_PATCH) {
5406 continue;
5407 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005408 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5409 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005410 }
5411 }
5412}
5413
Eric Laurente0720872014-03-11 09:30:41 -07005414void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005415 bool on,
5416 audio_io_handle_t output,
5417 int delayMs,
5418 audio_devices_t device)
5419{
5420 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005421 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005422 if (device == AUDIO_DEVICE_NONE) {
5423 device = outputDesc->device();
5424 }
5425
5426 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5427 stream, on, output, outputDesc->mMuteCount[stream], device);
5428
5429 if (on) {
5430 if (outputDesc->mMuteCount[stream] == 0) {
5431 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005432 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5433 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005434 checkAndSetVolume(stream, 0, output, device, delayMs);
5435 }
5436 }
5437 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5438 outputDesc->mMuteCount[stream]++;
5439 } else {
5440 if (outputDesc->mMuteCount[stream] == 0) {
5441 ALOGV("setStreamMute() unmuting non muted stream!");
5442 return;
5443 }
5444 if (--outputDesc->mMuteCount[stream] == 0) {
5445 checkAndSetVolume(stream,
5446 streamDesc.getVolumeIndex(device),
5447 output,
5448 device,
5449 delayMs);
5450 }
5451 }
5452}
5453
Eric Laurente0720872014-03-11 09:30:41 -07005454void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005455 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005456{
5457 // if the stream pertains to sonification strategy and we are in call we must
5458 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5459 // in the device used for phone strategy and play the tone if the selected device does not
5460 // interfere with the device used for phone strategy
5461 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5462 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005463 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005464 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5465 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005466 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005467 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5468 stream, starting, outputDesc->mDevice, stateChange);
5469 if (outputDesc->mRefCount[stream]) {
5470 int muteCount = 1;
5471 if (stateChange) {
5472 muteCount = outputDesc->mRefCount[stream];
5473 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005474 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005475 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5476 for (int i = 0; i < muteCount; i++) {
5477 setStreamMute(stream, starting, mPrimaryOutput);
5478 }
5479 } else {
5480 ALOGV("handleIncallSonification() high visibility");
5481 if (outputDesc->device() &
5482 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5483 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5484 for (int i = 0; i < muteCount; i++) {
5485 setStreamMute(stream, starting, mPrimaryOutput);
5486 }
5487 }
5488 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005489 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5490 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005491 } else {
5492 mpClientInterface->stopTone();
5493 }
5494 }
5495 }
5496 }
5497}
5498
Eric Laurente0720872014-03-11 09:30:41 -07005499bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005500{
5501 return isStateInCall(mPhoneState);
5502}
5503
Eric Laurente0720872014-03-11 09:30:41 -07005504bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005505 return ((state == AUDIO_MODE_IN_CALL) ||
5506 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005507}
5508
Eric Laurente0720872014-03-11 09:30:41 -07005509uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005510{
5511 return MAX_EFFECTS_CPU_LOAD;
5512}
5513
Eric Laurente0720872014-03-11 09:30:41 -07005514uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005515{
5516 return MAX_EFFECTS_MEMORY;
5517}
5518
Eric Laurent6a94d692014-05-20 11:18:06 -07005519
Eric Laurente552edb2014-03-10 17:42:56 -07005520// --- AudioOutputDescriptor class implementation
5521
Eric Laurente0720872014-03-11 09:30:41 -07005522AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005523 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005524 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005525 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005526 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5527{
5528 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005529 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005530 mRefCount[i] = 0;
5531 mCurVolume[i] = -1.0;
5532 mMuteCount[i] = 0;
5533 mStopTime[i] = 0;
5534 }
5535 for (int i = 0; i < NUM_STRATEGIES; i++) {
5536 mStrategyMutedByDevice[i] = false;
5537 }
5538 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005539 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005540 mSamplingRate = profile->pickSamplingRate();
5541 mFormat = profile->pickFormat();
5542 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005543 if (profile->mGains.size() > 0) {
5544 profile->mGains[0]->getDefaultConfig(&mGain);
5545 }
Eric Laurente552edb2014-03-10 17:42:56 -07005546 }
5547}
5548
Eric Laurente0720872014-03-11 09:30:41 -07005549audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005550{
5551 if (isDuplicated()) {
5552 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5553 } else {
5554 return mDevice;
5555 }
5556}
5557
Eric Laurente0720872014-03-11 09:30:41 -07005558uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005559{
5560 if (isDuplicated()) {
5561 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5562 } else {
5563 return mLatency;
5564 }
5565}
5566
Eric Laurente0720872014-03-11 09:30:41 -07005567bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005568 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005569{
5570 if (isDuplicated()) {
5571 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5572 } else if (outputDesc->isDuplicated()){
5573 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5574 } else {
5575 return (mProfile->mModule == outputDesc->mProfile->mModule);
5576 }
5577}
5578
Eric Laurente0720872014-03-11 09:30:41 -07005579void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005580 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005581{
5582 // forward usage count change to attached outputs
5583 if (isDuplicated()) {
5584 mOutput1->changeRefCount(stream, delta);
5585 mOutput2->changeRefCount(stream, delta);
5586 }
5587 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005588 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5589 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005590 mRefCount[stream] = 0;
5591 return;
5592 }
5593 mRefCount[stream] += delta;
5594 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5595}
5596
Eric Laurente0720872014-03-11 09:30:41 -07005597audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005598{
5599 if (isDuplicated()) {
5600 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5601 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005602 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005603 }
5604}
5605
Eric Laurente0720872014-03-11 09:30:41 -07005606bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005607{
5608 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5609}
5610
Eric Laurente0720872014-03-11 09:30:41 -07005611bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005612 uint32_t inPastMs,
5613 nsecs_t sysTime) const
5614{
5615 if ((sysTime == 0) && (inPastMs != 0)) {
5616 sysTime = systemTime();
5617 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005618 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005619 if (i == AUDIO_STREAM_PATCH) {
5620 continue;
5621 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005622 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005623 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005624 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005625 return true;
5626 }
5627 }
5628 return false;
5629}
5630
Eric Laurente0720872014-03-11 09:30:41 -07005631bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005632 uint32_t inPastMs,
5633 nsecs_t sysTime) const
5634{
5635 if (mRefCount[stream] != 0) {
5636 return true;
5637 }
5638 if (inPastMs == 0) {
5639 return false;
5640 }
5641 if (sysTime == 0) {
5642 sysTime = systemTime();
5643 }
5644 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5645 return true;
5646 }
5647 return false;
5648}
5649
Eric Laurent1c333e22014-05-20 10:48:17 -07005650void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005651 struct audio_port_config *dstConfig,
5652 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005653{
Eric Laurent84c70242014-06-23 08:46:27 -07005654 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5655
Eric Laurent1f2f2232014-06-02 12:01:23 -07005656 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5657 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5658 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005659 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005660 }
5661 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5662
Eric Laurent6a94d692014-05-20 11:18:06 -07005663 dstConfig->id = mId;
5664 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5665 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005666 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5667 dstConfig->ext.mix.handle = mIoHandle;
5668 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005669}
5670
5671void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5672 struct audio_port *port) const
5673{
Eric Laurent84c70242014-06-23 08:46:27 -07005674 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005675 mProfile->toAudioPort(port);
5676 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005677 toAudioPortConfig(&port->active_config);
5678 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005679 port->ext.mix.handle = mIoHandle;
5680 port->ext.mix.latency_class =
5681 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5682}
Eric Laurente552edb2014-03-10 17:42:56 -07005683
Eric Laurente0720872014-03-11 09:30:41 -07005684status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005685{
5686 const size_t SIZE = 256;
5687 char buffer[SIZE];
5688 String8 result;
5689
Eric Laurent4d416952014-08-10 14:07:09 -07005690 snprintf(buffer, SIZE, " ID: %d\n", mId);
5691 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005692 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5693 result.append(buffer);
5694 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5695 result.append(buffer);
5696 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5697 result.append(buffer);
5698 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5699 result.append(buffer);
5700 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5701 result.append(buffer);
5702 snprintf(buffer, SIZE, " Devices %08x\n", device());
5703 result.append(buffer);
5704 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5705 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005706 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5707 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5708 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005709 result.append(buffer);
5710 }
5711 write(fd, result.string(), result.size());
5712
5713 return NO_ERROR;
5714}
5715
5716// --- AudioInputDescriptor class implementation
5717
Eric Laurent1c333e22014-05-20 10:48:17 -07005718AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005719 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005720 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005721 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005722{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005723 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005724 mSamplingRate = profile->pickSamplingRate();
5725 mFormat = profile->pickFormat();
5726 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005727 if (profile->mGains.size() > 0) {
5728 profile->mGains[0]->getDefaultConfig(&mGain);
5729 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005730 }
Eric Laurente552edb2014-03-10 17:42:56 -07005731}
5732
Eric Laurent1c333e22014-05-20 10:48:17 -07005733void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005734 struct audio_port_config *dstConfig,
5735 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005736{
Eric Laurent84c70242014-06-23 08:46:27 -07005737 ALOG_ASSERT(mProfile != 0,
5738 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005739 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5740 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5741 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005742 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005743 }
5744
5745 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5746
Eric Laurent6a94d692014-05-20 11:18:06 -07005747 dstConfig->id = mId;
5748 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5749 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005750 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5751 dstConfig->ext.mix.handle = mIoHandle;
5752 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005753}
5754
5755void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5756 struct audio_port *port) const
5757{
Eric Laurent84c70242014-06-23 08:46:27 -07005758 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5759
Eric Laurent1c333e22014-05-20 10:48:17 -07005760 mProfile->toAudioPort(port);
5761 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005762 toAudioPortConfig(&port->active_config);
5763 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005764 port->ext.mix.handle = mIoHandle;
5765 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5766}
5767
Eric Laurente0720872014-03-11 09:30:41 -07005768status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005769{
5770 const size_t SIZE = 256;
5771 char buffer[SIZE];
5772 String8 result;
5773
Eric Laurent4d416952014-08-10 14:07:09 -07005774 snprintf(buffer, SIZE, " ID: %d\n", mId);
5775 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005776 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5777 result.append(buffer);
5778 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5779 result.append(buffer);
5780 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5781 result.append(buffer);
5782 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5783 result.append(buffer);
5784 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5785 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005786 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5787 result.append(buffer);
5788
Eric Laurente552edb2014-03-10 17:42:56 -07005789 write(fd, result.string(), result.size());
5790
5791 return NO_ERROR;
5792}
5793
5794// --- StreamDescriptor class implementation
5795
Eric Laurente0720872014-03-11 09:30:41 -07005796AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005797 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5798{
5799 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5800}
5801
Eric Laurente0720872014-03-11 09:30:41 -07005802int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005803{
Eric Laurente0720872014-03-11 09:30:41 -07005804 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005805 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5806 if (mIndexCur.indexOfKey(device) < 0) {
5807 device = AUDIO_DEVICE_OUT_DEFAULT;
5808 }
5809 return mIndexCur.valueFor(device);
5810}
5811
Eric Laurente0720872014-03-11 09:30:41 -07005812void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005813{
5814 const size_t SIZE = 256;
5815 char buffer[SIZE];
5816 String8 result;
5817
5818 snprintf(buffer, SIZE, "%s %02d %02d ",
5819 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5820 result.append(buffer);
5821 for (size_t i = 0; i < mIndexCur.size(); i++) {
5822 snprintf(buffer, SIZE, "%04x : %02d, ",
5823 mIndexCur.keyAt(i),
5824 mIndexCur.valueAt(i));
5825 result.append(buffer);
5826 }
5827 result.append("\n");
5828
5829 write(fd, result.string(), result.size());
5830}
5831
5832// --- EffectDescriptor class implementation
5833
Eric Laurente0720872014-03-11 09:30:41 -07005834status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005835{
5836 const size_t SIZE = 256;
5837 char buffer[SIZE];
5838 String8 result;
5839
5840 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5841 result.append(buffer);
5842 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5843 result.append(buffer);
5844 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5845 result.append(buffer);
5846 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5847 result.append(buffer);
5848 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5849 result.append(buffer);
5850 write(fd, result.string(), result.size());
5851
5852 return NO_ERROR;
5853}
5854
Eric Laurent1c333e22014-05-20 10:48:17 -07005855// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005856
Eric Laurente0720872014-03-11 09:30:41 -07005857AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005858 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5859 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005860{
5861}
5862
Eric Laurente0720872014-03-11 09:30:41 -07005863AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005864{
5865 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005866 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005867 }
5868 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005869 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005870 }
5871 free((void *)mName);
5872}
5873
Eric Laurent1afeecb2014-05-14 08:52:28 -07005874status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5875{
5876 cnode *node = root->first_child;
5877
5878 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5879
5880 while (node) {
5881 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5882 profile->loadSamplingRates((char *)node->value);
5883 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5884 profile->loadFormats((char *)node->value);
5885 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5886 profile->loadInChannels((char *)node->value);
5887 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5888 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5889 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005890 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5891 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005892 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5893 profile->loadGains(node);
5894 }
5895 node = node->next;
5896 }
5897 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5898 "loadInput() invalid supported devices");
5899 ALOGW_IF(profile->mChannelMasks.size() == 0,
5900 "loadInput() invalid supported channel masks");
5901 ALOGW_IF(profile->mSamplingRates.size() == 0,
5902 "loadInput() invalid supported sampling rates");
5903 ALOGW_IF(profile->mFormats.size() == 0,
5904 "loadInput() invalid supported formats");
5905 if (!profile->mSupportedDevices.isEmpty() &&
5906 (profile->mChannelMasks.size() != 0) &&
5907 (profile->mSamplingRates.size() != 0) &&
5908 (profile->mFormats.size() != 0)) {
5909
5910 ALOGV("loadInput() adding input Supported Devices %04x",
5911 profile->mSupportedDevices.types());
5912
5913 mInputProfiles.add(profile);
5914 return NO_ERROR;
5915 } else {
5916 return BAD_VALUE;
5917 }
5918}
5919
5920status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5921{
5922 cnode *node = root->first_child;
5923
5924 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5925
5926 while (node) {
5927 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5928 profile->loadSamplingRates((char *)node->value);
5929 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5930 profile->loadFormats((char *)node->value);
5931 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5932 profile->loadOutChannels((char *)node->value);
5933 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5934 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5935 mDeclaredDevices);
5936 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005937 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005938 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5939 profile->loadGains(node);
5940 }
5941 node = node->next;
5942 }
5943 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5944 "loadOutput() invalid supported devices");
5945 ALOGW_IF(profile->mChannelMasks.size() == 0,
5946 "loadOutput() invalid supported channel masks");
5947 ALOGW_IF(profile->mSamplingRates.size() == 0,
5948 "loadOutput() invalid supported sampling rates");
5949 ALOGW_IF(profile->mFormats.size() == 0,
5950 "loadOutput() invalid supported formats");
5951 if (!profile->mSupportedDevices.isEmpty() &&
5952 (profile->mChannelMasks.size() != 0) &&
5953 (profile->mSamplingRates.size() != 0) &&
5954 (profile->mFormats.size() != 0)) {
5955
5956 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5957 profile->mSupportedDevices.types(), profile->mFlags);
5958
5959 mOutputProfiles.add(profile);
5960 return NO_ERROR;
5961 } else {
5962 return BAD_VALUE;
5963 }
5964}
5965
5966status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5967{
5968 cnode *node = root->first_child;
5969
5970 audio_devices_t type = AUDIO_DEVICE_NONE;
5971 while (node) {
5972 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5973 type = parseDeviceNames((char *)node->value);
5974 break;
5975 }
5976 node = node->next;
5977 }
5978 if (type == AUDIO_DEVICE_NONE ||
5979 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5980 ALOGW("loadDevice() bad type %08x", type);
5981 return BAD_VALUE;
5982 }
5983 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5984 deviceDesc->mModule = this;
5985
5986 node = root->first_child;
5987 while (node) {
5988 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5989 deviceDesc->mAddress = String8((char *)node->value);
5990 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5991 if (audio_is_input_device(type)) {
5992 deviceDesc->loadInChannels((char *)node->value);
5993 } else {
5994 deviceDesc->loadOutChannels((char *)node->value);
5995 }
5996 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5997 deviceDesc->loadGains(node);
5998 }
5999 node = node->next;
6000 }
6001
6002 ALOGV("loadDevice() adding device name %s type %08x address %s",
6003 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6004
6005 mDeclaredDevices.add(deviceDesc);
6006
6007 return NO_ERROR;
6008}
6009
Eric Laurente0720872014-03-11 09:30:41 -07006010void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006011{
6012 const size_t SIZE = 256;
6013 char buffer[SIZE];
6014 String8 result;
6015
6016 snprintf(buffer, SIZE, " - name: %s\n", mName);
6017 result.append(buffer);
6018 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6019 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006020 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6021 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006022 write(fd, result.string(), result.size());
6023 if (mOutputProfiles.size()) {
6024 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6025 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006026 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006027 write(fd, buffer, strlen(buffer));
6028 mOutputProfiles[i]->dump(fd);
6029 }
6030 }
6031 if (mInputProfiles.size()) {
6032 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6033 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006034 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006035 write(fd, buffer, strlen(buffer));
6036 mInputProfiles[i]->dump(fd);
6037 }
6038 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006039 if (mDeclaredDevices.size()) {
6040 write(fd, " - devices:\n", strlen(" - devices:\n"));
6041 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6042 mDeclaredDevices[i]->dump(fd, 4, i);
6043 }
6044 }
Eric Laurente552edb2014-03-10 17:42:56 -07006045}
6046
Eric Laurent1c333e22014-05-20 10:48:17 -07006047// --- AudioPort class implementation
6048
Eric Laurenta121f902014-06-03 13:32:54 -07006049
6050AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6051 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006052 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006053{
6054 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6055 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6056}
6057
Eric Laurent1c333e22014-05-20 10:48:17 -07006058void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6059{
6060 port->role = mRole;
6061 port->type = mType;
6062 unsigned int i;
6063 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006064 if (mSamplingRates[i] != 0) {
6065 port->sample_rates[i] = mSamplingRates[i];
6066 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006067 }
6068 port->num_sample_rates = i;
6069 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006070 if (mChannelMasks[i] != 0) {
6071 port->channel_masks[i] = mChannelMasks[i];
6072 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006073 }
6074 port->num_channel_masks = i;
6075 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006076 if (mFormats[i] != 0) {
6077 port->formats[i] = mFormats[i];
6078 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006079 }
6080 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006081
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006082 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006083
6084 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6085 port->gains[i] = mGains[i]->mGain;
6086 }
6087 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006088}
6089
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006090void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6091 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6092 const uint32_t rate = port->mSamplingRates.itemAt(k);
6093 if (rate != 0) { // skip "dynamic" rates
6094 bool hasRate = false;
6095 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6096 if (rate == mSamplingRates.itemAt(l)) {
6097 hasRate = true;
6098 break;
6099 }
6100 }
6101 if (!hasRate) { // never import a sampling rate twice
6102 mSamplingRates.add(rate);
6103 }
6104 }
6105 }
6106 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6107 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6108 if (mask != 0) { // skip "dynamic" masks
6109 bool hasMask = false;
6110 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6111 if (mask == mChannelMasks.itemAt(l)) {
6112 hasMask = true;
6113 break;
6114 }
6115 }
6116 if (!hasMask) { // never import a channel mask twice
6117 mChannelMasks.add(mask);
6118 }
6119 }
6120 }
6121 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6122 const audio_format_t format = port->mFormats.itemAt(k);
6123 if (format != 0) { // skip "dynamic" formats
6124 bool hasFormat = false;
6125 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6126 if (format == mFormats.itemAt(l)) {
6127 hasFormat = true;
6128 break;
6129 }
6130 }
6131 if (!hasFormat) { // never import a channel mask twice
6132 mFormats.add(format);
6133 }
6134 }
6135 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006136 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6137 sp<AudioGain> gain = port->mGains.itemAt(k);
6138 if (gain != 0) {
6139 bool hasGain = false;
6140 for (size_t l = 0 ; l < mGains.size() ; l++) {
6141 if (gain == mGains.itemAt(l)) {
6142 hasGain = true;
6143 break;
6144 }
6145 }
6146 if (!hasGain) { // never import a gain twice
6147 mGains.add(gain);
6148 }
6149 }
6150 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006151}
6152
6153void AudioPolicyManager::AudioPort::clearCapabilities() {
6154 mChannelMasks.clear();
6155 mFormats.clear();
6156 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006157 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006158}
Eric Laurent1c333e22014-05-20 10:48:17 -07006159
6160void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6161{
6162 char *str = strtok(name, "|");
6163
6164 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6165 // rates should be read from the output stream after it is opened for the first time
6166 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6167 mSamplingRates.add(0);
6168 return;
6169 }
6170
6171 while (str != NULL) {
6172 uint32_t rate = atoi(str);
6173 if (rate != 0) {
6174 ALOGV("loadSamplingRates() adding rate %d", rate);
6175 mSamplingRates.add(rate);
6176 }
6177 str = strtok(NULL, "|");
6178 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006179}
6180
6181void AudioPolicyManager::AudioPort::loadFormats(char *name)
6182{
6183 char *str = strtok(name, "|");
6184
6185 // by convention, "0' in the first entry in mFormats indicates the supported formats
6186 // should be read from the output stream after it is opened for the first time
6187 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6188 mFormats.add(AUDIO_FORMAT_DEFAULT);
6189 return;
6190 }
6191
6192 while (str != NULL) {
6193 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6194 ARRAY_SIZE(sFormatNameToEnumTable),
6195 str);
6196 if (format != AUDIO_FORMAT_DEFAULT) {
6197 mFormats.add(format);
6198 }
6199 str = strtok(NULL, "|");
6200 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006201}
6202
6203void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6204{
6205 const char *str = strtok(name, "|");
6206
6207 ALOGV("loadInChannels() %s", name);
6208
6209 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6210 mChannelMasks.add(0);
6211 return;
6212 }
6213
6214 while (str != NULL) {
6215 audio_channel_mask_t channelMask =
6216 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6217 ARRAY_SIZE(sInChannelsNameToEnumTable),
6218 str);
6219 if (channelMask != 0) {
6220 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6221 mChannelMasks.add(channelMask);
6222 }
6223 str = strtok(NULL, "|");
6224 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006225}
6226
6227void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6228{
6229 const char *str = strtok(name, "|");
6230
6231 ALOGV("loadOutChannels() %s", name);
6232
6233 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6234 // masks should be read from the output stream after it is opened for the first time
6235 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6236 mChannelMasks.add(0);
6237 return;
6238 }
6239
6240 while (str != NULL) {
6241 audio_channel_mask_t channelMask =
6242 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6243 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6244 str);
6245 if (channelMask != 0) {
6246 mChannelMasks.add(channelMask);
6247 }
6248 str = strtok(NULL, "|");
6249 }
6250 return;
6251}
6252
Eric Laurent1afeecb2014-05-14 08:52:28 -07006253audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6254{
6255 const char *str = strtok(name, "|");
6256
6257 ALOGV("loadGainMode() %s", name);
6258 audio_gain_mode_t mode = 0;
6259 while (str != NULL) {
6260 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6261 ARRAY_SIZE(sGainModeNameToEnumTable),
6262 str);
6263 str = strtok(NULL, "|");
6264 }
6265 return mode;
6266}
6267
Eric Laurenta121f902014-06-03 13:32:54 -07006268void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006269{
6270 cnode *node = root->first_child;
6271
Eric Laurenta121f902014-06-03 13:32:54 -07006272 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006273
6274 while (node) {
6275 if (strcmp(node->name, GAIN_MODE) == 0) {
6276 gain->mGain.mode = loadGainMode((char *)node->value);
6277 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006278 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006279 gain->mGain.channel_mask =
6280 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6281 ARRAY_SIZE(sInChannelsNameToEnumTable),
6282 (char *)node->value);
6283 } else {
6284 gain->mGain.channel_mask =
6285 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6286 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6287 (char *)node->value);
6288 }
6289 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6290 gain->mGain.min_value = atoi((char *)node->value);
6291 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6292 gain->mGain.max_value = atoi((char *)node->value);
6293 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6294 gain->mGain.default_value = atoi((char *)node->value);
6295 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6296 gain->mGain.step_value = atoi((char *)node->value);
6297 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6298 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6299 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6300 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6301 }
6302 node = node->next;
6303 }
6304
6305 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6306 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6307
6308 if (gain->mGain.mode == 0) {
6309 return;
6310 }
6311 mGains.add(gain);
6312}
6313
6314void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6315{
6316 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006317 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006318 while (node) {
6319 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006320 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006321 node = node->next;
6322 }
6323}
6324
Glenn Kastencbd48022014-07-24 13:46:44 -07006325status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006326{
6327 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6328 if (mSamplingRates[i] == samplingRate) {
6329 return NO_ERROR;
6330 }
6331 }
6332 return BAD_VALUE;
6333}
6334
Glenn Kastencbd48022014-07-24 13:46:44 -07006335status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6336 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006337{
Glenn Kastencbd48022014-07-24 13:46:44 -07006338 // Search for the closest supported sampling rate that is above (preferred)
6339 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6340 // The sampling rates do not need to be sorted in ascending order.
6341 ssize_t maxBelow = -1;
6342 ssize_t minAbove = -1;
6343 uint32_t candidate;
6344 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6345 candidate = mSamplingRates[i];
6346 if (candidate == samplingRate) {
6347 if (updatedSamplingRate != NULL) {
6348 *updatedSamplingRate = candidate;
6349 }
6350 return NO_ERROR;
6351 }
6352 // candidate < desired
6353 if (candidate < samplingRate) {
6354 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6355 maxBelow = i;
6356 }
6357 // candidate > desired
6358 } else {
6359 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6360 minAbove = i;
6361 }
6362 }
6363 }
6364 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6365 // TODO Move these assumptions out.
6366 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6367 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6368 // due to approximation by an int32_t of the
6369 // phase increments
6370 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6371 if (minAbove >= 0) {
6372 candidate = mSamplingRates[minAbove];
6373 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6374 if (updatedSamplingRate != NULL) {
6375 *updatedSamplingRate = candidate;
6376 }
6377 return NO_ERROR;
6378 }
6379 }
6380 // But if we have to up-sample from a lower sampling rate, that's OK.
6381 if (maxBelow >= 0) {
6382 candidate = mSamplingRates[maxBelow];
6383 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6384 if (updatedSamplingRate != NULL) {
6385 *updatedSamplingRate = candidate;
6386 }
6387 return NO_ERROR;
6388 }
6389 }
6390 // leave updatedSamplingRate unmodified
6391 return BAD_VALUE;
6392}
6393
6394status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6395{
6396 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006397 if (mChannelMasks[i] == channelMask) {
6398 return NO_ERROR;
6399 }
6400 }
6401 return BAD_VALUE;
6402}
6403
Glenn Kastencbd48022014-07-24 13:46:44 -07006404status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6405 const
6406{
6407 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6408 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6409 // FIXME Does not handle multi-channel automatic conversions yet
6410 audio_channel_mask_t supported = mChannelMasks[i];
6411 if (supported == channelMask) {
6412 return NO_ERROR;
6413 }
6414 if (isRecordThread) {
6415 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6416 // FIXME Abstract this out to a table.
6417 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6418 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6419 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6420 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6421 return NO_ERROR;
6422 }
6423 }
6424 }
6425 return BAD_VALUE;
6426}
6427
Eric Laurenta121f902014-06-03 13:32:54 -07006428status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6429{
6430 for (size_t i = 0; i < mFormats.size(); i ++) {
6431 if (mFormats[i] == format) {
6432 return NO_ERROR;
6433 }
6434 }
6435 return BAD_VALUE;
6436}
6437
Eric Laurent1e693b52014-07-09 15:03:28 -07006438
6439uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6440{
6441 // special case for uninitialized dynamic profile
6442 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6443 return 0;
6444 }
6445
Eric Laurent828bcff2014-09-07 12:26:06 -07006446 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6447 // channel count / sampling rate combination chosen will be supported by the connected
6448 // sink
6449 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6450 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6451 uint32_t samplingRate = UINT_MAX;
6452 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6453 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6454 samplingRate = mSamplingRates[i];
6455 }
6456 }
6457 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6458 }
6459
Eric Laurent1e693b52014-07-09 15:03:28 -07006460 uint32_t samplingRate = 0;
6461 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6462
6463 // For mixed output and inputs, use max mixer sampling rates. Do not
6464 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006465 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006466 maxRate = UINT_MAX;
6467 }
6468 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6469 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6470 samplingRate = mSamplingRates[i];
6471 }
6472 }
6473 return samplingRate;
6474}
6475
6476audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6477{
6478 // special case for uninitialized dynamic profile
6479 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6480 return AUDIO_CHANNEL_NONE;
6481 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006482 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006483
6484 // For direct outputs, pick minimum channel count: this helps ensuring that the
6485 // channel count / sampling rate combination chosen will be supported by the connected
6486 // sink
6487 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6488 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6489 uint32_t channelCount = UINT_MAX;
6490 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6491 uint32_t cnlCount;
6492 if (mUseInChannelMask) {
6493 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6494 } else {
6495 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6496 }
6497 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6498 channelMask = mChannelMasks[i];
6499 channelCount = cnlCount;
6500 }
6501 }
6502 return channelMask;
6503 }
6504
Eric Laurent1e693b52014-07-09 15:03:28 -07006505 uint32_t channelCount = 0;
6506 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6507
6508 // For mixed output and inputs, use max mixer channel count. Do not
6509 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006510 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006511 maxCount = UINT_MAX;
6512 }
6513 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6514 uint32_t cnlCount;
6515 if (mUseInChannelMask) {
6516 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6517 } else {
6518 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6519 }
6520 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6521 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006522 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006523 }
6524 }
6525 return channelMask;
6526}
6527
Andy Hung9a605382014-07-28 16:16:31 -07006528/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006529const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6530 AUDIO_FORMAT_DEFAULT,
6531 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006532 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006533 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006534 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006535 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006536};
6537
6538int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6539 audio_format_t format2)
6540{
6541 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6542 // compressed format and better than any PCM format. This is by design of pickFormat()
6543 if (!audio_is_linear_pcm(format1)) {
6544 if (!audio_is_linear_pcm(format2)) {
6545 return 0;
6546 }
6547 return 1;
6548 }
6549 if (!audio_is_linear_pcm(format2)) {
6550 return -1;
6551 }
6552
6553 int index1 = -1, index2 = -1;
6554 for (size_t i = 0;
6555 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6556 i ++) {
6557 if (sPcmFormatCompareTable[i] == format1) {
6558 index1 = i;
6559 }
6560 if (sPcmFormatCompareTable[i] == format2) {
6561 index2 = i;
6562 }
6563 }
6564 // format1 not found => index1 < 0 => format2 > format1
6565 // format2 not found => index2 < 0 => format2 < format1
6566 return index1 - index2;
6567}
6568
6569audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6570{
6571 // special case for uninitialized dynamic profile
6572 if (mFormats.size() == 1 && mFormats[0] == 0) {
6573 return AUDIO_FORMAT_DEFAULT;
6574 }
6575
6576 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006577 audio_format_t bestFormat =
6578 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6579 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006580 // For mixed output and inputs, use best mixer output format. Do not
6581 // limit format otherwise
6582 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6583 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006584 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006585 bestFormat = AUDIO_FORMAT_INVALID;
6586 }
6587
6588 for (size_t i = 0; i < mFormats.size(); i ++) {
6589 if ((compareFormats(mFormats[i], format) > 0) &&
6590 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6591 format = mFormats[i];
6592 }
6593 }
6594 return format;
6595}
6596
Eric Laurenta121f902014-06-03 13:32:54 -07006597status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6598 int index) const
6599{
6600 if (index < 0 || (size_t)index >= mGains.size()) {
6601 return BAD_VALUE;
6602 }
6603 return mGains[index]->checkConfig(gainConfig);
6604}
6605
Eric Laurent1afeecb2014-05-14 08:52:28 -07006606void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6607{
6608 const size_t SIZE = 256;
6609 char buffer[SIZE];
6610 String8 result;
6611
6612 if (mName.size() != 0) {
6613 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6614 result.append(buffer);
6615 }
6616
6617 if (mSamplingRates.size() != 0) {
6618 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6619 result.append(buffer);
6620 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006621 if (i == 0 && mSamplingRates[i] == 0) {
6622 snprintf(buffer, SIZE, "Dynamic");
6623 } else {
6624 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6625 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006626 result.append(buffer);
6627 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6628 }
6629 result.append("\n");
6630 }
6631
6632 if (mChannelMasks.size() != 0) {
6633 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6634 result.append(buffer);
6635 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006636 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6637
6638 if (i == 0 && mChannelMasks[i] == 0) {
6639 snprintf(buffer, SIZE, "Dynamic");
6640 } else {
6641 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6642 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006643 result.append(buffer);
6644 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6645 }
6646 result.append("\n");
6647 }
6648
6649 if (mFormats.size() != 0) {
6650 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6651 result.append(buffer);
6652 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006653 const char *formatStr = enumToString(sFormatNameToEnumTable,
6654 ARRAY_SIZE(sFormatNameToEnumTable),
6655 mFormats[i]);
6656 if (i == 0 && strcmp(formatStr, "") == 0) {
6657 snprintf(buffer, SIZE, "Dynamic");
6658 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006659 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006660 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006661 result.append(buffer);
6662 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6663 }
6664 result.append("\n");
6665 }
6666 write(fd, result.string(), result.size());
6667 if (mGains.size() != 0) {
6668 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6669 write(fd, buffer, strlen(buffer) + 1);
6670 result.append(buffer);
6671 for (size_t i = 0; i < mGains.size(); i++) {
6672 mGains[i]->dump(fd, spaces + 2, i);
6673 }
6674 }
6675}
6676
6677// --- AudioGain class implementation
6678
Eric Laurenta121f902014-06-03 13:32:54 -07006679AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006680{
Eric Laurenta121f902014-06-03 13:32:54 -07006681 mIndex = index;
6682 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006683 memset(&mGain, 0, sizeof(struct audio_gain));
6684}
6685
Eric Laurenta121f902014-06-03 13:32:54 -07006686void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6687{
6688 config->index = mIndex;
6689 config->mode = mGain.mode;
6690 config->channel_mask = mGain.channel_mask;
6691 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6692 config->values[0] = mGain.default_value;
6693 } else {
6694 uint32_t numValues;
6695 if (mUseInChannelMask) {
6696 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6697 } else {
6698 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6699 }
6700 for (size_t i = 0; i < numValues; i++) {
6701 config->values[i] = mGain.default_value;
6702 }
6703 }
6704 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6705 config->ramp_duration_ms = mGain.min_ramp_ms;
6706 }
6707}
6708
6709status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6710{
6711 if ((config->mode & ~mGain.mode) != 0) {
6712 return BAD_VALUE;
6713 }
6714 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6715 if ((config->values[0] < mGain.min_value) ||
6716 (config->values[0] > mGain.max_value)) {
6717 return BAD_VALUE;
6718 }
6719 } else {
6720 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6721 return BAD_VALUE;
6722 }
6723 uint32_t numValues;
6724 if (mUseInChannelMask) {
6725 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6726 } else {
6727 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6728 }
6729 for (size_t i = 0; i < numValues; i++) {
6730 if ((config->values[i] < mGain.min_value) ||
6731 (config->values[i] > mGain.max_value)) {
6732 return BAD_VALUE;
6733 }
6734 }
6735 }
6736 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6737 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6738 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6739 return BAD_VALUE;
6740 }
6741 }
6742 return NO_ERROR;
6743}
6744
Eric Laurent1afeecb2014-05-14 08:52:28 -07006745void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6746{
6747 const size_t SIZE = 256;
6748 char buffer[SIZE];
6749 String8 result;
6750
6751 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6752 result.append(buffer);
6753 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6754 result.append(buffer);
6755 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6756 result.append(buffer);
6757 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6758 result.append(buffer);
6759 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6760 result.append(buffer);
6761 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6762 result.append(buffer);
6763 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6764 result.append(buffer);
6765 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6766 result.append(buffer);
6767 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6768 result.append(buffer);
6769
6770 write(fd, result.string(), result.size());
6771}
6772
Eric Laurent1f2f2232014-06-02 12:01:23 -07006773// --- AudioPortConfig class implementation
6774
6775AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6776{
6777 mSamplingRate = 0;
6778 mChannelMask = AUDIO_CHANNEL_NONE;
6779 mFormat = AUDIO_FORMAT_INVALID;
6780 mGain.index = -1;
6781}
6782
Eric Laurenta121f902014-06-03 13:32:54 -07006783status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6784 const struct audio_port_config *config,
6785 struct audio_port_config *backupConfig)
6786{
6787 struct audio_port_config localBackupConfig;
6788 status_t status = NO_ERROR;
6789
6790 localBackupConfig.config_mask = config->config_mask;
6791 toAudioPortConfig(&localBackupConfig);
6792
Marco Nelissen961ec212014-08-25 15:58:39 -07006793 sp<AudioPort> audioport = getAudioPort();
6794 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006795 status = NO_INIT;
6796 goto exit;
6797 }
6798 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006799 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006800 if (status != NO_ERROR) {
6801 goto exit;
6802 }
6803 mSamplingRate = config->sample_rate;
6804 }
6805 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006806 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006807 if (status != NO_ERROR) {
6808 goto exit;
6809 }
6810 mChannelMask = config->channel_mask;
6811 }
6812 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006813 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006814 if (status != NO_ERROR) {
6815 goto exit;
6816 }
6817 mFormat = config->format;
6818 }
6819 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006820 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006821 if (status != NO_ERROR) {
6822 goto exit;
6823 }
6824 mGain = config->gain;
6825 }
6826
6827exit:
6828 if (status != NO_ERROR) {
6829 applyAudioPortConfig(&localBackupConfig);
6830 }
6831 if (backupConfig != NULL) {
6832 *backupConfig = localBackupConfig;
6833 }
6834 return status;
6835}
6836
Eric Laurent1f2f2232014-06-02 12:01:23 -07006837void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6838 struct audio_port_config *dstConfig,
6839 const struct audio_port_config *srcConfig) const
6840{
6841 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6842 dstConfig->sample_rate = mSamplingRate;
6843 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6844 dstConfig->sample_rate = srcConfig->sample_rate;
6845 }
6846 } else {
6847 dstConfig->sample_rate = 0;
6848 }
6849 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6850 dstConfig->channel_mask = mChannelMask;
6851 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6852 dstConfig->channel_mask = srcConfig->channel_mask;
6853 }
6854 } else {
6855 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6856 }
6857 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6858 dstConfig->format = mFormat;
6859 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6860 dstConfig->format = srcConfig->format;
6861 }
6862 } else {
6863 dstConfig->format = AUDIO_FORMAT_INVALID;
6864 }
6865 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6866 dstConfig->gain = mGain;
6867 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6868 dstConfig->gain = srcConfig->gain;
6869 }
6870 } else {
6871 dstConfig->gain.index = -1;
6872 }
6873 if (dstConfig->gain.index != -1) {
6874 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6875 } else {
6876 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6877 }
6878}
6879
Eric Laurent1c333e22014-05-20 10:48:17 -07006880// --- IOProfile class implementation
6881
Eric Laurent1afeecb2014-05-14 08:52:28 -07006882AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006883 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006884 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006885{
6886}
6887
Eric Laurente0720872014-03-11 09:30:41 -07006888AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006889{
6890}
6891
6892// checks if the IO profile is compatible with specified parameters.
6893// Sampling rate, format and channel mask must be specified in order to
6894// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006895bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006896 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006897 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006898 audio_format_t format,
6899 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006900 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006901{
Glenn Kastencbd48022014-07-24 13:46:44 -07006902 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6903 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6904 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006905
Glenn Kastencbd48022014-07-24 13:46:44 -07006906 if ((mSupportedDevices.types() & device) != device) {
6907 return false;
6908 }
6909
6910 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006911 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006912 }
6913 uint32_t myUpdatedSamplingRate = samplingRate;
6914 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006915 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006916 }
6917 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6918 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006919 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006920 }
6921
6922 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6923 return false;
6924 }
6925
6926 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6927 checkExactChannelMask(channelMask) != NO_ERROR)) {
6928 return false;
6929 }
6930 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6931 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6932 return false;
6933 }
6934
6935 if (isPlaybackThread && (mFlags & flags) != flags) {
6936 return false;
6937 }
6938 // The only input flag that is allowed to be different is the fast flag.
6939 // An existing fast stream is compatible with a normal track request.
6940 // An existing normal stream is compatible with a fast track request,
6941 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006942 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006943 ~AUDIO_INPUT_FLAG_FAST)) {
6944 return false;
6945 }
6946
6947 if (updatedSamplingRate != NULL) {
6948 *updatedSamplingRate = myUpdatedSamplingRate;
6949 }
6950 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006951}
6952
Eric Laurente0720872014-03-11 09:30:41 -07006953void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006954{
6955 const size_t SIZE = 256;
6956 char buffer[SIZE];
6957 String8 result;
6958
Eric Laurent1afeecb2014-05-14 08:52:28 -07006959 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006960
Eric Laurente552edb2014-03-10 17:42:56 -07006961 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6962 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006963 snprintf(buffer, SIZE, " - devices:\n");
6964 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006965 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006966 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6967 mSupportedDevices[i]->dump(fd, 6, i);
6968 }
Eric Laurente552edb2014-03-10 17:42:56 -07006969}
6970
Eric Laurentd4692962014-05-05 18:13:44 -07006971void AudioPolicyManager::IOProfile::log()
6972{
6973 const size_t SIZE = 256;
6974 char buffer[SIZE];
6975 String8 result;
6976
6977 ALOGV(" - sampling rates: ");
6978 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6979 ALOGV(" %d", mSamplingRates[i]);
6980 }
6981
6982 ALOGV(" - channel masks: ");
6983 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6984 ALOGV(" 0x%04x", mChannelMasks[i]);
6985 }
6986
6987 ALOGV(" - formats: ");
6988 for (size_t i = 0; i < mFormats.size(); i++) {
6989 ALOGV(" 0x%08x", mFormats[i]);
6990 }
6991
6992 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6993 ALOGV(" - flags: 0x%04x\n", mFlags);
6994}
6995
6996
Eric Laurent3a4311c2014-03-17 12:00:47 -07006997// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006998
Eric Laurent1f2f2232014-06-02 12:01:23 -07006999
7000AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7001 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7002 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7003 AUDIO_PORT_ROLE_SOURCE,
7004 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007005 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007006{
Eric Laurenta121f902014-06-03 13:32:54 -07007007 if (mGains.size() > 0) {
7008 mGains[0]->getDefaultConfig(&mGain);
7009 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07007010}
7011
Eric Laurent3a4311c2014-03-17 12:00:47 -07007012bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007013{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007014 // Devices are considered equal if they:
7015 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7016 // - have the same address or one device does not specify the address
7017 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007018 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007019 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007020 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007021 mChannelMask == other->mChannelMask);
7022}
7023
7024void AudioPolicyManager::DeviceVector::refreshTypes()
7025{
Eric Laurent1c333e22014-05-20 10:48:17 -07007026 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007027 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007028 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007029 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007030 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007031}
7032
7033ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7034{
7035 for(size_t i = 0; i < size(); i++) {
7036 if (item->equals(itemAt(i))) {
7037 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007038 }
7039 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007040 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007041}
7042
Eric Laurent3a4311c2014-03-17 12:00:47 -07007043ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007044{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007045 ssize_t ret = indexOf(item);
7046
7047 if (ret < 0) {
7048 ret = SortedVector::add(item);
7049 if (ret >= 0) {
7050 refreshTypes();
7051 }
7052 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007053 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007054 ret = -1;
7055 }
7056 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007057}
7058
Eric Laurent3a4311c2014-03-17 12:00:47 -07007059ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7060{
7061 size_t i;
7062 ssize_t ret = indexOf(item);
7063
7064 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007065 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007066 } else {
7067 ret = SortedVector::removeAt(ret);
7068 if (ret >= 0) {
7069 refreshTypes();
7070 }
7071 }
7072 return ret;
7073}
7074
7075void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7076{
7077 DeviceVector deviceList;
7078
7079 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7080 types &= ~role_bit;
7081
7082 while (types) {
7083 uint32_t i = 31 - __builtin_clz(types);
7084 uint32_t type = 1 << i;
7085 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007086 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007087 }
7088}
7089
Eric Laurent1afeecb2014-05-14 08:52:28 -07007090void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7091 const DeviceVector& declaredDevices)
7092{
7093 char *devName = strtok(name, "|");
7094 while (devName != NULL) {
7095 if (strlen(devName) != 0) {
7096 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7097 ARRAY_SIZE(sDeviceNameToEnumTable),
7098 devName);
7099 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007100 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
7101 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
7102 dev->mAddress = String8("0");
7103 }
7104 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007105 } else {
7106 sp<DeviceDescriptor> deviceDesc =
7107 declaredDevices.getDeviceFromName(String8(devName));
7108 if (deviceDesc != 0) {
7109 add(deviceDesc);
7110 }
7111 }
7112 }
7113 devName = strtok(NULL, "|");
7114 }
7115}
7116
Eric Laurent1c333e22014-05-20 10:48:17 -07007117sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7118 audio_devices_t type, String8 address) const
7119{
7120 sp<DeviceDescriptor> device;
7121 for (size_t i = 0; i < size(); i++) {
7122 if (itemAt(i)->mDeviceType == type) {
7123 device = itemAt(i);
7124 if (itemAt(i)->mAddress = address) {
7125 break;
7126 }
7127 }
7128 }
7129 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
7130 type, address.string(), device.get());
7131 return device;
7132}
7133
Eric Laurent6a94d692014-05-20 11:18:06 -07007134sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7135 audio_port_handle_t id) const
7136{
7137 sp<DeviceDescriptor> device;
7138 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007139 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007140 if (itemAt(i)->mId == id) {
7141 device = itemAt(i);
7142 break;
7143 }
7144 }
7145 return device;
7146}
7147
Eric Laurent1c333e22014-05-20 10:48:17 -07007148AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7149 audio_devices_t type) const
7150{
7151 DeviceVector devices;
7152 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7153 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7154 devices.add(itemAt(i));
7155 type &= ~itemAt(i)->mDeviceType;
7156 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7157 itemAt(i)->mDeviceType, itemAt(i).get());
7158 }
7159 }
7160 return devices;
7161}
7162
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007163AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7164 audio_devices_t type, String8 address) const
7165{
7166 DeviceVector devices;
7167 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
7168 for (size_t i = 0; i < size(); i++) {
7169 //ALOGV(" at i=%d: device=%x, addr=%s",
7170 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
7171 if (itemAt(i)->mDeviceType == type) {
7172 if (itemAt(i)->mAddress == address) {
7173 //ALOGV(" found matching address %s", address.string());
7174 devices.add(itemAt(i));
7175 }
7176 }
7177 }
7178 return devices;
7179}
7180
Eric Laurent1afeecb2014-05-14 08:52:28 -07007181sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7182 const String8& name) const
7183{
7184 sp<DeviceDescriptor> device;
7185 for (size_t i = 0; i < size(); i++) {
7186 if (itemAt(i)->mName == name) {
7187 device = itemAt(i);
7188 break;
7189 }
7190 }
7191 return device;
7192}
7193
Eric Laurent6a94d692014-05-20 11:18:06 -07007194void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7195 struct audio_port_config *dstConfig,
7196 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007197{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007198 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7199 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007200 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007201 }
7202
7203 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7204
Eric Laurent6a94d692014-05-20 11:18:06 -07007205 dstConfig->id = mId;
7206 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007207 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007208 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007209 dstConfig->ext.device.type = mDeviceType;
7210 dstConfig->ext.device.hw_module = mModule->mHandle;
7211 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007212}
7213
7214void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7215{
Eric Laurent83b88082014-06-20 18:31:16 -07007216 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007217 AudioPort::toAudioPort(port);
7218 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007219 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007220 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007221 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007222 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7223}
7224
Eric Laurent1afeecb2014-05-14 08:52:28 -07007225status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007226{
7227 const size_t SIZE = 256;
7228 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007229 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007230
Eric Laurent1afeecb2014-05-14 08:52:28 -07007231 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7232 result.append(buffer);
7233 if (mId != 0) {
7234 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7235 result.append(buffer);
7236 }
7237 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7238 enumToString(sDeviceNameToEnumTable,
7239 ARRAY_SIZE(sDeviceNameToEnumTable),
7240 mDeviceType));
7241 result.append(buffer);
7242 if (mAddress.size() != 0) {
7243 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7244 result.append(buffer);
7245 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007246 write(fd, result.string(), result.size());
7247 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007248
7249 return NO_ERROR;
7250}
7251
Eric Laurent4d416952014-08-10 14:07:09 -07007252status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7253{
7254 const size_t SIZE = 256;
7255 char buffer[SIZE];
7256 String8 result;
7257
7258
7259 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7260 result.append(buffer);
7261 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7262 result.append(buffer);
7263 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7264 result.append(buffer);
7265 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7266 result.append(buffer);
7267 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7268 result.append(buffer);
7269 for (size_t i = 0; i < mPatch.num_sources; i++) {
7270 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7271 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7272 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7273 ARRAY_SIZE(sDeviceNameToEnumTable),
7274 mPatch.sources[i].ext.device.type));
7275 } else {
7276 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7277 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7278 }
7279 result.append(buffer);
7280 }
7281 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7282 result.append(buffer);
7283 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7284 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7285 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7286 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7287 ARRAY_SIZE(sDeviceNameToEnumTable),
7288 mPatch.sinks[i].ext.device.type));
7289 } else {
7290 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7291 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7292 }
7293 result.append(buffer);
7294 }
7295
7296 write(fd, result.string(), result.size());
7297 return NO_ERROR;
7298}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007299
7300// --- audio_policy.conf file parsing
7301
Eric Laurent5dbe4712014-09-19 19:04:57 -07007302uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007303{
7304 uint32_t flag = 0;
7305
7306 // it is OK to cast name to non const here as we are not going to use it after
7307 // strtok() modifies it
7308 char *flagName = strtok(name, "|");
7309 while (flagName != NULL) {
7310 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007311 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7312 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007313 flagName);
7314 }
7315 flagName = strtok(NULL, "|");
7316 }
7317 //force direct flag if offload flag is set: offloading implies a direct output stream
7318 // and all common behaviors are driven by checking only the direct flag
7319 // this should normally be set appropriately in the policy configuration file
7320 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7321 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7322 }
7323
Eric Laurent5dbe4712014-09-19 19:04:57 -07007324 return flag;
7325}
7326
7327uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7328{
7329 uint32_t flag = 0;
7330
7331 // it is OK to cast name to non const here as we are not going to use it after
7332 // strtok() modifies it
7333 char *flagName = strtok(name, "|");
7334 while (flagName != NULL) {
7335 if (strlen(flagName) != 0) {
7336 flag |= stringToEnum(sInputFlagNameToEnumTable,
7337 ARRAY_SIZE(sInputFlagNameToEnumTable),
7338 flagName);
7339 }
7340 flagName = strtok(NULL, "|");
7341 }
7342 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007343}
7344
Eric Laurente0720872014-03-11 09:30:41 -07007345audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007346{
7347 uint32_t device = 0;
7348
7349 char *devName = strtok(name, "|");
7350 while (devName != NULL) {
7351 if (strlen(devName) != 0) {
7352 device |= stringToEnum(sDeviceNameToEnumTable,
7353 ARRAY_SIZE(sDeviceNameToEnumTable),
7354 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007355 }
Eric Laurente552edb2014-03-10 17:42:56 -07007356 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007357 }
Eric Laurente552edb2014-03-10 17:42:56 -07007358 return device;
7359}
7360
Eric Laurente0720872014-03-11 09:30:41 -07007361void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007362{
Eric Laurente552edb2014-03-10 17:42:56 -07007363 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007364 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007365 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007366
Eric Laurent1afeecb2014-05-14 08:52:28 -07007367 node = config_find(root, DEVICES_TAG);
7368 if (node != NULL) {
7369 node = node->first_child;
7370 while (node) {
7371 ALOGV("loadHwModule() loading device %s", node->name);
7372 status_t tmpStatus = module->loadDevice(node);
7373 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7374 status = tmpStatus;
7375 }
7376 node = node->next;
7377 }
7378 }
7379 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007380 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007381 node = node->first_child;
7382 while (node) {
7383 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007384 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007385 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7386 status = tmpStatus;
7387 }
7388 node = node->next;
7389 }
7390 }
7391 node = config_find(root, INPUTS_TAG);
7392 if (node != NULL) {
7393 node = node->first_child;
7394 while (node) {
7395 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007396 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007397 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7398 status = tmpStatus;
7399 }
7400 node = node->next;
7401 }
7402 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007403 loadGlobalConfig(root, module);
7404
Eric Laurente552edb2014-03-10 17:42:56 -07007405 if (status == NO_ERROR) {
7406 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007407 }
7408}
7409
Eric Laurente0720872014-03-11 09:30:41 -07007410void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007411{
7412 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7413 if (node == NULL) {
7414 return;
7415 }
7416
7417 node = node->first_child;
7418 while (node) {
7419 ALOGV("loadHwModules() loading module %s", node->name);
7420 loadHwModule(node);
7421 node = node->next;
7422 }
7423}
7424
Eric Laurent1f2f2232014-06-02 12:01:23 -07007425void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007426{
7427 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007428
Eric Laurente552edb2014-03-10 17:42:56 -07007429 if (node == NULL) {
7430 return;
7431 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007432 DeviceVector declaredDevices;
7433 if (module != NULL) {
7434 declaredDevices = module->mDeclaredDevices;
7435 }
7436
Eric Laurente552edb2014-03-10 17:42:56 -07007437 node = node->first_child;
7438 while (node) {
7439 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007440 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7441 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007442 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7443 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007444 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007445 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007446 ARRAY_SIZE(sDeviceNameToEnumTable),
7447 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007448 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007449 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007450 } else {
7451 ALOGW("loadGlobalConfig() default device not specified");
7452 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007453 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007454 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007455 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7456 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007457 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007458 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7459 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7460 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007461 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7462 uint32_t major, minor;
7463 sscanf((char *)node->value, "%u.%u", &major, &minor);
7464 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7465 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7466 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007467 }
7468 node = node->next;
7469 }
7470}
7471
Eric Laurente0720872014-03-11 09:30:41 -07007472status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007473{
7474 cnode *root;
7475 char *data;
7476
7477 data = (char *)load_file(path, NULL);
7478 if (data == NULL) {
7479 return -ENODEV;
7480 }
7481 root = config_node("", "");
7482 config_load(root, data);
7483
Eric Laurente552edb2014-03-10 17:42:56 -07007484 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007485 // legacy audio_policy.conf files have one global_configuration section
7486 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007487 config_free(root);
7488 free(root);
7489 free(data);
7490
7491 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7492
7493 return NO_ERROR;
7494}
7495
Eric Laurente0720872014-03-11 09:30:41 -07007496void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007497{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007498 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007499 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007500 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7501 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007502 mAvailableOutputDevices.add(mDefaultOutputDevice);
7503 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007504
7505 module = new HwModule("primary");
7506
Eric Laurent1afeecb2014-05-14 08:52:28 -07007507 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007508 profile->mSamplingRates.add(44100);
7509 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7510 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007511 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007512 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7513 module->mOutputProfiles.add(profile);
7514
Eric Laurent1afeecb2014-05-14 08:52:28 -07007515 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007516 profile->mSamplingRates.add(8000);
7517 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7518 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007519 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007520 module->mInputProfiles.add(profile);
7521
7522 mHwModules.add(module);
7523}
7524
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007525audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7526{
7527 // flags to stream type mapping
7528 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7529 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7530 }
7531 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7532 return AUDIO_STREAM_BLUETOOTH_SCO;
7533 }
7534
7535 // usage to stream type mapping
7536 switch (attr->usage) {
7537 case AUDIO_USAGE_MEDIA:
7538 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007539 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7540 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007541 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007542 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7543 return AUDIO_STREAM_ALARM;
7544 }
7545 if (isStreamActive(AUDIO_STREAM_RING)) {
7546 return AUDIO_STREAM_RING;
7547 }
7548 if (isInCall()) {
7549 return AUDIO_STREAM_VOICE_CALL;
7550 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08007551 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007552 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7553 return AUDIO_STREAM_SYSTEM;
7554 case AUDIO_USAGE_VOICE_COMMUNICATION:
7555 return AUDIO_STREAM_VOICE_CALL;
7556
7557 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7558 return AUDIO_STREAM_DTMF;
7559
7560 case AUDIO_USAGE_ALARM:
7561 return AUDIO_STREAM_ALARM;
7562 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7563 return AUDIO_STREAM_RING;
7564
7565 case AUDIO_USAGE_NOTIFICATION:
7566 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7567 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7568 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7569 case AUDIO_USAGE_NOTIFICATION_EVENT:
7570 return AUDIO_STREAM_NOTIFICATION;
7571
7572 case AUDIO_USAGE_UNKNOWN:
7573 default:
7574 return AUDIO_STREAM_MUSIC;
7575 }
7576}
Eric Laurente83b55d2014-11-14 10:06:21 -08007577
7578bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
7579 // has flags that map to a strategy?
7580 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7581 return true;
7582 }
7583
7584 // has known usage?
7585 switch (paa->usage) {
7586 case AUDIO_USAGE_UNKNOWN:
7587 case AUDIO_USAGE_MEDIA:
7588 case AUDIO_USAGE_VOICE_COMMUNICATION:
7589 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7590 case AUDIO_USAGE_ALARM:
7591 case AUDIO_USAGE_NOTIFICATION:
7592 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7593 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7594 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7595 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7596 case AUDIO_USAGE_NOTIFICATION_EVENT:
7597 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7598 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7599 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7600 case AUDIO_USAGE_GAME:
7601 break;
7602 default:
7603 return false;
7604 }
7605 return true;
7606}
7607
Eric Laurente552edb2014-03-10 17:42:56 -07007608}; // namespace android