blob: b5a3d5b2264898038869a9e7810930b630910d87 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
Hochi Huang327cb702014-09-21 09:47:31 +080029#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
Eric Laurente552edb2014-03-10 17:42:56 -070030// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070047#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070048#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070049#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurent3b73df72014-03-11 09:06:29 -070051namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070052
53// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070054// Definitions for audio_policy.conf file parsing
55// ----------------------------------------------------------------------------
56
57struct StringToEnum {
58 const char *name;
59 uint32_t value;
60};
61
62#define STRING_TO_ENUM(string) { #string, string }
63#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64
65const StringToEnum sDeviceNameToEnumTable[] = {
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070069 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070081 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070087 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
91 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070092 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050093 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070094 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
98 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700108 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
110 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
111 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700112 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900113 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700114};
115
Eric Laurent5dbe4712014-09-19 19:04:57 -0700116const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700123 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700124};
125
Eric Laurent5dbe4712014-09-19 19:04:57 -0700126const StringToEnum sInputFlagNameToEnumTable[] = {
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
128 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
129};
130
Eric Laurent3a4311c2014-03-17 12:00:47 -0700131const StringToEnum sFormatNameToEnumTable[] = {
132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
137 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
138 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
149 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
152 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
153 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
154 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
155 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156};
157
158const StringToEnum sOutChannelsNameToEnumTable[] = {
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
163 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
164};
165
166const StringToEnum sInChannelsNameToEnumTable[] = {
167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
169 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
170};
171
Eric Laurent1afeecb2014-05-14 08:52:28 -0700172const StringToEnum sGainModeNameToEnumTable[] = {
173 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
174 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
175 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
176};
177
Eric Laurent3a4311c2014-03-17 12:00:47 -0700178
179uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
180 size_t size,
181 const char *name)
182{
183 for (size_t i = 0; i < size; i++) {
184 if (strcmp(table[i].name, name) == 0) {
185 ALOGV("stringToEnum() found %s", table[i].name);
186 return table[i].value;
187 }
188 }
189 return 0;
190}
191
192const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
193 size_t size,
194 uint32_t value)
195{
196 for (size_t i = 0; i < size; i++) {
197 if (table[i].value == value) {
198 return table[i].name;
199 }
200 }
201 return "";
202}
203
204bool AudioPolicyManager::stringToBool(const char *value)
205{
206 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
207}
208
209
210// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700211// AudioPolicyInterface implementation
212// ----------------------------------------------------------------------------
213
214
Eric Laurente0720872014-03-11 09:30:41 -0700215status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700216 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700217 const char *device_address)
218{
Eric Laurent22226012014-08-01 17:00:54 -0700219 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700220 // handle legacy remote submix case where the address was not always specified
221 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
222 address = String8("0");
223 }
Eric Laurente552edb2014-03-10 17:42:56 -0700224
Eric Laurent22226012014-08-01 17:00:54 -0700225 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
226 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700227
228 // connect/disconnect only 1 device at a time
229 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
230
Eric Laurente552edb2014-03-10 17:42:56 -0700231 // handle output devices
232 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700233 SortedVector <audio_io_handle_t> outputs;
234
Eric Laurent1afeecb2014-05-14 08:52:28 -0700235 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
236 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
238
Eric Laurente552edb2014-03-10 17:42:56 -0700239 // save a copy of the opened output descriptors before any output is opened or closed
240 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
241 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700242 switch (state)
243 {
244 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700245 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700246 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700247 ALOGW("setDeviceConnectionState() device already connected: %x", device);
248 return INVALID_OPERATION;
249 }
250 ALOGV("setDeviceConnectionState() connecting device %x", device);
251
Eric Laurente552edb2014-03-10 17:42:56 -0700252 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 index = mAvailableOutputDevices.add(devDesc);
254 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700255 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700256 if (module == 0) {
257 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
258 device);
259 mAvailableOutputDevices.remove(devDesc);
260 return INVALID_OPERATION;
261 }
262 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700263 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 } else {
265 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700266 }
267
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700268 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700269 mAvailableOutputDevices.remove(devDesc);
270 return INVALID_OPERATION;
271 }
272 // outputs should never be empty here
273 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
274 "checkOutputsForDevice() returned no outputs but status OK");
275 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
276 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700277 break;
278 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700279 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700280 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700281 ALOGW("setDeviceConnectionState() device not connected: %x", device);
282 return INVALID_OPERATION;
283 }
284
Paul McLean5c477aa2014-08-20 16:47:57 -0700285 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
286
287 // Set Disconnect to HALs
288 AudioParameter param = AudioParameter(address);
289 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
290 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
291
Eric Laurente552edb2014-03-10 17:42:56 -0700292 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700293 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700294
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700295 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700296 } break;
297
298 default:
299 ALOGE("setDeviceConnectionState() invalid state: %x", state);
300 return BAD_VALUE;
301 }
302
Eric Laurent3a4311c2014-03-17 12:00:47 -0700303 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
304 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700305 checkA2dpSuspend();
306 checkOutputForAllStrategies();
307 // outputs must be closed after checkOutputForAllStrategies() is executed
308 if (!outputs.isEmpty()) {
309 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700310 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700311 // close unused outputs after device disconnection or direct outputs that have been
312 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700313 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700314 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
315 (desc->mDirectOpenCount == 0))) {
316 closeOutput(outputs[i]);
317 }
318 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700319 // check again after closing A2DP output to reset mA2dpSuspended if needed
320 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700321 }
322
323 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 if (mPhoneState == AUDIO_MODE_IN_CALL) {
325 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
326 updateCallRouting(newDevice);
327 }
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700329 audio_io_handle_t output = mOutputs.keyAt(i);
330 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
331 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
332 true /*fromCache*/);
333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
336 bool force = !mOutputs.valueAt(i)->isDuplicated()
337 && (!deviceDistinguishesOnAddress(device)
338 // always force when disconnecting (a non-duplicated device)
339 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
340 setOutputDevice(output, newDevice, force, 0);
341 }
Eric Laurente552edb2014-03-10 17:42:56 -0700342 }
343
Eric Laurent72aa32f2014-05-30 18:51:48 -0700344 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700345 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700346 } // end if is output device
347
Eric Laurente552edb2014-03-10 17:42:56 -0700348 // handle input devices
349 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700350 SortedVector <audio_io_handle_t> inputs;
351
Eric Laurent1afeecb2014-05-14 08:52:28 -0700352 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
353 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700355 switch (state)
356 {
357 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700358 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700360 ALOGW("setDeviceConnectionState() device already connected: %d", device);
361 return INVALID_OPERATION;
362 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700363 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700364 if (module == NULL) {
365 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
366 device);
367 return INVALID_OPERATION;
368 }
Eric Laurentd4692962014-05-05 18:13:44 -0700369 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
370 return INVALID_OPERATION;
371 }
372
Eric Laurent3a4311c2014-03-17 12:00:47 -0700373 index = mAvailableInputDevices.add(devDesc);
374 if (index >= 0) {
375 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700376 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700377 } else {
378 return NO_MEMORY;
379 }
Eric Laurentd4692962014-05-05 18:13:44 -0700380 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700381
382 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700383 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700384 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700385 ALOGW("setDeviceConnectionState() device not connected: %d", device);
386 return INVALID_OPERATION;
387 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700388
389 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
390
391 // Set Disconnect to HALs
392 AudioParameter param = AudioParameter(address);
393 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
394 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
395
Eric Laurentd4692962014-05-05 18:13:44 -0700396 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700397 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700398
Eric Laurentd4692962014-05-05 18:13:44 -0700399 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700400
401 default:
402 ALOGE("setDeviceConnectionState() invalid state: %x", state);
403 return BAD_VALUE;
404 }
405
Eric Laurentd4692962014-05-05 18:13:44 -0700406 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700407
Eric Laurentc2730ba2014-07-20 15:47:07 -0700408 if (mPhoneState == AUDIO_MODE_IN_CALL) {
409 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
410 updateCallRouting(newDevice);
411 }
412
Eric Laurentb52c1522014-05-20 11:27:36 -0700413 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700414 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700415 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700416
417 ALOGW("setDeviceConnectionState() invalid device: %x", device);
418 return BAD_VALUE;
419}
420
Eric Laurente0720872014-03-11 09:30:41 -0700421audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700422 const char *device_address)
423{
Eric Laurent3b73df72014-03-11 09:06:29 -0700424 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700425 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700426 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700427 // handle legacy remote submix case where the address was not always specified
428 if (deviceDistinguishesOnAddress(device) && (devDesc->mAddress.length() == 0)) {
429 devDesc->mAddress = String8("0");
430 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700431 ssize_t index;
432 DeviceVector *deviceVector;
433
Eric Laurente552edb2014-03-10 17:42:56 -0700434 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700435 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700436 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700437 deviceVector = &mAvailableInputDevices;
438 } else {
439 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
440 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700441 }
442
Eric Laurent3a4311c2014-03-17 12:00:47 -0700443 index = deviceVector->indexOf(devDesc);
444 if (index >= 0) {
445 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
446 } else {
447 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
448 }
Eric Laurente552edb2014-03-10 17:42:56 -0700449}
450
Eric Laurentc2730ba2014-07-20 15:47:07 -0700451void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
452{
453 bool createTxPatch = false;
454 struct audio_patch patch;
455 patch.num_sources = 1;
456 patch.num_sinks = 1;
457 status_t status;
458 audio_patch_handle_t afPatchHandle;
459 DeviceVector deviceList;
460
461 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
462 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
463
464 // release existing RX patch if any
465 if (mCallRxPatch != 0) {
466 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
467 mCallRxPatch.clear();
468 }
469 // release TX patch if any
470 if (mCallTxPatch != 0) {
471 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
472 mCallTxPatch.clear();
473 }
474
475 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
476 // via setOutputDevice() on primary output.
477 // Otherwise, create two audio patches for TX and RX path.
478 if (availablePrimaryOutputDevices() & rxDevice) {
479 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
480 // If the TX device is also on the primary HW module, setOutputDevice() will take care
481 // of it due to legacy implementation. If not, create a patch.
482 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
483 == AUDIO_DEVICE_NONE) {
484 createTxPatch = true;
485 }
486 } else {
487 // create RX path audio patch
488 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
489 ALOG_ASSERT(!deviceList.isEmpty(),
490 "updateCallRouting() selected device not in output device list");
491 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
492 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
493 ALOG_ASSERT(!deviceList.isEmpty(),
494 "updateCallRouting() no telephony RX device");
495 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
496
497 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
498 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
499
500 // request to reuse existing output stream if one is already opened to reach the RX device
501 SortedVector<audio_io_handle_t> outputs =
502 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700503 audio_io_handle_t output = selectOutput(outputs,
504 AUDIO_OUTPUT_FLAG_NONE,
505 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700506 if (output != AUDIO_IO_HANDLE_NONE) {
507 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
508 ALOG_ASSERT(!outputDesc->isDuplicated(),
509 "updateCallRouting() RX device output is duplicated");
510 outputDesc->toAudioPortConfig(&patch.sources[1]);
511 patch.num_sources = 2;
512 }
513
514 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
515 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
516 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
517 status);
518 if (status == NO_ERROR) {
519 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
520 &patch, mUidCached);
521 mCallRxPatch->mAfPatchHandle = afPatchHandle;
522 mCallRxPatch->mUid = mUidCached;
523 }
524 createTxPatch = true;
525 }
526 if (createTxPatch) {
527
528 struct audio_patch patch;
529 patch.num_sources = 1;
530 patch.num_sinks = 1;
531 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
532 ALOG_ASSERT(!deviceList.isEmpty(),
533 "updateCallRouting() selected device not in input device list");
534 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
535 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
536 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
537 ALOG_ASSERT(!deviceList.isEmpty(),
538 "updateCallRouting() no telephony TX device");
539 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
540 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
541
542 SortedVector<audio_io_handle_t> outputs =
543 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700544 audio_io_handle_t output = selectOutput(outputs,
545 AUDIO_OUTPUT_FLAG_NONE,
546 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700547 // request to reuse existing output stream if one is already opened to reach the TX
548 // path output device
549 if (output != AUDIO_IO_HANDLE_NONE) {
550 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
551 ALOG_ASSERT(!outputDesc->isDuplicated(),
552 "updateCallRouting() RX device output is duplicated");
553 outputDesc->toAudioPortConfig(&patch.sources[1]);
554 patch.num_sources = 2;
555 }
556
557 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
558 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
559 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
560 status);
561 if (status == NO_ERROR) {
562 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
563 &patch, mUidCached);
564 mCallTxPatch->mAfPatchHandle = afPatchHandle;
565 mCallTxPatch->mUid = mUidCached;
566 }
567 }
568}
569
Eric Laurente0720872014-03-11 09:30:41 -0700570void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700571{
572 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700573 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700574 ALOGW("setPhoneState() invalid state %d", state);
575 return;
576 }
577
578 if (state == mPhoneState ) {
579 ALOGW("setPhoneState() setting same state %d", state);
580 return;
581 }
582
583 // if leaving call state, handle special case of active streams
584 // pertaining to sonification strategy see handleIncallSonification()
585 if (isInCall()) {
586 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700587 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800588 if (stream == AUDIO_STREAM_PATCH) {
589 continue;
590 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700591 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700592 }
593 }
594
595 // store previous phone state for management of sonification strategy below
596 int oldState = mPhoneState;
597 mPhoneState = state;
598 bool force = false;
599
600 // are we entering or starting a call
601 if (!isStateInCall(oldState) && isStateInCall(state)) {
602 ALOGV(" Entering call in setPhoneState()");
603 // force routing command to audio hardware when starting a call
604 // even if no device change is needed
605 force = true;
606 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
607 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
608 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
609 }
610 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
611 ALOGV(" Exiting call in setPhoneState()");
612 // force routing command to audio hardware when exiting a call
613 // even if no device change is needed
614 force = true;
615 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
616 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
617 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
618 }
619 } else if (isStateInCall(state) && (state != oldState)) {
620 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
621 // force routing command to audio hardware when switching between telephony and VoIP
622 // even if no device change is needed
623 force = true;
624 }
625
626 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700627 checkA2dpSuspend();
628 checkOutputForAllStrategies();
629 updateDevicesAndOutputs();
630
Eric Laurent1f2f2232014-06-02 12:01:23 -0700631 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700632
Eric Laurente552edb2014-03-10 17:42:56 -0700633 int delayMs = 0;
634 if (isStateInCall(state)) {
635 nsecs_t sysTime = systemTime();
636 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700637 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700638 // mute media and sonification strategies and delay device switch by the largest
639 // latency of any output where either strategy is active.
640 // This avoid sending the ring tone or music tail into the earpiece or headset.
641 if ((desc->isStrategyActive(STRATEGY_MEDIA,
642 SONIFICATION_HEADSET_MUSIC_DELAY,
643 sysTime) ||
644 desc->isStrategyActive(STRATEGY_SONIFICATION,
645 SONIFICATION_HEADSET_MUSIC_DELAY,
646 sysTime)) &&
647 (delayMs < (int)desc->mLatency*2)) {
648 delayMs = desc->mLatency*2;
649 }
650 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
651 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
652 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
653 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
654 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
655 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
656 }
657 }
658
Eric Laurentc2730ba2014-07-20 15:47:07 -0700659 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
660 // the device returned is not necessarily reachable via this output
661 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
662 // force routing command to audio hardware when ending call
663 // even if no device change is needed
664 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
665 rxDevice = hwOutputDesc->device();
666 }
Eric Laurente552edb2014-03-10 17:42:56 -0700667
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668 if (state == AUDIO_MODE_IN_CALL) {
669 updateCallRouting(rxDevice, delayMs);
670 } else if (oldState == AUDIO_MODE_IN_CALL) {
671 if (mCallRxPatch != 0) {
672 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
673 mCallRxPatch.clear();
674 }
675 if (mCallTxPatch != 0) {
676 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
677 mCallTxPatch.clear();
678 }
679 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
680 } else {
681 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
682 }
Eric Laurente552edb2014-03-10 17:42:56 -0700683 // if entering in call state, handle special case of active streams
684 // pertaining to sonification strategy see handleIncallSonification()
685 if (isStateInCall(state)) {
686 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700687 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800688 if (stream == AUDIO_STREAM_PATCH) {
689 continue;
690 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700691 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700692 }
693 }
694
695 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700696 if (state == AUDIO_MODE_RINGTONE &&
697 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700698 mLimitRingtoneVolume = true;
699 } else {
700 mLimitRingtoneVolume = false;
701 }
702}
703
Eric Laurente0720872014-03-11 09:30:41 -0700704void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700705 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700706{
707 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
708
709 bool forceVolumeReeval = false;
710 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700711 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
712 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
713 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700714 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
715 return;
716 }
717 forceVolumeReeval = true;
718 mForceUse[usage] = config;
719 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700720 case AUDIO_POLICY_FORCE_FOR_MEDIA:
721 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
722 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
723 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
724 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800725 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700726 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
727 return;
728 }
729 mForceUse[usage] = config;
730 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700731 case AUDIO_POLICY_FORCE_FOR_RECORD:
732 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
733 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700734 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
735 return;
736 }
737 mForceUse[usage] = config;
738 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700739 case AUDIO_POLICY_FORCE_FOR_DOCK:
740 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
741 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
742 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
743 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
744 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700745 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
746 }
747 forceVolumeReeval = true;
748 mForceUse[usage] = config;
749 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700750 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
751 if (config != AUDIO_POLICY_FORCE_NONE &&
752 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700753 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
754 }
755 forceVolumeReeval = true;
756 mForceUse[usage] = config;
757 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900758 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
759 if (config != AUDIO_POLICY_FORCE_NONE &&
760 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
761 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
762 }
763 mForceUse[usage] = config;
764 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700765 default:
766 ALOGW("setForceUse() invalid usage %d", usage);
767 break;
768 }
769
770 // check for device and output changes triggered by new force usage
771 checkA2dpSuspend();
772 checkOutputForAllStrategies();
773 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700774 if (mPhoneState == AUDIO_MODE_IN_CALL) {
775 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
776 updateCallRouting(newDevice);
777 }
Eric Laurente552edb2014-03-10 17:42:56 -0700778 for (size_t i = 0; i < mOutputs.size(); i++) {
779 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700780 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700781 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
782 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
783 }
Eric Laurente552edb2014-03-10 17:42:56 -0700784 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
785 applyStreamVolumes(output, newDevice, 0, true);
786 }
787 }
788
789 audio_io_handle_t activeInput = getActiveInput();
790 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700791 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700792 }
793
794}
795
Eric Laurente0720872014-03-11 09:30:41 -0700796audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700797{
798 return mForceUse[usage];
799}
800
Eric Laurente0720872014-03-11 09:30:41 -0700801void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700802{
803 ALOGV("setSystemProperty() property %s, value %s", property, value);
804}
805
806// Find a direct output profile compatible with the parameters passed, even if the input flags do
807// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700808sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700809 audio_devices_t device,
810 uint32_t samplingRate,
811 audio_format_t format,
812 audio_channel_mask_t channelMask,
813 audio_output_flags_t flags)
814{
815 for (size_t i = 0; i < mHwModules.size(); i++) {
816 if (mHwModules[i]->mHandle == 0) {
817 continue;
818 }
819 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700820 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700821 bool found = profile->isCompatibleProfile(device, samplingRate,
822 NULL /*updatedSamplingRate*/, format, channelMask,
823 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
824 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700825 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
826 return profile;
827 }
Eric Laurente552edb2014-03-10 17:42:56 -0700828 }
829 }
830 return 0;
831}
832
Eric Laurente0720872014-03-11 09:30:41 -0700833audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700834 uint32_t samplingRate,
835 audio_format_t format,
836 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700837 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700838 const audio_offload_info_t *offloadInfo)
839{
Eric Laurent3b73df72014-03-11 09:06:29 -0700840 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700841 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
842 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
843 device, stream, samplingRate, format, channelMask, flags);
844
Eric Laurente83b55d2014-11-14 10:06:21 -0800845 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
846 stream, samplingRate,format, channelMask,
847 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848}
849
Eric Laurente83b55d2014-11-14 10:06:21 -0800850status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
851 audio_io_handle_t *output,
852 audio_session_t session,
853 audio_stream_type_t *stream,
854 uint32_t samplingRate,
855 audio_format_t format,
856 audio_channel_mask_t channelMask,
857 audio_output_flags_t flags,
858 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700859{
Eric Laurente83b55d2014-11-14 10:06:21 -0800860 audio_attributes_t attributes;
861 if (attr != NULL) {
862 if (!isValidAttributes(attr)) {
863 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
864 attr->usage, attr->content_type, attr->flags,
865 attr->tags);
866 return BAD_VALUE;
867 }
868 attributes = *attr;
869 } else {
870 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
871 ALOGE("getOutputForAttr(): invalid stream type");
872 return BAD_VALUE;
873 }
874 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700875 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800876
Eric Laurent93c3d412014-08-01 14:48:35 -0700877 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800878 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700879
880 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
Eric Laurente83b55d2014-11-14 10:06:21 -0800881 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700882 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700883
Eric Laurente83b55d2014-11-14 10:06:21 -0800884 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700885 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
886 }
887
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700888 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700889 device, samplingRate, format, channelMask, flags);
890
Eric Laurente83b55d2014-11-14 10:06:21 -0800891 *stream = streamTypefromAttributesInt(&attributes);
892 *output = getOutputForDevice(device, session, *stream,
893 samplingRate, format, channelMask,
894 flags, offloadInfo);
895 if (*output == AUDIO_IO_HANDLE_NONE) {
896 return INVALID_OPERATION;
897 }
898 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700899}
900
901audio_io_handle_t AudioPolicyManager::getOutputForDevice(
902 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800903 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700904 audio_stream_type_t stream,
905 uint32_t samplingRate,
906 audio_format_t format,
907 audio_channel_mask_t channelMask,
908 audio_output_flags_t flags,
909 const audio_offload_info_t *offloadInfo)
910{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700911 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700912 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700913 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700914
Eric Laurente552edb2014-03-10 17:42:56 -0700915#ifdef AUDIO_POLICY_TEST
916 if (mCurOutput != 0) {
917 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
918 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
919
920 if (mTestOutputs[mCurOutput] == 0) {
921 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700922 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700923 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700924 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700925 outputDesc->mFlags =
926 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700927 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700928 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
929 config.sample_rate = mTestSamplingRate;
930 config.channel_mask = mTestChannels;
931 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700932 if (offloadInfo != NULL) {
933 config.offload_info = *offloadInfo;
934 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700935 status = mpClientInterface->openOutput(0,
936 &mTestOutputs[mCurOutput],
937 &config,
938 &outputDesc->mDevice,
939 String8(""),
940 &outputDesc->mLatency,
941 outputDesc->mFlags);
942 if (status == NO_ERROR) {
943 outputDesc->mSamplingRate = config.sample_rate;
944 outputDesc->mFormat = config.format;
945 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700946 AudioParameter outputCmd = AudioParameter();
947 outputCmd.addInt(String8("set_id"),mCurOutput);
948 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
949 addOutput(mTestOutputs[mCurOutput], outputDesc);
950 }
951 }
952 return mTestOutputs[mCurOutput];
953 }
954#endif //AUDIO_POLICY_TEST
955
956 // open a direct output if required by specified parameters
957 //force direct flag if offload flag is set: offloading implies a direct output stream
958 // and all common behaviors are driven by checking only the direct flag
959 // this should normally be set appropriately in the policy configuration file
960 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700961 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700962 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700963 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
964 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
965 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800966 // only allow deep buffering for music stream type
967 if (stream != AUDIO_STREAM_MUSIC) {
968 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
969 }
Eric Laurente552edb2014-03-10 17:42:56 -0700970
Eric Laurentb732cf52014-09-24 19:08:21 -0700971 sp<IOProfile> profile;
972
973 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700974 // and not explicitly requested
975 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
976 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700977 audio_channel_count_from_out_mask(channelMask) <= 2) {
978 goto non_direct_output;
979 }
980
Eric Laurente552edb2014-03-10 17:42:56 -0700981 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
982 // creating an offloaded track and tearing it down immediately after start when audioflinger
983 // detects there is an active non offloadable effect.
984 // FIXME: We should check the audio session here but we do not have it in this context.
985 // This may prevent offloading in rare situations where effects are left active by apps
986 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700987
Eric Laurente552edb2014-03-10 17:42:56 -0700988 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
989 !isNonOffloadableEffectEnabled()) {
990 profile = getProfileForDirectOutput(device,
991 samplingRate,
992 format,
993 channelMask,
994 (audio_output_flags_t)flags);
995 }
996
Eric Laurent1c333e22014-05-20 10:48:17 -0700997 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700998 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700999
1000 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001001 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001002 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1003 outputDesc = desc;
1004 // reuse direct output if currently open and configured with same parameters
1005 if ((samplingRate == outputDesc->mSamplingRate) &&
1006 (format == outputDesc->mFormat) &&
1007 (channelMask == outputDesc->mChannelMask)) {
1008 outputDesc->mDirectOpenCount++;
1009 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1010 return mOutputs.keyAt(i);
1011 }
1012 }
1013 }
1014 // close direct output if currently open and configured with different parameters
1015 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001016 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001017 }
1018 outputDesc = new AudioOutputDescriptor(profile);
1019 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001020 outputDesc->mLatency = 0;
1021 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001022 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1023 config.sample_rate = samplingRate;
1024 config.channel_mask = channelMask;
1025 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001026 if (offloadInfo != NULL) {
1027 config.offload_info = *offloadInfo;
1028 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001029 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1030 &output,
1031 &config,
1032 &outputDesc->mDevice,
1033 String8(""),
1034 &outputDesc->mLatency,
1035 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001036
1037 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001038 if (status != NO_ERROR ||
1039 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1040 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1041 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001042 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1043 "format %d %d, channelMask %04x %04x", output, samplingRate,
1044 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1045 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001046 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001047 mpClientInterface->closeOutput(output);
1048 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001049 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001050 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001051 outputDesc->mSamplingRate = config.sample_rate;
1052 outputDesc->mChannelMask = config.channel_mask;
1053 outputDesc->mFormat = config.format;
1054 outputDesc->mRefCount[stream] = 0;
1055 outputDesc->mStopTime[stream] = 0;
1056 outputDesc->mDirectOpenCount = 1;
1057
Eric Laurente552edb2014-03-10 17:42:56 -07001058 audio_io_handle_t srcOutput = getOutputForEffect();
1059 addOutput(output, outputDesc);
1060 audio_io_handle_t dstOutput = getOutputForEffect();
1061 if (dstOutput == output) {
1062 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1063 }
1064 mPreviousOutputs = mOutputs;
1065 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001066 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001067 return output;
1068 }
1069
Eric Laurentb732cf52014-09-24 19:08:21 -07001070non_direct_output:
1071
Eric Laurente552edb2014-03-10 17:42:56 -07001072 // ignoring channel mask due to downmix capability in mixer
1073
1074 // open a non direct output
1075
1076 // for non direct outputs, only PCM is supported
1077 if (audio_is_linear_pcm(format)) {
1078 // get which output is suitable for the specified stream. The actual
1079 // routing change will happen when startOutput() will be called
1080 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1081
Eric Laurent8838a382014-09-08 16:44:28 -07001082 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1083 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1084 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001085 }
1086 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1087 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1088
1089 ALOGV("getOutput() returns output %d", output);
1090
1091 return output;
1092}
1093
Eric Laurente0720872014-03-11 09:30:41 -07001094audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001095 audio_output_flags_t flags,
1096 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001097{
1098 // select one output among several that provide a path to a particular device or set of
1099 // devices (the list was previously build by getOutputsForDevice()).
1100 // The priority is as follows:
1101 // 1: the output with the highest number of requested policy flags
1102 // 2: the primary output
1103 // 3: the first output in the list
1104
1105 if (outputs.size() == 0) {
1106 return 0;
1107 }
1108 if (outputs.size() == 1) {
1109 return outputs[0];
1110 }
1111
1112 int maxCommonFlags = 0;
1113 audio_io_handle_t outputFlags = 0;
1114 audio_io_handle_t outputPrimary = 0;
1115
1116 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001117 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001118 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001119 // if a valid format is specified, skip output if not compatible
1120 if (format != AUDIO_FORMAT_INVALID) {
1121 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1122 if (format != outputDesc->mFormat) {
1123 continue;
1124 }
1125 } else if (!audio_is_linear_pcm(format)) {
1126 continue;
1127 }
1128 }
1129
Eric Laurent3b73df72014-03-11 09:06:29 -07001130 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001131 if (commonFlags > maxCommonFlags) {
1132 outputFlags = outputs[i];
1133 maxCommonFlags = commonFlags;
1134 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1135 }
1136 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1137 outputPrimary = outputs[i];
1138 }
1139 }
1140 }
1141
1142 if (outputFlags != 0) {
1143 return outputFlags;
1144 }
1145 if (outputPrimary != 0) {
1146 return outputPrimary;
1147 }
1148
1149 return outputs[0];
1150}
1151
Eric Laurente0720872014-03-11 09:30:41 -07001152status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001153 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001154 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001155{
1156 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1157 ssize_t index = mOutputs.indexOfKey(output);
1158 if (index < 0) {
1159 ALOGW("startOutput() unknown output %d", output);
1160 return BAD_VALUE;
1161 }
1162
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001163 // cannot start playback of STREAM_TTS if any other output is being used
1164 uint32_t beaconMuteLatency = 0;
1165 if (stream == AUDIO_STREAM_TTS) {
1166 ALOGV("\t found BEACON stream");
1167 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1168 return INVALID_OPERATION;
1169 } else {
1170 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1171 }
1172 } else {
1173 // some playback other than beacon starts
1174 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1175 }
1176
Eric Laurent1f2f2232014-06-02 12:01:23 -07001177 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001178
1179 // increment usage count for this stream on the requested output:
1180 // NOTE that the usage count is the same for duplicated output and hardware output which is
1181 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1182 outputDesc->changeRefCount(stream, 1);
1183
1184 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001185 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001186 routing_strategy strategy = getStrategy(stream);
1187 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001188 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1189 (beaconMuteLatency > 0);
1190 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001191 bool force = false;
1192 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001193 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001194 if (desc != outputDesc) {
1195 // force a device change if any other output is managed by the same hw
1196 // module and has a current device selection that differs from selected device.
1197 // In this case, the audio HAL must receive the new device selection so that it can
1198 // change the device currently selected by the other active output.
1199 if (outputDesc->sharesHwModuleWith(desc) &&
1200 desc->device() != newDevice) {
1201 force = true;
1202 }
1203 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001204 // a notification so that audio focus effect can propagate, or that a mute/unmute
1205 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001206 uint32_t latency = desc->latency();
1207 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1208 waitMs = latency;
1209 }
1210 }
1211 }
1212 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1213
1214 // handle special case for sonification while in call
1215 if (isInCall()) {
1216 handleIncallSonification(stream, true, false);
1217 }
1218
1219 // apply volume rules for current stream and device if necessary
1220 checkAndSetVolume(stream,
1221 mStreams[stream].getVolumeIndex(newDevice),
1222 output,
1223 newDevice);
1224
1225 // update the outputs if starting an output with a stream that can affect notification
1226 // routing
1227 handleNotificationRoutingForStream(stream);
1228 if (waitMs > muteWaitMs) {
1229 usleep((waitMs - muteWaitMs) * 2 * 1000);
1230 }
1231 }
1232 return NO_ERROR;
1233}
1234
1235
Eric Laurente0720872014-03-11 09:30:41 -07001236status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001237 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001238 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001239{
1240 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1241 ssize_t index = mOutputs.indexOfKey(output);
1242 if (index < 0) {
1243 ALOGW("stopOutput() unknown output %d", output);
1244 return BAD_VALUE;
1245 }
1246
Eric Laurent1f2f2232014-06-02 12:01:23 -07001247 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001248
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001249 // always handle stream stop, check which stream type is stopping
1250 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1251
Eric Laurente552edb2014-03-10 17:42:56 -07001252 // handle special case for sonification while in call
1253 if (isInCall()) {
1254 handleIncallSonification(stream, false, false);
1255 }
1256
1257 if (outputDesc->mRefCount[stream] > 0) {
1258 // decrement usage count of this stream on the output
1259 outputDesc->changeRefCount(stream, -1);
1260 // store time at which the stream was stopped - see isStreamActive()
1261 if (outputDesc->mRefCount[stream] == 0) {
1262 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001263 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001264 // delay the device switch by twice the latency because stopOutput() is executed when
1265 // the track stop() command is received and at that time the audio track buffer can
1266 // still contain data that needs to be drained. The latency only covers the audio HAL
1267 // and kernel buffers. Also the latency does not always include additional delay in the
1268 // audio path (audio DSP, CODEC ...)
1269 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1270
1271 // force restoring the device selection on other active outputs if it differs from the
1272 // one being selected for this output
1273 for (size_t i = 0; i < mOutputs.size(); i++) {
1274 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001275 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001276 if (curOutput != output &&
1277 desc->isActive() &&
1278 outputDesc->sharesHwModuleWith(desc) &&
1279 (newDevice != desc->device())) {
1280 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001281 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001282 true,
1283 outputDesc->mLatency*2);
1284 }
1285 }
1286 // update the outputs if stopping one with a stream that can affect notification routing
1287 handleNotificationRoutingForStream(stream);
1288 }
1289 return NO_ERROR;
1290 } else {
1291 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1292 return INVALID_OPERATION;
1293 }
1294}
1295
Eric Laurente83b55d2014-11-14 10:06:21 -08001296void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001297 audio_stream_type_t stream __unused,
1298 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001299{
1300 ALOGV("releaseOutput() %d", output);
1301 ssize_t index = mOutputs.indexOfKey(output);
1302 if (index < 0) {
1303 ALOGW("releaseOutput() releasing unknown output %d", output);
1304 return;
1305 }
1306
1307#ifdef AUDIO_POLICY_TEST
1308 int testIndex = testOutputIndex(output);
1309 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001310 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001311 if (outputDesc->isActive()) {
1312 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001313 mOutputs.removeItem(output);
1314 mTestOutputs[testIndex] = 0;
1315 }
1316 return;
1317 }
1318#endif //AUDIO_POLICY_TEST
1319
Eric Laurent1f2f2232014-06-02 12:01:23 -07001320 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001321 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001322 if (desc->mDirectOpenCount <= 0) {
1323 ALOGW("releaseOutput() invalid open count %d for output %d",
1324 desc->mDirectOpenCount, output);
1325 return;
1326 }
1327 if (--desc->mDirectOpenCount == 0) {
1328 closeOutput(output);
1329 // If effects where present on the output, audioflinger moved them to the primary
1330 // output by default: move them back to the appropriate output.
1331 audio_io_handle_t dstOutput = getOutputForEffect();
1332 if (dstOutput != mPrimaryOutput) {
1333 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1334 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001335 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001336 }
1337 }
1338}
1339
1340
Eric Laurentcaf7f482014-11-25 17:50:47 -08001341status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1342 audio_io_handle_t *input,
1343 audio_session_t session,
1344 uint32_t samplingRate,
1345 audio_format_t format,
1346 audio_channel_mask_t channelMask,
1347 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001348{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001349 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1350 "session %d, flags %#x",
1351 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001352
Eric Laurentcaf7f482014-11-25 17:50:47 -08001353 audio_devices_t device = getDeviceForInputSource(attr->source);
Eric Laurente552edb2014-03-10 17:42:56 -07001354
1355 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001356 ALOGW("getInputForAttr() could not find device for source %d", attr->source);
1357 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001358 }
1359
1360 // adapt channel selection to input source
Eric Laurentcaf7f482014-11-25 17:50:47 -08001361 switch (attr->source) {
Eric Laurente552edb2014-03-10 17:42:56 -07001362 case AUDIO_SOURCE_VOICE_UPLINK:
1363 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1364 break;
1365 case AUDIO_SOURCE_VOICE_DOWNLINK:
1366 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1367 break;
1368 case AUDIO_SOURCE_VOICE_CALL:
1369 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1370 break;
1371 default:
1372 break;
1373 }
1374
Eric Laurentcaf7f482014-11-25 17:50:47 -08001375 *input = AUDIO_IO_HANDLE_NONE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001376 bool isSoundTrigger = false;
Eric Laurentcaf7f482014-11-25 17:50:47 -08001377 audio_source_t halInputSource = attr->source;
1378 if (attr->source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001379 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1380 if (index >= 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001381 *input = mSoundTriggerSessions.valueFor(session);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001382 isSoundTrigger = true;
1383 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001384 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001385 } else {
1386 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1387 }
1388 }
1389
Eric Laurent1c333e22014-05-20 10:48:17 -07001390 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001391 samplingRate,
1392 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001393 channelMask,
1394 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001395 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001396 //retry without flags
1397 audio_input_flags_t log_flags = flags;
1398 flags = AUDIO_INPUT_FLAG_NONE;
1399 profile = getInputProfile(device,
1400 samplingRate,
1401 format,
1402 channelMask,
1403 flags);
1404 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001405 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1406 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001407 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001408 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001409 }
Eric Laurente552edb2014-03-10 17:42:56 -07001410 }
1411
1412 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001413 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1414 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001415 }
1416
1417 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1418 config.sample_rate = samplingRate;
1419 config.channel_mask = channelMask;
1420 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001421
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001422 // handle legacy remote submix case where the address was not always specified
1423 String8 address = deviceDistinguishesOnAddress(device) ? String8("0") : String8("");
1424
Eric Laurentcf2c0212014-07-25 16:20:43 -07001425 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001426 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001427 &config,
1428 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001429 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001430 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001431 flags);
1432
1433 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001434 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001435 (samplingRate != config.sample_rate) ||
1436 (format != config.format) ||
1437 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001438 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001439 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001440 if (*input != AUDIO_IO_HANDLE_NONE) {
1441 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001442 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001443 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001444 }
1445
Eric Laurent1f2f2232014-06-02 12:01:23 -07001446 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001447 inputDesc->mInputSource = attr->source;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001448 inputDesc->mRefCount = 0;
1449 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001450 inputDesc->mSamplingRate = samplingRate;
1451 inputDesc->mFormat = format;
1452 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001453 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001454 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001455 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001456
Eric Laurentcaf7f482014-11-25 17:50:47 -08001457 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001458 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001459 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001460}
1461
Eric Laurent4dc68062014-07-28 17:26:49 -07001462status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1463 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001464{
1465 ALOGV("startInput() input %d", input);
1466 ssize_t index = mInputs.indexOfKey(input);
1467 if (index < 0) {
1468 ALOGW("startInput() unknown input %d", input);
1469 return BAD_VALUE;
1470 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001471 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001472
Eric Laurent4dc68062014-07-28 17:26:49 -07001473 index = inputDesc->mSessions.indexOf(session);
1474 if (index < 0) {
1475 ALOGW("startInput() unknown session %d on input %d", session, input);
1476 return BAD_VALUE;
1477 }
1478
Glenn Kasten74a8e252014-07-24 14:09:55 -07001479 // virtual input devices are compatible with other input devices
1480 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1481
1482 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001483 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001484 if (activeInput != 0 && activeInput != input) {
1485
1486 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1487 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001488 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001489 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001490 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001491 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1492 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001493 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001494 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001495 return INVALID_OPERATION;
1496 }
1497 }
1498 }
1499
Glenn Kasten74a8e252014-07-24 14:09:55 -07001500 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001501 if (activeInputsCount() == 0) {
1502 SoundTrigger::setCaptureState(true);
1503 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001504 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001505
Glenn Kasten74a8e252014-07-24 14:09:55 -07001506 // Automatically enable the remote submix output when input is started.
1507 // For remote submix (a virtual device), we open only one input per capture request.
1508 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1509 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1510 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1511 }
Eric Laurente552edb2014-03-10 17:42:56 -07001512 }
1513
Eric Laurente552edb2014-03-10 17:42:56 -07001514 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1515
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001516 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001517 return NO_ERROR;
1518}
1519
Eric Laurent4dc68062014-07-28 17:26:49 -07001520status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1521 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001522{
1523 ALOGV("stopInput() input %d", input);
1524 ssize_t index = mInputs.indexOfKey(input);
1525 if (index < 0) {
1526 ALOGW("stopInput() unknown input %d", input);
1527 return BAD_VALUE;
1528 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001529 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001530
Eric Laurent4dc68062014-07-28 17:26:49 -07001531 index = inputDesc->mSessions.indexOf(session);
1532 if (index < 0) {
1533 ALOGW("stopInput() unknown session %d on input %d", session, input);
1534 return BAD_VALUE;
1535 }
1536
Eric Laurente552edb2014-03-10 17:42:56 -07001537 if (inputDesc->mRefCount == 0) {
1538 ALOGW("stopInput() input %d already stopped", input);
1539 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001540 }
1541
1542 inputDesc->mRefCount--;
1543 if (inputDesc->mRefCount == 0) {
1544
Eric Laurente552edb2014-03-10 17:42:56 -07001545 // automatically disable the remote submix output when input is stopped
1546 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1547 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001548 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001549 }
1550
Eric Laurent1c333e22014-05-20 10:48:17 -07001551 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001552
1553 if (activeInputsCount() == 0) {
1554 SoundTrigger::setCaptureState(false);
1555 }
Eric Laurente552edb2014-03-10 17:42:56 -07001556 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001557 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001558}
1559
Eric Laurent4dc68062014-07-28 17:26:49 -07001560void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1561 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001562{
1563 ALOGV("releaseInput() %d", input);
1564 ssize_t index = mInputs.indexOfKey(input);
1565 if (index < 0) {
1566 ALOGW("releaseInput() releasing unknown input %d", input);
1567 return;
1568 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001569 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1570 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001571
1572 index = inputDesc->mSessions.indexOf(session);
1573 if (index < 0) {
1574 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1575 return;
1576 }
1577 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001578 if (inputDesc->mOpenRefCount == 0) {
1579 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1580 return;
1581 }
1582 inputDesc->mOpenRefCount--;
1583 if (inputDesc->mOpenRefCount > 0) {
1584 ALOGV("releaseInput() exit > 0");
1585 return;
1586 }
1587
Eric Laurent05b90f82014-08-27 15:32:29 -07001588 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001589 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001590 ALOGV("releaseInput() exit");
1591}
1592
Eric Laurentd4692962014-05-05 18:13:44 -07001593void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001594 bool patchRemoved = false;
1595
Eric Laurentd4692962014-05-05 18:13:44 -07001596 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001597 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1598 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1599 if (patch_index >= 0) {
1600 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1601 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1602 mAudioPatches.removeItemsAt(patch_index);
1603 patchRemoved = true;
1604 }
Eric Laurentd4692962014-05-05 18:13:44 -07001605 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1606 }
1607 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001608 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001609
1610 if (patchRemoved) {
1611 mpClientInterface->onAudioPatchListUpdate();
1612 }
Eric Laurentd4692962014-05-05 18:13:44 -07001613}
1614
Eric Laurente0720872014-03-11 09:30:41 -07001615void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001616 int indexMin,
1617 int indexMax)
1618{
1619 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1620 if (indexMin < 0 || indexMin >= indexMax) {
1621 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1622 return;
1623 }
1624 mStreams[stream].mIndexMin = indexMin;
1625 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001626 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1627 if (stream == AUDIO_STREAM_MUSIC) {
1628 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1629 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1630 }
Eric Laurente552edb2014-03-10 17:42:56 -07001631}
1632
Eric Laurente0720872014-03-11 09:30:41 -07001633status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001634 int index,
1635 audio_devices_t device)
1636{
1637
1638 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1639 return BAD_VALUE;
1640 }
1641 if (!audio_is_output_device(device)) {
1642 return BAD_VALUE;
1643 }
1644
1645 // Force max volume if stream cannot be muted
1646 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1647
1648 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1649 stream, device, index);
1650
1651 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1652 // clear all device specific values
1653 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1654 mStreams[stream].mIndexCur.clear();
1655 }
1656 mStreams[stream].mIndexCur.add(device, index);
1657
Eric Laurent31551f82014-10-10 18:21:56 -07001658 // update volume on all outputs whose current device is also selected by the same
1659 // strategy as the device specified by the caller
1660 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001661
1662
1663 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1664 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1665 if (stream == AUDIO_STREAM_MUSIC) {
1666 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1667 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1668 }
1669 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1670 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001671 return NO_ERROR;
1672 }
Eric Laurente552edb2014-03-10 17:42:56 -07001673 status_t status = NO_ERROR;
1674 for (size_t i = 0; i < mOutputs.size(); i++) {
1675 audio_devices_t curDevice =
1676 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001677 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001678 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1679 if (volStatus != NO_ERROR) {
1680 status = volStatus;
1681 }
1682 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001683 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1684 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1685 index, mOutputs.keyAt(i), curDevice);
1686 }
Eric Laurente552edb2014-03-10 17:42:56 -07001687 }
1688 return status;
1689}
1690
Eric Laurente0720872014-03-11 09:30:41 -07001691status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001692 int *index,
1693 audio_devices_t device)
1694{
1695 if (index == NULL) {
1696 return BAD_VALUE;
1697 }
1698 if (!audio_is_output_device(device)) {
1699 return BAD_VALUE;
1700 }
1701 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1702 // the strategy the stream belongs to.
1703 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1704 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1705 }
1706 device = getDeviceForVolume(device);
1707
1708 *index = mStreams[stream].getVolumeIndex(device);
1709 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1710 return NO_ERROR;
1711}
1712
Eric Laurente0720872014-03-11 09:30:41 -07001713audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001714 const SortedVector<audio_io_handle_t>& outputs)
1715{
1716 // select one output among several suitable for global effects.
1717 // The priority is as follows:
1718 // 1: An offloaded output. If the effect ends up not being offloadable,
1719 // AudioFlinger will invalidate the track and the offloaded output
1720 // will be closed causing the effect to be moved to a PCM output.
1721 // 2: A deep buffer output
1722 // 3: the first output in the list
1723
1724 if (outputs.size() == 0) {
1725 return 0;
1726 }
1727
1728 audio_io_handle_t outputOffloaded = 0;
1729 audio_io_handle_t outputDeepBuffer = 0;
1730
1731 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001732 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001733 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001734 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1735 outputOffloaded = outputs[i];
1736 }
1737 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1738 outputDeepBuffer = outputs[i];
1739 }
1740 }
1741
1742 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1743 outputOffloaded, outputDeepBuffer);
1744 if (outputOffloaded != 0) {
1745 return outputOffloaded;
1746 }
1747 if (outputDeepBuffer != 0) {
1748 return outputDeepBuffer;
1749 }
1750
1751 return outputs[0];
1752}
1753
Eric Laurente0720872014-03-11 09:30:41 -07001754audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001755{
1756 // apply simple rule where global effects are attached to the same output as MUSIC streams
1757
Eric Laurent3b73df72014-03-11 09:06:29 -07001758 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001759 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1760 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1761
1762 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1763 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1764 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1765
1766 return output;
1767}
1768
Eric Laurente0720872014-03-11 09:30:41 -07001769status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001770 audio_io_handle_t io,
1771 uint32_t strategy,
1772 int session,
1773 int id)
1774{
1775 ssize_t index = mOutputs.indexOfKey(io);
1776 if (index < 0) {
1777 index = mInputs.indexOfKey(io);
1778 if (index < 0) {
1779 ALOGW("registerEffect() unknown io %d", io);
1780 return INVALID_OPERATION;
1781 }
1782 }
1783
1784 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1785 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1786 desc->name, desc->memoryUsage);
1787 return INVALID_OPERATION;
1788 }
1789 mTotalEffectsMemory += desc->memoryUsage;
1790 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1791 desc->name, io, strategy, session, id);
1792 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1793
Eric Laurent1f2f2232014-06-02 12:01:23 -07001794 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1795 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1796 effectDesc->mIo = io;
1797 effectDesc->mStrategy = (routing_strategy)strategy;
1798 effectDesc->mSession = session;
1799 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001800
Eric Laurent1f2f2232014-06-02 12:01:23 -07001801 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001802
1803 return NO_ERROR;
1804}
1805
Eric Laurente0720872014-03-11 09:30:41 -07001806status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001807{
1808 ssize_t index = mEffects.indexOfKey(id);
1809 if (index < 0) {
1810 ALOGW("unregisterEffect() unknown effect ID %d", id);
1811 return INVALID_OPERATION;
1812 }
1813
Eric Laurent1f2f2232014-06-02 12:01:23 -07001814 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001815
Eric Laurent1f2f2232014-06-02 12:01:23 -07001816 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001817
Eric Laurent1f2f2232014-06-02 12:01:23 -07001818 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001819 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001820 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1821 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001822 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001823 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001824 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001825 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001826
1827 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001828
1829 return NO_ERROR;
1830}
1831
Eric Laurente0720872014-03-11 09:30:41 -07001832status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001833{
1834 ssize_t index = mEffects.indexOfKey(id);
1835 if (index < 0) {
1836 ALOGW("unregisterEffect() unknown effect ID %d", id);
1837 return INVALID_OPERATION;
1838 }
1839
1840 return setEffectEnabled(mEffects.valueAt(index), enabled);
1841}
1842
Eric Laurent1f2f2232014-06-02 12:01:23 -07001843status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001844{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001845 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001846 ALOGV("setEffectEnabled(%s) effect already %s",
1847 enabled?"true":"false", enabled?"enabled":"disabled");
1848 return INVALID_OPERATION;
1849 }
1850
1851 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001852 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001853 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001854 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001855 return INVALID_OPERATION;
1856 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001857 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001858 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1859 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001860 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001861 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001862 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1863 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001864 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001865 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001866 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1867 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001868 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001869 return NO_ERROR;
1870}
1871
Eric Laurente0720872014-03-11 09:30:41 -07001872bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001873{
1874 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001875 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1876 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1877 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001878 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001879 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001880 return true;
1881 }
1882 }
1883 return false;
1884}
1885
Eric Laurente0720872014-03-11 09:30:41 -07001886bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001887{
1888 nsecs_t sysTime = systemTime();
1889 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001890 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001891 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001892 return true;
1893 }
1894 }
1895 return false;
1896}
1897
Eric Laurente0720872014-03-11 09:30:41 -07001898bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001899 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001900{
1901 nsecs_t sysTime = systemTime();
1902 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001903 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001904 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001905 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001906 return true;
1907 }
1908 }
1909 return false;
1910}
1911
Eric Laurente0720872014-03-11 09:30:41 -07001912bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001913{
1914 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001915 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001916 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001917 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001918 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1919 && (inputDescriptor->mRefCount > 0)) {
1920 return true;
1921 }
1922 }
1923 return false;
1924}
1925
1926
Eric Laurente0720872014-03-11 09:30:41 -07001927status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001928{
1929 const size_t SIZE = 256;
1930 char buffer[SIZE];
1931 String8 result;
1932
1933 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1934 result.append(buffer);
1935
1936 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1937 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001938 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1939 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001940 snprintf(buffer, SIZE, " Force use for communications %d\n",
1941 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001942 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001943 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001944 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001945 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001946 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001947 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001948 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001949 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001950 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001951 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1952 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1953 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001954
Eric Laurent3a4311c2014-03-17 12:00:47 -07001955 snprintf(buffer, SIZE, " Available output devices:\n");
1956 result.append(buffer);
1957 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001958 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001959 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001960 }
1961 snprintf(buffer, SIZE, "\n Available input devices:\n");
1962 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001963 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001964 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001965 }
Eric Laurente552edb2014-03-10 17:42:56 -07001966
1967 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1968 write(fd, buffer, strlen(buffer));
1969 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001970 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001971 write(fd, buffer, strlen(buffer));
1972 mHwModules[i]->dump(fd);
1973 }
1974
1975 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1976 write(fd, buffer, strlen(buffer));
1977 for (size_t i = 0; i < mOutputs.size(); i++) {
1978 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1979 write(fd, buffer, strlen(buffer));
1980 mOutputs.valueAt(i)->dump(fd);
1981 }
1982
1983 snprintf(buffer, SIZE, "\nInputs dump:\n");
1984 write(fd, buffer, strlen(buffer));
1985 for (size_t i = 0; i < mInputs.size(); i++) {
1986 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1987 write(fd, buffer, strlen(buffer));
1988 mInputs.valueAt(i)->dump(fd);
1989 }
1990
1991 snprintf(buffer, SIZE, "\nStreams dump:\n");
1992 write(fd, buffer, strlen(buffer));
1993 snprintf(buffer, SIZE,
1994 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1995 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001996 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001997 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001998 write(fd, buffer, strlen(buffer));
1999 mStreams[i].dump(fd);
2000 }
2001
2002 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2003 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2004 write(fd, buffer, strlen(buffer));
2005
2006 snprintf(buffer, SIZE, "Registered effects:\n");
2007 write(fd, buffer, strlen(buffer));
2008 for (size_t i = 0; i < mEffects.size(); i++) {
2009 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2010 write(fd, buffer, strlen(buffer));
2011 mEffects.valueAt(i)->dump(fd);
2012 }
2013
Eric Laurent4d416952014-08-10 14:07:09 -07002014 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2015 write(fd, buffer, strlen(buffer));
2016 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2017 mAudioPatches[i]->dump(fd, 2, i);
2018 }
Eric Laurente552edb2014-03-10 17:42:56 -07002019
2020 return NO_ERROR;
2021}
2022
2023// This function checks for the parameters which can be offloaded.
2024// This can be enhanced depending on the capability of the DSP and policy
2025// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002026bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002027{
2028 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002029 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002030 offloadInfo.sample_rate, offloadInfo.channel_mask,
2031 offloadInfo.format,
2032 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2033 offloadInfo.has_video);
2034
2035 // Check if offload has been disabled
2036 char propValue[PROPERTY_VALUE_MAX];
2037 if (property_get("audio.offload.disable", propValue, "0")) {
2038 if (atoi(propValue) != 0) {
2039 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2040 return false;
2041 }
2042 }
2043
2044 // Check if stream type is music, then only allow offload as of now.
2045 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2046 {
2047 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2048 return false;
2049 }
2050
2051 //TODO: enable audio offloading with video when ready
2052 if (offloadInfo.has_video)
2053 {
2054 ALOGV("isOffloadSupported: has_video == true, returning false");
2055 return false;
2056 }
2057
2058 //If duration is less than minimum value defined in property, return false
2059 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2060 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2061 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2062 return false;
2063 }
2064 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2065 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2066 return false;
2067 }
2068
2069 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2070 // creating an offloaded track and tearing it down immediately after start when audioflinger
2071 // detects there is an active non offloadable effect.
2072 // FIXME: We should check the audio session here but we do not have it in this context.
2073 // This may prevent offloading in rare situations where effects are left active by apps
2074 // in the background.
2075 if (isNonOffloadableEffectEnabled()) {
2076 return false;
2077 }
2078
2079 // See if there is a profile to support this.
2080 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002081 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002082 offloadInfo.sample_rate,
2083 offloadInfo.format,
2084 offloadInfo.channel_mask,
2085 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002086 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2087 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002088}
2089
Eric Laurent6a94d692014-05-20 11:18:06 -07002090status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2091 audio_port_type_t type,
2092 unsigned int *num_ports,
2093 struct audio_port *ports,
2094 unsigned int *generation)
2095{
2096 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2097 generation == NULL) {
2098 return BAD_VALUE;
2099 }
2100 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2101 if (ports == NULL) {
2102 *num_ports = 0;
2103 }
2104
2105 size_t portsWritten = 0;
2106 size_t portsMax = *num_ports;
2107 *num_ports = 0;
2108 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2109 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2110 for (size_t i = 0;
2111 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2112 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2113 }
2114 *num_ports += mAvailableOutputDevices.size();
2115 }
2116 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2117 for (size_t i = 0;
2118 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2119 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2120 }
2121 *num_ports += mAvailableInputDevices.size();
2122 }
2123 }
2124 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2125 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2126 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2127 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2128 }
2129 *num_ports += mInputs.size();
2130 }
2131 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002132 size_t numOutputs = 0;
2133 for (size_t i = 0; i < mOutputs.size(); i++) {
2134 if (!mOutputs[i]->isDuplicated()) {
2135 numOutputs++;
2136 if (portsWritten < portsMax) {
2137 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2138 }
2139 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002140 }
Eric Laurent84c70242014-06-23 08:46:27 -07002141 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002142 }
2143 }
2144 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002145 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002146 return NO_ERROR;
2147}
2148
2149status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2150{
2151 return NO_ERROR;
2152}
2153
Eric Laurent1f2f2232014-06-02 12:01:23 -07002154sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002155 audio_port_handle_t id) const
2156{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002157 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002158 for (size_t i = 0; i < mOutputs.size(); i++) {
2159 outputDesc = mOutputs.valueAt(i);
2160 if (outputDesc->mId == id) {
2161 break;
2162 }
2163 }
2164 return outputDesc;
2165}
2166
Eric Laurent1f2f2232014-06-02 12:01:23 -07002167sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002168 audio_port_handle_t id) const
2169{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002170 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002171 for (size_t i = 0; i < mInputs.size(); i++) {
2172 inputDesc = mInputs.valueAt(i);
2173 if (inputDesc->mId == id) {
2174 break;
2175 }
2176 }
2177 return inputDesc;
2178}
2179
Eric Laurent1f2f2232014-06-02 12:01:23 -07002180sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2181 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002182{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002183 sp <HwModule> module;
2184
Eric Laurent6a94d692014-05-20 11:18:06 -07002185 for (size_t i = 0; i < mHwModules.size(); i++) {
2186 if (mHwModules[i]->mHandle == 0) {
2187 continue;
2188 }
2189 if (audio_is_output_device(device)) {
2190 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2191 {
2192 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2193 return mHwModules[i];
2194 }
2195 }
2196 } else {
2197 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2198 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2199 device & ~AUDIO_DEVICE_BIT_IN) {
2200 return mHwModules[i];
2201 }
2202 }
2203 }
2204 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002205 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002206}
2207
Eric Laurent1f2f2232014-06-02 12:01:23 -07002208sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002209{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002210 sp <HwModule> module;
2211
Eric Laurent1afeecb2014-05-14 08:52:28 -07002212 for (size_t i = 0; i < mHwModules.size(); i++)
2213 {
2214 if (strcmp(mHwModules[i]->mName, name) == 0) {
2215 return mHwModules[i];
2216 }
2217 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002218 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002219}
2220
Eric Laurentc2730ba2014-07-20 15:47:07 -07002221audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2222{
2223 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2224 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2225 return devices & mAvailableOutputDevices.types();
2226}
2227
2228audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2229{
2230 audio_module_handle_t primaryHandle =
2231 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2232 audio_devices_t devices = AUDIO_DEVICE_NONE;
2233 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2234 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2235 devices |= mAvailableInputDevices[i]->mDeviceType;
2236 }
2237 }
2238 return devices;
2239}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002240
Eric Laurent6a94d692014-05-20 11:18:06 -07002241status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2242 audio_patch_handle_t *handle,
2243 uid_t uid)
2244{
2245 ALOGV("createAudioPatch()");
2246
2247 if (handle == NULL || patch == NULL) {
2248 return BAD_VALUE;
2249 }
2250 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2251
Eric Laurent874c42872014-08-08 15:13:39 -07002252 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2253 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2254 return BAD_VALUE;
2255 }
2256 // only one source per audio patch supported for now
2257 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002258 return INVALID_OPERATION;
2259 }
Eric Laurent874c42872014-08-08 15:13:39 -07002260
2261 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002262 return INVALID_OPERATION;
2263 }
Eric Laurent874c42872014-08-08 15:13:39 -07002264 for (size_t i = 0; i < patch->num_sinks; i++) {
2265 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2266 return INVALID_OPERATION;
2267 }
2268 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002269
2270 sp<AudioPatch> patchDesc;
2271 ssize_t index = mAudioPatches.indexOfKey(*handle);
2272
Eric Laurent6a94d692014-05-20 11:18:06 -07002273 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2274 patch->sources[0].role,
2275 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002276#if LOG_NDEBUG == 0
2277 for (size_t i = 0; i < patch->num_sinks; i++) {
2278 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2279 patch->sinks[i].role,
2280 patch->sinks[i].type);
2281 }
2282#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002283
2284 if (index >= 0) {
2285 patchDesc = mAudioPatches.valueAt(index);
2286 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2287 mUidCached, patchDesc->mUid, uid);
2288 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2289 return INVALID_OPERATION;
2290 }
2291 } else {
2292 *handle = 0;
2293 }
2294
2295 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002296 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002297 if (outputDesc == NULL) {
2298 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2299 return BAD_VALUE;
2300 }
Eric Laurent84c70242014-06-23 08:46:27 -07002301 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2302 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002303 if (patchDesc != 0) {
2304 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2305 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2306 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2307 return BAD_VALUE;
2308 }
2309 }
Eric Laurent874c42872014-08-08 15:13:39 -07002310 DeviceVector devices;
2311 for (size_t i = 0; i < patch->num_sinks; i++) {
2312 // Only support mix to devices connection
2313 // TODO add support for mix to mix connection
2314 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2315 ALOGV("createAudioPatch() source mix but sink is not a device");
2316 return INVALID_OPERATION;
2317 }
2318 sp<DeviceDescriptor> devDesc =
2319 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2320 if (devDesc == 0) {
2321 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2322 return BAD_VALUE;
2323 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002324
Eric Laurent874c42872014-08-08 15:13:39 -07002325 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2326 patch->sources[0].sample_rate,
2327 NULL, // updatedSamplingRate
2328 patch->sources[0].format,
2329 patch->sources[0].channel_mask,
2330 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2331 ALOGV("createAudioPatch() profile not supported for device %08x",
2332 devDesc->mDeviceType);
2333 return INVALID_OPERATION;
2334 }
2335 devices.add(devDesc);
2336 }
2337 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002338 return INVALID_OPERATION;
2339 }
Eric Laurent874c42872014-08-08 15:13:39 -07002340
Eric Laurent6a94d692014-05-20 11:18:06 -07002341 // TODO: reconfigure output format and channels here
2342 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002343 devices.types(), outputDesc->mIoHandle);
2344 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002345 index = mAudioPatches.indexOfKey(*handle);
2346 if (index >= 0) {
2347 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2348 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2349 }
2350 patchDesc = mAudioPatches.valueAt(index);
2351 patchDesc->mUid = uid;
2352 ALOGV("createAudioPatch() success");
2353 } else {
2354 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2355 return INVALID_OPERATION;
2356 }
2357 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2358 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2359 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002360 // only one sink supported when connecting an input device to a mix
2361 if (patch->num_sinks > 1) {
2362 return INVALID_OPERATION;
2363 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002364 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002365 if (inputDesc == NULL) {
2366 return BAD_VALUE;
2367 }
2368 if (patchDesc != 0) {
2369 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2370 return BAD_VALUE;
2371 }
2372 }
2373 sp<DeviceDescriptor> devDesc =
2374 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2375 if (devDesc == 0) {
2376 return BAD_VALUE;
2377 }
2378
Eric Laurent84c70242014-06-23 08:46:27 -07002379 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002380 patch->sinks[0].sample_rate,
2381 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002382 patch->sinks[0].format,
2383 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002384 // FIXME for the parameter type,
2385 // and the NONE
2386 (audio_output_flags_t)
2387 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002388 return INVALID_OPERATION;
2389 }
2390 // TODO: reconfigure output format and channels here
2391 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002392 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002393 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002394 index = mAudioPatches.indexOfKey(*handle);
2395 if (index >= 0) {
2396 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2397 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2398 }
2399 patchDesc = mAudioPatches.valueAt(index);
2400 patchDesc->mUid = uid;
2401 ALOGV("createAudioPatch() success");
2402 } else {
2403 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2404 return INVALID_OPERATION;
2405 }
2406 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2407 // device to device connection
2408 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002409 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002410 return BAD_VALUE;
2411 }
2412 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002413 sp<DeviceDescriptor> srcDeviceDesc =
2414 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002415 if (srcDeviceDesc == 0) {
2416 return BAD_VALUE;
2417 }
Eric Laurent874c42872014-08-08 15:13:39 -07002418
Eric Laurent6a94d692014-05-20 11:18:06 -07002419 //update source and sink with our own data as the data passed in the patch may
2420 // be incomplete.
2421 struct audio_patch newPatch = *patch;
2422 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002423
Eric Laurent874c42872014-08-08 15:13:39 -07002424 for (size_t i = 0; i < patch->num_sinks; i++) {
2425 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2426 ALOGV("createAudioPatch() source device but one sink is not a device");
2427 return INVALID_OPERATION;
2428 }
2429
2430 sp<DeviceDescriptor> sinkDeviceDesc =
2431 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2432 if (sinkDeviceDesc == 0) {
2433 return BAD_VALUE;
2434 }
2435 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2436
2437 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2438 // only one sink supported when connected devices across HW modules
2439 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002440 return INVALID_OPERATION;
2441 }
Eric Laurent874c42872014-08-08 15:13:39 -07002442 SortedVector<audio_io_handle_t> outputs =
2443 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2444 mOutputs);
2445 // if the sink device is reachable via an opened output stream, request to go via
2446 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002447 audio_io_handle_t output = selectOutput(outputs,
2448 AUDIO_OUTPUT_FLAG_NONE,
2449 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002450 if (output != AUDIO_IO_HANDLE_NONE) {
2451 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2452 if (outputDesc->isDuplicated()) {
2453 return INVALID_OPERATION;
2454 }
2455 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2456 newPatch.num_sources = 2;
2457 }
Eric Laurent83b88082014-06-20 18:31:16 -07002458 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002459 }
2460 // TODO: check from routing capabilities in config file and other conflicting patches
2461
2462 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2463 if (index >= 0) {
2464 afPatchHandle = patchDesc->mAfPatchHandle;
2465 }
2466
2467 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2468 &afPatchHandle,
2469 0);
2470 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2471 status, afPatchHandle);
2472 if (status == NO_ERROR) {
2473 if (index < 0) {
2474 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2475 &newPatch, uid);
2476 addAudioPatch(patchDesc->mHandle, patchDesc);
2477 } else {
2478 patchDesc->mPatch = newPatch;
2479 }
2480 patchDesc->mAfPatchHandle = afPatchHandle;
2481 *handle = patchDesc->mHandle;
2482 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002483 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002484 } else {
2485 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2486 status);
2487 return INVALID_OPERATION;
2488 }
2489 } else {
2490 return BAD_VALUE;
2491 }
2492 } else {
2493 return BAD_VALUE;
2494 }
2495 return NO_ERROR;
2496}
2497
2498status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2499 uid_t uid)
2500{
2501 ALOGV("releaseAudioPatch() patch %d", handle);
2502
2503 ssize_t index = mAudioPatches.indexOfKey(handle);
2504
2505 if (index < 0) {
2506 return BAD_VALUE;
2507 }
2508 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2509 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2510 mUidCached, patchDesc->mUid, uid);
2511 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2512 return INVALID_OPERATION;
2513 }
2514
2515 struct audio_patch *patch = &patchDesc->mPatch;
2516 patchDesc->mUid = mUidCached;
2517 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002518 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002519 if (outputDesc == NULL) {
2520 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2521 return BAD_VALUE;
2522 }
2523
2524 setOutputDevice(outputDesc->mIoHandle,
2525 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2526 true,
2527 0,
2528 NULL);
2529 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2530 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002531 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002532 if (inputDesc == NULL) {
2533 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2534 return BAD_VALUE;
2535 }
2536 setInputDevice(inputDesc->mIoHandle,
2537 getNewInputDevice(inputDesc->mIoHandle),
2538 true,
2539 NULL);
2540 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2541 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2542 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2543 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2544 status, patchDesc->mAfPatchHandle);
2545 removeAudioPatch(patchDesc->mHandle);
2546 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002547 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002548 } else {
2549 return BAD_VALUE;
2550 }
2551 } else {
2552 return BAD_VALUE;
2553 }
2554 return NO_ERROR;
2555}
2556
2557status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2558 struct audio_patch *patches,
2559 unsigned int *generation)
2560{
2561 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2562 generation == NULL) {
2563 return BAD_VALUE;
2564 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002565 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002566 *num_patches, patches, mAudioPatches.size());
2567 if (patches == NULL) {
2568 *num_patches = 0;
2569 }
2570
2571 size_t patchesWritten = 0;
2572 size_t patchesMax = *num_patches;
2573 for (size_t i = 0;
2574 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2575 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2576 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002577 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002578 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2579 }
2580 *num_patches = mAudioPatches.size();
2581
2582 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002583 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002584 return NO_ERROR;
2585}
2586
Eric Laurente1715a42014-05-20 11:30:42 -07002587status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002588{
Eric Laurente1715a42014-05-20 11:30:42 -07002589 ALOGV("setAudioPortConfig()");
2590
2591 if (config == NULL) {
2592 return BAD_VALUE;
2593 }
2594 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2595 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002596 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2597 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002598 }
2599
Eric Laurenta121f902014-06-03 13:32:54 -07002600 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002601 if (config->type == AUDIO_PORT_TYPE_MIX) {
2602 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002603 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002604 if (outputDesc == NULL) {
2605 return BAD_VALUE;
2606 }
Eric Laurent84c70242014-06-23 08:46:27 -07002607 ALOG_ASSERT(!outputDesc->isDuplicated(),
2608 "setAudioPortConfig() called on duplicated output %d",
2609 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002610 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002611 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002612 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002613 if (inputDesc == NULL) {
2614 return BAD_VALUE;
2615 }
Eric Laurenta121f902014-06-03 13:32:54 -07002616 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002617 } else {
2618 return BAD_VALUE;
2619 }
2620 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2621 sp<DeviceDescriptor> deviceDesc;
2622 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2623 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2624 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2625 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2626 } else {
2627 return BAD_VALUE;
2628 }
2629 if (deviceDesc == NULL) {
2630 return BAD_VALUE;
2631 }
Eric Laurenta121f902014-06-03 13:32:54 -07002632 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002633 } else {
2634 return BAD_VALUE;
2635 }
2636
Eric Laurenta121f902014-06-03 13:32:54 -07002637 struct audio_port_config backupConfig;
2638 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2639 if (status == NO_ERROR) {
2640 struct audio_port_config newConfig;
2641 audioPortConfig->toAudioPortConfig(&newConfig, config);
2642 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002643 }
Eric Laurenta121f902014-06-03 13:32:54 -07002644 if (status != NO_ERROR) {
2645 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002646 }
Eric Laurente1715a42014-05-20 11:30:42 -07002647
2648 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002649}
2650
2651void AudioPolicyManager::clearAudioPatches(uid_t uid)
2652{
2653 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2654 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2655 if (patchDesc->mUid == uid) {
2656 // releaseAudioPatch() removes the patch from mAudioPatches
2657 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2658 i--;
2659 }
2660 }
2661 }
2662}
2663
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002664status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2665 audio_io_handle_t *ioHandle,
2666 audio_devices_t *device)
2667{
2668 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2669 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2670 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2671
2672 mSoundTriggerSessions.add(*session, *ioHandle);
2673
2674 return NO_ERROR;
2675}
2676
2677status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2678{
2679 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2680 if (index < 0) {
2681 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2682 return BAD_VALUE;
2683 }
2684
2685 mSoundTriggerSessions.removeItem(session);
2686 return NO_ERROR;
2687}
2688
Eric Laurent6a94d692014-05-20 11:18:06 -07002689status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2690 const sp<AudioPatch>& patch)
2691{
2692 ssize_t index = mAudioPatches.indexOfKey(handle);
2693
2694 if (index >= 0) {
2695 ALOGW("addAudioPatch() patch %d already in", handle);
2696 return ALREADY_EXISTS;
2697 }
2698 mAudioPatches.add(handle, patch);
2699 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2700 "sink handle %d",
2701 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2702 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2703 return NO_ERROR;
2704}
2705
2706status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2707{
2708 ssize_t index = mAudioPatches.indexOfKey(handle);
2709
2710 if (index < 0) {
2711 ALOGW("removeAudioPatch() patch %d not in", handle);
2712 return ALREADY_EXISTS;
2713 }
2714 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2715 mAudioPatches.valueAt(index)->mAfPatchHandle);
2716 mAudioPatches.removeItemsAt(index);
2717 return NO_ERROR;
2718}
2719
Eric Laurente552edb2014-03-10 17:42:56 -07002720// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002721// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002722// ----------------------------------------------------------------------------
2723
Eric Laurent3a4311c2014-03-17 12:00:47 -07002724uint32_t AudioPolicyManager::nextUniqueId()
2725{
2726 return android_atomic_inc(&mNextUniqueId);
2727}
2728
Eric Laurent6a94d692014-05-20 11:18:06 -07002729uint32_t AudioPolicyManager::nextAudioPortGeneration()
2730{
2731 return android_atomic_inc(&mAudioPortGeneration);
2732}
2733
Eric Laurente0720872014-03-11 09:30:41 -07002734AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002735 :
2736#ifdef AUDIO_POLICY_TEST
2737 Thread(false),
2738#endif //AUDIO_POLICY_TEST
2739 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002740 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002741 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2742 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002743 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002744 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002745 mAudioPortGeneration(1),
2746 mBeaconMuteRefCount(0),
2747 mBeaconPlayingRefCount(0),
2748 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002749{
Eric Laurent6a94d692014-05-20 11:18:06 -07002750 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002751 mpClientInterface = clientInterface;
2752
Eric Laurent3b73df72014-03-11 09:06:29 -07002753 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2754 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002755 }
2756
Eric Laurent1afeecb2014-05-14 08:52:28 -07002757 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002758 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2759 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2760 ALOGE("could not load audio policy configuration file, setting defaults");
2761 defaultAudioPolicyConfig();
2762 }
2763 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002764 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002765
2766 // must be done after reading the policy
2767 initializeVolumeCurves();
2768
2769 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002770 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2771 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002772 for (size_t i = 0; i < mHwModules.size(); i++) {
2773 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2774 if (mHwModules[i]->mHandle == 0) {
2775 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2776 continue;
2777 }
2778 // open all output streams needed to access attached devices
2779 // except for direct output streams that are only opened when they are actually
2780 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002781 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002782 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2783 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002784 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002785
Eric Laurent3a4311c2014-03-17 12:00:47 -07002786 if (outProfile->mSupportedDevices.isEmpty()) {
2787 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2788 continue;
2789 }
2790
Eric Laurentd78f1532014-09-16 16:38:20 -07002791 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2792 continue;
2793 }
Eric Laurent83b88082014-06-20 18:31:16 -07002794 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2795 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2796 profileType = mDefaultOutputDevice->mDeviceType;
2797 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002798 // chose first device present in mSupportedDevices also part of
2799 // outputDeviceTypes
2800 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2801 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2802 if ((profileType & outputDeviceTypes) != 0) {
2803 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002804 }
Eric Laurente552edb2014-03-10 17:42:56 -07002805 }
2806 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002807 if ((profileType & outputDeviceTypes) == 0) {
2808 continue;
2809 }
2810 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2811
2812 outputDesc->mDevice = profileType;
2813 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2814 config.sample_rate = outputDesc->mSamplingRate;
2815 config.channel_mask = outputDesc->mChannelMask;
2816 config.format = outputDesc->mFormat;
2817 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2818 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2819 &output,
2820 &config,
2821 &outputDesc->mDevice,
2822 String8(""),
2823 &outputDesc->mLatency,
2824 outputDesc->mFlags);
2825
2826 if (status != NO_ERROR) {
2827 ALOGW("Cannot open output stream for device %08x on hw module %s",
2828 outputDesc->mDevice,
2829 mHwModules[i]->mName);
2830 } else {
2831 outputDesc->mSamplingRate = config.sample_rate;
2832 outputDesc->mChannelMask = config.channel_mask;
2833 outputDesc->mFormat = config.format;
2834
2835 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2836 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2837 ssize_t index =
2838 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2839 // give a valid ID to an attached device once confirmed it is reachable
2840 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2841 mAvailableOutputDevices[index]->mId = nextUniqueId();
2842 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2843 }
2844 }
2845 if (mPrimaryOutput == 0 &&
2846 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2847 mPrimaryOutput = output;
2848 }
2849 addOutput(output, outputDesc);
2850 setOutputDevice(output,
2851 outputDesc->mDevice,
2852 true);
2853 }
Eric Laurente552edb2014-03-10 17:42:56 -07002854 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002855 // open input streams needed to access attached devices to validate
2856 // mAvailableInputDevices list
2857 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2858 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002859 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002860
Eric Laurent3a4311c2014-03-17 12:00:47 -07002861 if (inProfile->mSupportedDevices.isEmpty()) {
2862 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2863 continue;
2864 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002865 // chose first device present in mSupportedDevices also part of
2866 // inputDeviceTypes
2867 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2868 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2869 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2870 if (profileType & inputDeviceTypes) {
2871 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002872 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002873 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002874 if ((profileType & inputDeviceTypes) == 0) {
2875 continue;
2876 }
2877 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2878
2879 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2880 inputDesc->mDevice = profileType;
2881
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002882 // find the address
2883 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
2884 // the inputs vector must be of size 1, but we don't want to crash here
2885 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
2886 : String8("");
2887 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
2888 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
2889
Eric Laurentd78f1532014-09-16 16:38:20 -07002890 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2891 config.sample_rate = inputDesc->mSamplingRate;
2892 config.channel_mask = inputDesc->mChannelMask;
2893 config.format = inputDesc->mFormat;
2894 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2895 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2896 &input,
2897 &config,
2898 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002899 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07002900 AUDIO_SOURCE_MIC,
2901 AUDIO_INPUT_FLAG_NONE);
2902
2903 if (status == NO_ERROR) {
2904 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2905 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2906 ssize_t index =
2907 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2908 // give a valid ID to an attached device once confirmed it is reachable
2909 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2910 mAvailableInputDevices[index]->mId = nextUniqueId();
2911 mAvailableInputDevices[index]->mModule = mHwModules[i];
2912 }
2913 }
2914 mpClientInterface->closeInput(input);
2915 } else {
2916 ALOGW("Cannot open input stream for device %08x on hw module %s",
2917 inputDesc->mDevice,
2918 mHwModules[i]->mName);
2919 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002920 }
2921 }
2922 // make sure all attached devices have been allocated a unique ID
2923 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2924 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002925 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002926 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2927 continue;
2928 }
2929 i++;
2930 }
2931 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2932 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002933 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002934 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2935 continue;
2936 }
2937 i++;
2938 }
2939 // make sure default device is reachable
2940 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002941 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002942 }
Eric Laurente552edb2014-03-10 17:42:56 -07002943
2944 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2945
2946 updateDevicesAndOutputs();
2947
2948#ifdef AUDIO_POLICY_TEST
2949 if (mPrimaryOutput != 0) {
2950 AudioParameter outputCmd = AudioParameter();
2951 outputCmd.addInt(String8("set_id"), 0);
2952 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2953
2954 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2955 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002956 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2957 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002958 mTestLatencyMs = 0;
2959 mCurOutput = 0;
2960 mDirectOutput = false;
2961 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2962 mTestOutputs[i] = 0;
2963 }
2964
2965 const size_t SIZE = 256;
2966 char buffer[SIZE];
2967 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2968 run(buffer, ANDROID_PRIORITY_AUDIO);
2969 }
2970#endif //AUDIO_POLICY_TEST
2971}
2972
Eric Laurente0720872014-03-11 09:30:41 -07002973AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002974{
2975#ifdef AUDIO_POLICY_TEST
2976 exit();
2977#endif //AUDIO_POLICY_TEST
2978 for (size_t i = 0; i < mOutputs.size(); i++) {
2979 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002980 }
2981 for (size_t i = 0; i < mInputs.size(); i++) {
2982 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002983 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002984 mAvailableOutputDevices.clear();
2985 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002986 mOutputs.clear();
2987 mInputs.clear();
2988 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002989}
2990
Eric Laurente0720872014-03-11 09:30:41 -07002991status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002992{
2993 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2994}
2995
2996#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002997bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002998{
2999 ALOGV("entering threadLoop()");
3000 while (!exitPending())
3001 {
3002 String8 command;
3003 int valueInt;
3004 String8 value;
3005
3006 Mutex::Autolock _l(mLock);
3007 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3008
3009 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3010 AudioParameter param = AudioParameter(command);
3011
3012 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3013 valueInt != 0) {
3014 ALOGV("Test command %s received", command.string());
3015 String8 target;
3016 if (param.get(String8("target"), target) != NO_ERROR) {
3017 target = "Manager";
3018 }
3019 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3020 param.remove(String8("test_cmd_policy_output"));
3021 mCurOutput = valueInt;
3022 }
3023 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3024 param.remove(String8("test_cmd_policy_direct"));
3025 if (value == "false") {
3026 mDirectOutput = false;
3027 } else if (value == "true") {
3028 mDirectOutput = true;
3029 }
3030 }
3031 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3032 param.remove(String8("test_cmd_policy_input"));
3033 mTestInput = valueInt;
3034 }
3035
3036 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3037 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003038 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003039 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003040 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003041 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003042 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003043 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003044 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003045 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003046 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003047 if (target == "Manager") {
3048 mTestFormat = format;
3049 } else if (mTestOutputs[mCurOutput] != 0) {
3050 AudioParameter outputParam = AudioParameter();
3051 outputParam.addInt(String8("format"), format);
3052 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3053 }
3054 }
3055 }
3056 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3057 param.remove(String8("test_cmd_policy_channels"));
3058 int channels = 0;
3059
3060 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003061 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003062 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003063 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003064 }
3065 if (channels != 0) {
3066 if (target == "Manager") {
3067 mTestChannels = channels;
3068 } else if (mTestOutputs[mCurOutput] != 0) {
3069 AudioParameter outputParam = AudioParameter();
3070 outputParam.addInt(String8("channels"), channels);
3071 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3072 }
3073 }
3074 }
3075 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3076 param.remove(String8("test_cmd_policy_sampleRate"));
3077 if (valueInt >= 0 && valueInt <= 96000) {
3078 int samplingRate = valueInt;
3079 if (target == "Manager") {
3080 mTestSamplingRate = samplingRate;
3081 } else if (mTestOutputs[mCurOutput] != 0) {
3082 AudioParameter outputParam = AudioParameter();
3083 outputParam.addInt(String8("sampling_rate"), samplingRate);
3084 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3085 }
3086 }
3087 }
3088
3089 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3090 param.remove(String8("test_cmd_policy_reopen"));
3091
Eric Laurent1f2f2232014-06-02 12:01:23 -07003092 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003093 mpClientInterface->closeOutput(mPrimaryOutput);
3094
3095 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3096
Eric Laurente552edb2014-03-10 17:42:56 -07003097 mOutputs.removeItem(mPrimaryOutput);
3098
Eric Laurent1f2f2232014-06-02 12:01:23 -07003099 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003100 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003101 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3102 config.sample_rate = outputDesc->mSamplingRate;
3103 config.channel_mask = outputDesc->mChannelMask;
3104 config.format = outputDesc->mFormat;
3105 status_t status = mpClientInterface->openOutput(moduleHandle,
3106 &mPrimaryOutput,
3107 &config,
3108 &outputDesc->mDevice,
3109 String8(""),
3110 &outputDesc->mLatency,
3111 outputDesc->mFlags);
3112 if (status != NO_ERROR) {
3113 ALOGE("Failed to reopen hardware output stream, "
3114 "samplingRate: %d, format %d, channels %d",
3115 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003116 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003117 outputDesc->mSamplingRate = config.sample_rate;
3118 outputDesc->mChannelMask = config.channel_mask;
3119 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003120 AudioParameter outputCmd = AudioParameter();
3121 outputCmd.addInt(String8("set_id"), 0);
3122 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3123 addOutput(mPrimaryOutput, outputDesc);
3124 }
3125 }
3126
3127
3128 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3129 }
3130 }
3131 return false;
3132}
3133
Eric Laurente0720872014-03-11 09:30:41 -07003134void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003135{
3136 {
3137 AutoMutex _l(mLock);
3138 requestExit();
3139 mWaitWorkCV.signal();
3140 }
3141 requestExitAndWait();
3142}
3143
Eric Laurente0720872014-03-11 09:30:41 -07003144int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003145{
3146 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3147 if (output == mTestOutputs[i]) return i;
3148 }
3149 return 0;
3150}
3151#endif //AUDIO_POLICY_TEST
3152
3153// ---
3154
Eric Laurent1f2f2232014-06-02 12:01:23 -07003155void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003156{
Eric Laurent1c333e22014-05-20 10:48:17 -07003157 outputDesc->mIoHandle = output;
3158 outputDesc->mId = nextUniqueId();
3159 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003160 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003161}
3162
Eric Laurent1f2f2232014-06-02 12:01:23 -07003163void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003164{
Eric Laurent1c333e22014-05-20 10:48:17 -07003165 inputDesc->mIoHandle = input;
3166 inputDesc->mId = nextUniqueId();
3167 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003168 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003169}
Eric Laurente552edb2014-03-10 17:42:56 -07003170
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003171void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3172 const String8 address /*in*/,
3173 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3174 // look for a match on the given address on the addresses of the outputs:
3175 // find the address by finding the patch that maps to this output
3176 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3177 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3178 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3179 if (patchIdx >= 0) {
3180 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3181 const int numSinks = patchDesc->mPatch.num_sinks;
3182 for (ssize_t j=0; j < numSinks; j++) {
3183 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3184 const char* patchAddr =
3185 patchDesc->mPatch.sinks[j].ext.device.address;
3186 if (strncmp(patchAddr,
3187 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003188 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003189 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3190 outputs.add(desc->mIoHandle);
3191 break;
3192 }
3193 }
3194 }
3195 }
3196}
3197
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003198status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003199 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003200 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003201 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003202{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003203 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003204 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003205 // erase all current sample rates, formats and channel masks
3206 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003207
Eric Laurent3b73df72014-03-11 09:06:29 -07003208 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003209 // first list already open outputs that can be routed to this device
3210 for (size_t i = 0; i < mOutputs.size(); i++) {
3211 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003212 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003213 if (!deviceDistinguishesOnAddress(device)) {
3214 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3215 outputs.add(mOutputs.keyAt(i));
3216 } else {
3217 ALOGV(" checking address match due to device 0x%x", device);
3218 findIoHandlesByAddress(desc, address, outputs);
3219 }
Eric Laurente552edb2014-03-10 17:42:56 -07003220 }
3221 }
3222 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003223 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003224 for (size_t i = 0; i < mHwModules.size(); i++)
3225 {
3226 if (mHwModules[i]->mHandle == 0) {
3227 continue;
3228 }
3229 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3230 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003231 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003232 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003233 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3234 }
3235 }
3236 }
3237
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003238 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3239
Eric Laurente552edb2014-03-10 17:42:56 -07003240 if (profiles.isEmpty() && outputs.isEmpty()) {
3241 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3242 return BAD_VALUE;
3243 }
3244
3245 // open outputs for matching profiles if needed. Direct outputs are also opened to
3246 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3247 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003248 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003249
3250 // nothing to do if one output is already opened for this profile
3251 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003252 for (j = 0; j < outputs.size(); j++) {
3253 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003254 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003255 // matching profile: save the sample rates, format and channel masks supported
3256 // by the profile in our device descriptor
3257 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003258 break;
3259 }
3260 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003261 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003262 continue;
3263 }
3264
Eric Laurent83b88082014-06-20 18:31:16 -07003265 ALOGV("opening output for device %08x with params %s profile %p",
3266 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003267 desc = new AudioOutputDescriptor(profile);
3268 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003269 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3270 config.sample_rate = desc->mSamplingRate;
3271 config.channel_mask = desc->mChannelMask;
3272 config.format = desc->mFormat;
3273 config.offload_info.sample_rate = desc->mSamplingRate;
3274 config.offload_info.channel_mask = desc->mChannelMask;
3275 config.offload_info.format = desc->mFormat;
3276 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3277 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3278 &output,
3279 &config,
3280 &desc->mDevice,
3281 address,
3282 &desc->mLatency,
3283 desc->mFlags);
3284 if (status == NO_ERROR) {
3285 desc->mSamplingRate = config.sample_rate;
3286 desc->mChannelMask = config.channel_mask;
3287 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003288
Eric Laurentd4692962014-05-05 18:13:44 -07003289 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003290 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003291 char *param = audio_device_address_to_parameter(device, address);
3292 mpClientInterface->setParameters(output, String8(param));
3293 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003294 }
3295
Eric Laurentd4692962014-05-05 18:13:44 -07003296 // Here is where we step through and resolve any "dynamic" fields
3297 String8 reply;
3298 char *value;
3299 if (profile->mSamplingRates[0] == 0) {
3300 reply = mpClientInterface->getParameters(output,
3301 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003302 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003303 reply.string());
3304 value = strpbrk((char *)reply.string(), "=");
3305 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003306 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003307 }
Eric Laurentd4692962014-05-05 18:13:44 -07003308 }
3309 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3310 reply = mpClientInterface->getParameters(output,
3311 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003312 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003313 reply.string());
3314 value = strpbrk((char *)reply.string(), "=");
3315 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003316 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003317 }
Eric Laurentd4692962014-05-05 18:13:44 -07003318 }
3319 if (profile->mChannelMasks[0] == 0) {
3320 reply = mpClientInterface->getParameters(output,
3321 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003322 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003323 reply.string());
3324 value = strpbrk((char *)reply.string(), "=");
3325 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003326 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003327 }
Eric Laurentd4692962014-05-05 18:13:44 -07003328 }
3329 if (((profile->mSamplingRates[0] == 0) &&
3330 (profile->mSamplingRates.size() < 2)) ||
3331 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3332 (profile->mFormats.size() < 2)) ||
3333 ((profile->mChannelMasks[0] == 0) &&
3334 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003335 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003336 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003337 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003338 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3339 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003340 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003341 config.sample_rate = profile->pickSamplingRate();
3342 config.channel_mask = profile->pickChannelMask();
3343 config.format = profile->pickFormat();
3344 config.offload_info.sample_rate = config.sample_rate;
3345 config.offload_info.channel_mask = config.channel_mask;
3346 config.offload_info.format = config.format;
3347 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3348 &output,
3349 &config,
3350 &desc->mDevice,
3351 address,
3352 &desc->mLatency,
3353 desc->mFlags);
3354 if (status == NO_ERROR) {
3355 desc->mSamplingRate = config.sample_rate;
3356 desc->mChannelMask = config.channel_mask;
3357 desc->mFormat = config.format;
3358 } else {
3359 output = AUDIO_IO_HANDLE_NONE;
3360 }
Eric Laurentd4692962014-05-05 18:13:44 -07003361 }
3362
Eric Laurentcf2c0212014-07-25 16:20:43 -07003363 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003364 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003365 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003366 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003367
Eric Laurentd4692962014-05-05 18:13:44 -07003368 // set initial stream volume for device
3369 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003370
Eric Laurentd4692962014-05-05 18:13:44 -07003371 //TODO: configure audio effect output stage here
3372
3373 // open a duplicating output thread for the new output and the primary output
3374 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3375 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003376 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003377 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003378 sp<AudioOutputDescriptor> dupOutputDesc =
3379 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003380 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3381 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3382 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3383 dupOutputDesc->mFormat = desc->mFormat;
3384 dupOutputDesc->mChannelMask = desc->mChannelMask;
3385 dupOutputDesc->mLatency = desc->mLatency;
3386 addOutput(duplicatedOutput, dupOutputDesc);
3387 applyStreamVolumes(duplicatedOutput, device, 0, true);
3388 } else {
3389 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3390 mPrimaryOutput, output);
3391 mpClientInterface->closeOutput(output);
3392 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003393 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003394 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003395 }
Eric Laurente552edb2014-03-10 17:42:56 -07003396 }
3397 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003398 } else {
3399 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003400 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003401 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003402 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003403 profiles.removeAt(profile_index);
3404 profile_index--;
3405 } else {
3406 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003407 devDesc->importAudioPort(profile);
3408
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003409 if (deviceDistinguishesOnAddress(device)) {
3410 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3411 device, address.string());
3412 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3413 NULL/*patch handle*/, address.string());
3414 }
Eric Laurente552edb2014-03-10 17:42:56 -07003415 ALOGV("checkOutputsForDevice(): adding output %d", output);
3416 }
3417 }
3418
3419 if (profiles.isEmpty()) {
3420 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3421 return BAD_VALUE;
3422 }
Eric Laurentd4692962014-05-05 18:13:44 -07003423 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003424 // check if one opened output is not needed any more after disconnecting one device
3425 for (size_t i = 0; i < mOutputs.size(); i++) {
3426 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003427 if (!desc->isDuplicated()) {
3428 if (!(desc->mProfile->mSupportedDevices.types()
3429 & mAvailableOutputDevices.types())) {
3430 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3431 mOutputs.keyAt(i));
3432 outputs.add(mOutputs.keyAt(i));
3433 } else if (deviceDistinguishesOnAddress(device) &&
3434 // exact match on device
3435 (desc->mProfile->mSupportedDevices.types() == device)) {
3436 findIoHandlesByAddress(desc, address, outputs);
3437 }
Eric Laurente552edb2014-03-10 17:42:56 -07003438 }
3439 }
Eric Laurentd4692962014-05-05 18:13:44 -07003440 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003441 for (size_t i = 0; i < mHwModules.size(); i++)
3442 {
3443 if (mHwModules[i]->mHandle == 0) {
3444 continue;
3445 }
3446 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3447 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003448 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003449 if (profile->mSupportedDevices.types() & device) {
3450 ALOGV("checkOutputsForDevice(): "
3451 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003452 if (profile->mSamplingRates[0] == 0) {
3453 profile->mSamplingRates.clear();
3454 profile->mSamplingRates.add(0);
3455 }
3456 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3457 profile->mFormats.clear();
3458 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3459 }
3460 if (profile->mChannelMasks[0] == 0) {
3461 profile->mChannelMasks.clear();
3462 profile->mChannelMasks.add(0);
3463 }
3464 }
3465 }
3466 }
3467 }
3468 return NO_ERROR;
3469}
3470
Eric Laurentd4692962014-05-05 18:13:44 -07003471status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3472 audio_policy_dev_state_t state,
3473 SortedVector<audio_io_handle_t>& inputs,
3474 const String8 address)
3475{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003476 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003477 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3478 // first list already open inputs that can be routed to this device
3479 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3480 desc = mInputs.valueAt(input_index);
3481 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3482 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3483 inputs.add(mInputs.keyAt(input_index));
3484 }
3485 }
3486
3487 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003488 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003489 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3490 {
3491 if (mHwModules[module_idx]->mHandle == 0) {
3492 continue;
3493 }
3494 for (size_t profile_index = 0;
3495 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3496 profile_index++)
3497 {
3498 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3499 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003500 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003501 profile_index, module_idx);
3502 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3503 }
3504 }
3505 }
3506
3507 if (profiles.isEmpty() && inputs.isEmpty()) {
3508 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3509 return BAD_VALUE;
3510 }
3511
3512 // open inputs for matching profiles if needed. Direct inputs are also opened to
3513 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3514 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3515
Eric Laurent1c333e22014-05-20 10:48:17 -07003516 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003517 // nothing to do if one input is already opened for this profile
3518 size_t input_index;
3519 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3520 desc = mInputs.valueAt(input_index);
3521 if (desc->mProfile == profile) {
3522 break;
3523 }
3524 }
3525 if (input_index != mInputs.size()) {
3526 continue;
3527 }
3528
3529 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3530 desc = new AudioInputDescriptor(profile);
3531 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003532 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3533 config.sample_rate = desc->mSamplingRate;
3534 config.channel_mask = desc->mChannelMask;
3535 config.format = desc->mFormat;
3536 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3537 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3538 &input,
3539 &config,
3540 &desc->mDevice,
3541 address,
3542 AUDIO_SOURCE_MIC,
3543 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003544
Eric Laurentcf2c0212014-07-25 16:20:43 -07003545 if (status == NO_ERROR) {
3546 desc->mSamplingRate = config.sample_rate;
3547 desc->mChannelMask = config.channel_mask;
3548 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003549
Eric Laurentd4692962014-05-05 18:13:44 -07003550 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003551 char *param = audio_device_address_to_parameter(device, address);
3552 mpClientInterface->setParameters(input, String8(param));
3553 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003554 }
3555
3556 // Here is where we step through and resolve any "dynamic" fields
3557 String8 reply;
3558 char *value;
3559 if (profile->mSamplingRates[0] == 0) {
3560 reply = mpClientInterface->getParameters(input,
3561 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3562 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3563 reply.string());
3564 value = strpbrk((char *)reply.string(), "=");
3565 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003566 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003567 }
3568 }
3569 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3570 reply = mpClientInterface->getParameters(input,
3571 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3572 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3573 value = strpbrk((char *)reply.string(), "=");
3574 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003575 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003576 }
3577 }
3578 if (profile->mChannelMasks[0] == 0) {
3579 reply = mpClientInterface->getParameters(input,
3580 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3581 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3582 reply.string());
3583 value = strpbrk((char *)reply.string(), "=");
3584 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003585 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003586 }
3587 }
3588 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3589 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3590 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3591 ALOGW("checkInputsForDevice() direct input missing param");
3592 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003593 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003594 }
3595
3596 if (input != 0) {
3597 addInput(input, desc);
3598 }
3599 } // endif input != 0
3600
Eric Laurentcf2c0212014-07-25 16:20:43 -07003601 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003602 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003603 profiles.removeAt(profile_index);
3604 profile_index--;
3605 } else {
3606 inputs.add(input);
3607 ALOGV("checkInputsForDevice(): adding input %d", input);
3608 }
3609 } // end scan profiles
3610
3611 if (profiles.isEmpty()) {
3612 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3613 return BAD_VALUE;
3614 }
3615 } else {
3616 // Disconnect
3617 // check if one opened input is not needed any more after disconnecting one device
3618 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3619 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003620 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3621 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003622 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3623 mInputs.keyAt(input_index));
3624 inputs.add(mInputs.keyAt(input_index));
3625 }
3626 }
3627 // Clear any profiles associated with the disconnected device.
3628 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3629 if (mHwModules[module_index]->mHandle == 0) {
3630 continue;
3631 }
3632 for (size_t profile_index = 0;
3633 profile_index < mHwModules[module_index]->mInputProfiles.size();
3634 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003635 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003636 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003637 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003638 profile_index, module_index);
3639 if (profile->mSamplingRates[0] == 0) {
3640 profile->mSamplingRates.clear();
3641 profile->mSamplingRates.add(0);
3642 }
3643 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3644 profile->mFormats.clear();
3645 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3646 }
3647 if (profile->mChannelMasks[0] == 0) {
3648 profile->mChannelMasks.clear();
3649 profile->mChannelMasks.add(0);
3650 }
3651 }
3652 }
3653 }
3654 } // end disconnect
3655
3656 return NO_ERROR;
3657}
3658
3659
Eric Laurente0720872014-03-11 09:30:41 -07003660void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003661{
3662 ALOGV("closeOutput(%d)", output);
3663
Eric Laurent1f2f2232014-06-02 12:01:23 -07003664 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003665 if (outputDesc == NULL) {
3666 ALOGW("closeOutput() unknown output %d", output);
3667 return;
3668 }
3669
3670 // look for duplicated outputs connected to the output being removed.
3671 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003672 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003673 if (dupOutputDesc->isDuplicated() &&
3674 (dupOutputDesc->mOutput1 == outputDesc ||
3675 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003676 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003677 if (dupOutputDesc->mOutput1 == outputDesc) {
3678 outputDesc2 = dupOutputDesc->mOutput2;
3679 } else {
3680 outputDesc2 = dupOutputDesc->mOutput1;
3681 }
3682 // As all active tracks on duplicated output will be deleted,
3683 // and as they were also referenced on the other output, the reference
3684 // count for their stream type must be adjusted accordingly on
3685 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003686 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003687 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003688 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003689 }
3690 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3691 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3692
3693 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003694 mOutputs.removeItem(duplicatedOutput);
3695 }
3696 }
3697
Eric Laurent05b90f82014-08-27 15:32:29 -07003698 nextAudioPortGeneration();
3699
3700 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3701 if (index >= 0) {
3702 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3703 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3704 mAudioPatches.removeItemsAt(index);
3705 mpClientInterface->onAudioPatchListUpdate();
3706 }
3707
Eric Laurente552edb2014-03-10 17:42:56 -07003708 AudioParameter param;
3709 param.add(String8("closing"), String8("true"));
3710 mpClientInterface->setParameters(output, param.toString());
3711
3712 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003713 mOutputs.removeItem(output);
3714 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003715}
3716
3717void AudioPolicyManager::closeInput(audio_io_handle_t input)
3718{
3719 ALOGV("closeInput(%d)", input);
3720
3721 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3722 if (inputDesc == NULL) {
3723 ALOGW("closeInput() unknown input %d", input);
3724 return;
3725 }
3726
Eric Laurent6a94d692014-05-20 11:18:06 -07003727 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003728
3729 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3730 if (index >= 0) {
3731 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3732 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3733 mAudioPatches.removeItemsAt(index);
3734 mpClientInterface->onAudioPatchListUpdate();
3735 }
3736
3737 mpClientInterface->closeInput(input);
3738 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003739}
3740
Eric Laurente0720872014-03-11 09:30:41 -07003741SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003742 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003743{
3744 SortedVector<audio_io_handle_t> outputs;
3745
3746 ALOGVV("getOutputsForDevice() device %04x", device);
3747 for (size_t i = 0; i < openOutputs.size(); i++) {
3748 ALOGVV("output %d isDuplicated=%d device=%04x",
3749 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3750 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3751 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3752 outputs.add(openOutputs.keyAt(i));
3753 }
3754 }
3755 return outputs;
3756}
3757
Eric Laurente0720872014-03-11 09:30:41 -07003758bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003759 SortedVector<audio_io_handle_t>& outputs2)
3760{
3761 if (outputs1.size() != outputs2.size()) {
3762 return false;
3763 }
3764 for (size_t i = 0; i < outputs1.size(); i++) {
3765 if (outputs1[i] != outputs2[i]) {
3766 return false;
3767 }
3768 }
3769 return true;
3770}
3771
Eric Laurente0720872014-03-11 09:30:41 -07003772void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003773{
3774 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3775 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3776 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3777 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3778
3779 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3780 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3781 strategy, srcOutputs[0], dstOutputs[0]);
3782 // mute strategy while moving tracks from one output to another
3783 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003784 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003785 if (desc->isStrategyActive(strategy)) {
3786 setStrategyMute(strategy, true, srcOutputs[i]);
3787 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3788 }
3789 }
3790
3791 // Move effects associated to this strategy from previous output to new output
3792 if (strategy == STRATEGY_MEDIA) {
3793 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3794 SortedVector<audio_io_handle_t> moved;
3795 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003796 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3797 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3798 effectDesc->mIo != fxOutput) {
3799 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003800 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3801 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003802 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003803 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003804 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003805 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003806 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003807 }
3808 }
3809 }
3810 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003811 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08003812 if (i == AUDIO_STREAM_PATCH) {
3813 continue;
3814 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003815 if (getStrategy((audio_stream_type_t)i) == strategy) {
3816 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003817 }
3818 }
3819 }
3820}
3821
Eric Laurente0720872014-03-11 09:30:41 -07003822void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003823{
Jon Eklund966095e2014-09-09 15:39:49 -05003824 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3825 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003826 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003827 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3828 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003829 checkOutputForStrategy(STRATEGY_SONIFICATION);
3830 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003831 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07003832 checkOutputForStrategy(STRATEGY_MEDIA);
3833 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003834 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07003835}
3836
Eric Laurente0720872014-03-11 09:30:41 -07003837audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003838{
Eric Laurente552edb2014-03-10 17:42:56 -07003839 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003840 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003841 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3842 return mOutputs.keyAt(i);
3843 }
3844 }
3845
3846 return 0;
3847}
3848
Eric Laurente0720872014-03-11 09:30:41 -07003849void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003850{
Eric Laurente552edb2014-03-10 17:42:56 -07003851 audio_io_handle_t a2dpOutput = getA2dpOutput();
3852 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003853 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003854 return;
3855 }
3856
Eric Laurent3a4311c2014-03-17 12:00:47 -07003857 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08003858 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
3859 ~AUDIO_DEVICE_BIT_IN) != 0) ||
3860 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003861 // suspend A2DP output if:
3862 // (NOT already suspended) &&
3863 // ((SCO device is connected &&
3864 // (forced usage for communication || for record is SCO))) ||
3865 // (phone state is ringing || in call)
3866 //
3867 // restore A2DP output if:
3868 // (Already suspended) &&
3869 // ((SCO device is NOT connected ||
3870 // (forced usage NOT for communication && NOT for record is SCO))) &&
3871 // (phone state is NOT ringing && NOT in call)
3872 //
3873 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003874 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003875 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3876 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3877 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3878 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003879
3880 mpClientInterface->restoreOutput(a2dpOutput);
3881 mA2dpSuspended = false;
3882 }
3883 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003884 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003885 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3886 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3887 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3888 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003889
3890 mpClientInterface->suspendOutput(a2dpOutput);
3891 mA2dpSuspended = true;
3892 }
3893 }
3894}
3895
Eric Laurent1c333e22014-05-20 10:48:17 -07003896audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003897{
3898 audio_devices_t device = AUDIO_DEVICE_NONE;
3899
Eric Laurent1f2f2232014-06-02 12:01:23 -07003900 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003901
3902 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3903 if (index >= 0) {
3904 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3905 if (patchDesc->mUid != mUidCached) {
3906 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3907 outputDesc->device(), outputDesc->mPatchHandle);
3908 return outputDesc->device();
3909 }
3910 }
3911
Eric Laurente552edb2014-03-10 17:42:56 -07003912 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003913 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003914 // use device for strategy enforced audible
3915 // 2: we are in call or the strategy phone is active on the output:
3916 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003917 // 3: the strategy for enforced audible is active but not enforced on the output:
3918 // use the device for strategy enforced audible
3919 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003920 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003921 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003922 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08003923 // 6: the strategy accessibility is active on the output:
3924 // use device for strategy accessibility
3925 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003926 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08003927 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003928 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08003929 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003930 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05003931 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3932 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003933 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3934 } else if (isInCall() ||
3935 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3936 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003937 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3938 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003939 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3940 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3941 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3942 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003943 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
3944 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003945 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3946 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3947 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3948 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003949 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
3950 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003951 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
3952 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003953 }
3954
Eric Laurent1c333e22014-05-20 10:48:17 -07003955 ALOGV("getNewOutputDevice() selected device %x", device);
3956 return device;
3957}
3958
3959audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3960{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003961 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003962
3963 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3964 if (index >= 0) {
3965 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3966 if (patchDesc->mUid != mUidCached) {
3967 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3968 inputDesc->mDevice, inputDesc->mPatchHandle);
3969 return inputDesc->mDevice;
3970 }
3971 }
3972
Eric Laurent1c333e22014-05-20 10:48:17 -07003973 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3974
3975 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003976 return device;
3977}
3978
Eric Laurente0720872014-03-11 09:30:41 -07003979uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003980 return (uint32_t)getStrategy(stream);
3981}
3982
Eric Laurente0720872014-03-11 09:30:41 -07003983audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003984 // By checking the range of stream before calling getStrategy, we avoid
3985 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3986 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08003987 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003988 return AUDIO_DEVICE_NONE;
3989 }
3990 audio_devices_t devices;
3991 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3992 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3993 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3994 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003995 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003996 if (outputDesc->isStrategyActive(strategy)) {
3997 devices = outputDesc->device();
3998 break;
3999 }
Eric Laurente552edb2014-03-10 17:42:56 -07004000 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004001
4002 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4003 and doesn't really need to.*/
4004 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4005 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4006 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4007 }
4008
Eric Laurente552edb2014-03-10 17:42:56 -07004009 return devices;
4010}
4011
Eric Laurente0720872014-03-11 09:30:41 -07004012AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004013 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004014
4015 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4016
Eric Laurente552edb2014-03-10 17:42:56 -07004017 // stream to strategy mapping
4018 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004019 case AUDIO_STREAM_VOICE_CALL:
4020 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004021 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004022 case AUDIO_STREAM_RING:
4023 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004024 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004025 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004026 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004027 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004028 return STRATEGY_DTMF;
4029 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004030 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004031 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004032 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4033 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004034 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004035 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004036 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004037 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004038 case AUDIO_STREAM_TTS:
4039 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004040 case AUDIO_STREAM_ACCESSIBILITY:
4041 return STRATEGY_ACCESSIBILITY;
4042 case AUDIO_STREAM_REROUTING:
4043 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004044 }
4045}
4046
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004047uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4048 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004049 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4050 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4051 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004052 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4053 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4054 }
4055
4056 // usage to strategy mapping
4057 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004058 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4059 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4060 return (uint32_t) STRATEGY_SONIFICATION;
4061 }
4062 if (isInCall()) {
4063 return (uint32_t) STRATEGY_PHONE;
4064 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004065 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004066
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004067 case AUDIO_USAGE_MEDIA:
4068 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004069 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4070 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4071 return (uint32_t) STRATEGY_MEDIA;
4072
4073 case AUDIO_USAGE_VOICE_COMMUNICATION:
4074 return (uint32_t) STRATEGY_PHONE;
4075
4076 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4077 return (uint32_t) STRATEGY_DTMF;
4078
4079 case AUDIO_USAGE_ALARM:
4080 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4081 return (uint32_t) STRATEGY_SONIFICATION;
4082
4083 case AUDIO_USAGE_NOTIFICATION:
4084 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4085 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4086 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4087 case AUDIO_USAGE_NOTIFICATION_EVENT:
4088 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4089
4090 case AUDIO_USAGE_UNKNOWN:
4091 default:
4092 return (uint32_t) STRATEGY_MEDIA;
4093 }
4094}
4095
Eric Laurente0720872014-03-11 09:30:41 -07004096void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004097 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004098 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004099 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4100 updateDevicesAndOutputs();
4101 break;
4102 default:
4103 break;
4104 }
4105}
4106
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004107bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4108 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4109 if (s == (size_t) streamToIgnore) {
4110 continue;
4111 }
4112 for (size_t i = 0; i < mOutputs.size(); i++) {
4113 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4114 if (outputDesc->mRefCount[s] != 0) {
4115 return true;
4116 }
4117 }
4118 }
4119 return false;
4120}
4121
4122uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4123 switch(event) {
4124 case STARTING_OUTPUT:
4125 mBeaconMuteRefCount++;
4126 break;
4127 case STOPPING_OUTPUT:
4128 if (mBeaconMuteRefCount > 0) {
4129 mBeaconMuteRefCount--;
4130 }
4131 break;
4132 case STARTING_BEACON:
4133 mBeaconPlayingRefCount++;
4134 break;
4135 case STOPPING_BEACON:
4136 if (mBeaconPlayingRefCount > 0) {
4137 mBeaconPlayingRefCount--;
4138 }
4139 break;
4140 }
4141
4142 if (mBeaconMuteRefCount > 0) {
4143 // any playback causes beacon to be muted
4144 return setBeaconMute(true);
4145 } else {
4146 // no other playback: unmute when beacon starts playing, mute when it stops
4147 return setBeaconMute(mBeaconPlayingRefCount == 0);
4148 }
4149}
4150
4151uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4152 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4153 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4154 // keep track of muted state to avoid repeating mute/unmute operations
4155 if (mBeaconMuted != mute) {
4156 // mute/unmute AUDIO_STREAM_TTS on all outputs
4157 ALOGV("\t muting %d", mute);
4158 uint32_t maxLatency = 0;
4159 for (size_t i = 0; i < mOutputs.size(); i++) {
4160 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4161 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4162 desc->mIoHandle,
4163 0 /*delay*/, AUDIO_DEVICE_NONE);
4164 const uint32_t latency = desc->latency() * 2;
4165 if (latency > maxLatency) {
4166 maxLatency = latency;
4167 }
4168 }
4169 mBeaconMuted = mute;
4170 return maxLatency;
4171 }
4172 return 0;
4173}
4174
Eric Laurente0720872014-03-11 09:30:41 -07004175audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004176 bool fromCache)
4177{
4178 uint32_t device = AUDIO_DEVICE_NONE;
4179
4180 if (fromCache) {
4181 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4182 strategy, mDeviceForStrategy[strategy]);
4183 return mDeviceForStrategy[strategy];
4184 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004185 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004186 switch (strategy) {
4187
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004188 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4189 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4190 if (!device) {
4191 ALOGE("getDeviceForStrategy() no device found for "\
4192 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4193 }
4194 break;
4195
Eric Laurente552edb2014-03-10 17:42:56 -07004196 case STRATEGY_SONIFICATION_RESPECTFUL:
4197 if (isInCall()) {
4198 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004199 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004200 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4201 // while media is playing on a remote device, use the the sonification behavior.
4202 // Note that we test this usecase before testing if media is playing because
4203 // the isStreamActive() method only informs about the activity of a stream, not
4204 // if it's for local playback. Note also that we use the same delay between both tests
4205 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004206 //user "safe" speaker if available instead of normal speaker to avoid triggering
4207 //other acoustic safety mechanisms for notification
4208 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4209 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004210 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004211 // while media is playing (or has recently played), use the same device
4212 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4213 } else {
4214 // when media is not playing anymore, fall back on the sonification behavior
4215 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004216 //user "safe" speaker if available instead of normal speaker to avoid triggering
4217 //other acoustic safety mechanisms for notification
4218 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4219 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004220 }
4221
4222 break;
4223
4224 case STRATEGY_DTMF:
4225 if (!isInCall()) {
4226 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4227 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4228 break;
4229 }
4230 // when in call, DTMF and PHONE strategies follow the same rules
4231 // FALL THROUGH
4232
4233 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004234 // Force use of only devices on primary output if:
4235 // - in call AND
4236 // - cannot route from voice call RX OR
4237 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4238 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4239 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4240 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4241 if (((mAvailableInputDevices.types() &
4242 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4243 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004244 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004245 AUDIO_DEVICE_API_VERSION_3_0))) {
4246 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4247 }
4248 }
Eric Laurente552edb2014-03-10 17:42:56 -07004249 // for phone strategy, we first consider the forced use and then the available devices by order
4250 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004251 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4252 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004253 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004254 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004255 if (device) break;
4256 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004257 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004258 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004259 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004260 if (device) break;
4261 // if SCO device is requested but no SCO device is available, fall back to default case
4262 // FALL THROUGH
4263
4264 default: // FORCE_NONE
4265 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004266 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004267 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004268 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004269 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004270 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004271 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004272 if (device) break;
4273 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004274 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004275 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004276 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004277 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004278 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4279 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004280 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004281 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004282 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004283 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004284 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004285 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004286 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004287 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004288 if (device) break;
4289 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004290 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004291 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004292 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004293 if (device == AUDIO_DEVICE_NONE) {
4294 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4295 }
4296 break;
4297
Eric Laurent3b73df72014-03-11 09:06:29 -07004298 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004299 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4300 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004301 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004302 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004303 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004304 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004305 if (device) break;
4306 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004307 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004308 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004309 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004310 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004311 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004312 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004313 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004314 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004315 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004316 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004317 if (device) break;
4318 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004319 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4320 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004321 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004322 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004323 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004324 if (device == AUDIO_DEVICE_NONE) {
4325 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4326 }
4327 break;
4328 }
4329 break;
4330
4331 case STRATEGY_SONIFICATION:
4332
4333 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4334 // handleIncallSonification().
4335 if (isInCall()) {
4336 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4337 break;
4338 }
4339 // FALL THROUGH
4340
4341 case STRATEGY_ENFORCED_AUDIBLE:
4342 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4343 // except:
4344 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4345 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4346
4347 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004348 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004349 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004350 if (device == AUDIO_DEVICE_NONE) {
4351 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4352 }
4353 }
4354 // The second device used for sonification is the same as the device used by media strategy
4355 // FALL THROUGH
4356
Eric Laurent223fd5c2014-11-11 13:43:36 -08004357 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4358 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004359 if (strategy == STRATEGY_ACCESSIBILITY) {
4360 // do not route accessibility prompts to a digital output currently configured with a
4361 // compressed format as they would likely not be mixed and dropped.
4362 for (size_t i = 0; i < mOutputs.size(); i++) {
4363 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4364 audio_devices_t devices = desc->device() &
4365 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4366 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4367 devices != AUDIO_DEVICE_NONE) {
4368 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4369 }
4370 }
4371 }
4372 // FALL THROUGH
4373
Eric Laurent223fd5c2014-11-11 13:43:36 -08004374 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004375 case STRATEGY_MEDIA: {
4376 uint32_t device2 = AUDIO_DEVICE_NONE;
4377 if (strategy != STRATEGY_SONIFICATION) {
4378 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004379 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004380 }
4381 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004382 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004383 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004384 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004385 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004386 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004387 }
4388 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004389 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004390 }
4391 }
Hochi Huang327cb702014-09-21 09:47:31 +08004392 if ((device2 == AUDIO_DEVICE_NONE) &&
4393 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4394 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4395 }
Eric Laurente552edb2014-03-10 17:42:56 -07004396 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004397 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004398 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004399 if ((device2 == AUDIO_DEVICE_NONE)) {
4400 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4401 }
Eric Laurente552edb2014-03-10 17:42:56 -07004402 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004403 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004404 }
4405 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004406 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004407 }
4408 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004409 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004410 }
4411 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004412 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004413 }
4414 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4415 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004416 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004417 }
4418 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004419 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004420 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004421 }
4422 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004423 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004424 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004425 int device3 = AUDIO_DEVICE_NONE;
4426 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004427 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004428 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4429 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004430 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004431 }
Eric Laurente552edb2014-03-10 17:42:56 -07004432
Jungshik Jang839e4f32014-06-26 17:23:40 +09004433 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004434 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4435 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4436 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004437
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004438 // If hdmi system audio mode is on, remove speaker out of output list.
4439 if ((strategy == STRATEGY_MEDIA) &&
4440 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4441 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4442 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4443 }
4444
Eric Laurente552edb2014-03-10 17:42:56 -07004445 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004446 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004447 if (device == AUDIO_DEVICE_NONE) {
4448 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4449 }
4450 } break;
4451
4452 default:
4453 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4454 break;
4455 }
4456
4457 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4458 return device;
4459}
4460
Eric Laurente0720872014-03-11 09:30:41 -07004461void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004462{
4463 for (int i = 0; i < NUM_STRATEGIES; i++) {
4464 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4465 }
4466 mPreviousOutputs = mOutputs;
4467}
4468
Eric Laurent1f2f2232014-06-02 12:01:23 -07004469uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004470 audio_devices_t prevDevice,
4471 uint32_t delayMs)
4472{
4473 // mute/unmute strategies using an incompatible device combination
4474 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4475 // if unmuting, unmute only after the specified delay
4476 if (outputDesc->isDuplicated()) {
4477 return 0;
4478 }
4479
4480 uint32_t muteWaitMs = 0;
4481 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004482 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004483
4484 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4485 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004486 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004487 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4488 bool doMute = false;
4489
4490 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4491 doMute = true;
4492 outputDesc->mStrategyMutedByDevice[i] = true;
4493 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4494 doMute = true;
4495 outputDesc->mStrategyMutedByDevice[i] = false;
4496 }
Eric Laurent99401132014-05-07 19:48:15 -07004497 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004498 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004499 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004500 // skip output if it does not share any device with current output
4501 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4502 == AUDIO_DEVICE_NONE) {
4503 continue;
4504 }
4505 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4506 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4507 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4508 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4509 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004510 if (mute) {
4511 // FIXME: should not need to double latency if volume could be applied
4512 // immediately by the audioflinger mixer. We must account for the delay
4513 // between now and the next time the audioflinger thread for this output
4514 // will process a buffer (which corresponds to one buffer size,
4515 // usually 1/2 or 1/4 of the latency).
4516 if (muteWaitMs < desc->latency() * 2) {
4517 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004518 }
4519 }
4520 }
4521 }
4522 }
4523 }
4524
Eric Laurent99401132014-05-07 19:48:15 -07004525 // temporary mute output if device selection changes to avoid volume bursts due to
4526 // different per device volumes
4527 if (outputDesc->isActive() && (device != prevDevice)) {
4528 if (muteWaitMs < outputDesc->latency() * 2) {
4529 muteWaitMs = outputDesc->latency() * 2;
4530 }
4531 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4532 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004533 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004534 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004535 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004536 muteWaitMs *2, device);
4537 }
4538 }
4539 }
4540
Eric Laurente552edb2014-03-10 17:42:56 -07004541 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4542 if (muteWaitMs > delayMs) {
4543 muteWaitMs -= delayMs;
4544 usleep(muteWaitMs * 1000);
4545 return muteWaitMs;
4546 }
4547 return 0;
4548}
4549
Eric Laurente0720872014-03-11 09:30:41 -07004550uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004551 audio_devices_t device,
4552 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004553 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004554 audio_patch_handle_t *patchHandle,
4555 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004556{
4557 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004558 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004559 AudioParameter param;
4560 uint32_t muteWaitMs;
4561
4562 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004563 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4564 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004565 return muteWaitMs;
4566 }
4567 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4568 // output profile
4569 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004570 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004571 return 0;
4572 }
4573
4574 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004575 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004576
4577 audio_devices_t prevDevice = outputDesc->mDevice;
4578
4579 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4580
4581 if (device != AUDIO_DEVICE_NONE) {
4582 outputDesc->mDevice = device;
4583 }
4584 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4585
4586 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004587 // the requested device is AUDIO_DEVICE_NONE
4588 // OR the requested device is the same as current device
4589 // AND force is not specified
4590 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004591 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004592 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4593 outputDesc->mPatchHandle != 0) {
4594 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4595 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004596 return muteWaitMs;
4597 }
4598
4599 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004600
Eric Laurente552edb2014-03-10 17:42:56 -07004601 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004602 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004603 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004604 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004605 DeviceVector deviceList = (address == NULL) ?
4606 mAvailableOutputDevices.getDevicesFromType(device)
4607 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004608 if (!deviceList.isEmpty()) {
4609 struct audio_patch patch;
4610 outputDesc->toAudioPortConfig(&patch.sources[0]);
4611 patch.num_sources = 1;
4612 patch.num_sinks = 0;
4613 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4614 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004615 patch.num_sinks++;
4616 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004617 ssize_t index;
4618 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4619 index = mAudioPatches.indexOfKey(*patchHandle);
4620 } else {
4621 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4622 }
4623 sp< AudioPatch> patchDesc;
4624 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4625 if (index >= 0) {
4626 patchDesc = mAudioPatches.valueAt(index);
4627 afPatchHandle = patchDesc->mAfPatchHandle;
4628 }
4629
Eric Laurent1c333e22014-05-20 10:48:17 -07004630 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004631 &afPatchHandle,
4632 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004633 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4634 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004635 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004636 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004637 if (index < 0) {
4638 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4639 &patch, mUidCached);
4640 addAudioPatch(patchDesc->mHandle, patchDesc);
4641 } else {
4642 patchDesc->mPatch = patch;
4643 }
4644 patchDesc->mAfPatchHandle = afPatchHandle;
4645 patchDesc->mUid = mUidCached;
4646 if (patchHandle) {
4647 *patchHandle = patchDesc->mHandle;
4648 }
4649 outputDesc->mPatchHandle = patchDesc->mHandle;
4650 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004651 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004652 }
4653 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004654
4655 // inform all input as well
4656 for (size_t i = 0; i < mInputs.size(); i++) {
4657 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4658 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4659 AudioParameter inputCmd = AudioParameter();
4660 ALOGV("%s: inform input %d of device:%d", __func__,
4661 inputDescriptor->mIoHandle, device);
4662 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4663 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4664 inputCmd.toString(),
4665 delayMs);
4666 }
4667 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004668 }
Eric Laurente552edb2014-03-10 17:42:56 -07004669
4670 // update stream volumes according to new device
4671 applyStreamVolumes(output, device, delayMs);
4672
4673 return muteWaitMs;
4674}
4675
Eric Laurent1c333e22014-05-20 10:48:17 -07004676status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004677 int delayMs,
4678 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004679{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004680 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004681 ssize_t index;
4682 if (patchHandle) {
4683 index = mAudioPatches.indexOfKey(*patchHandle);
4684 } else {
4685 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4686 }
4687 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004688 return INVALID_OPERATION;
4689 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004690 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4691 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004692 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4693 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004694 removeAudioPatch(patchDesc->mHandle);
4695 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004696 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004697 return status;
4698}
4699
4700status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4701 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004702 bool force,
4703 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004704{
4705 status_t status = NO_ERROR;
4706
Eric Laurent1f2f2232014-06-02 12:01:23 -07004707 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004708 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4709 inputDesc->mDevice = device;
4710
4711 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4712 if (!deviceList.isEmpty()) {
4713 struct audio_patch patch;
4714 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004715 // AUDIO_SOURCE_HOTWORD is for internal use only:
4716 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004717 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4718 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004719 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4720 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004721 patch.num_sinks = 1;
4722 //only one input device for now
4723 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004724 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004725 ssize_t index;
4726 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4727 index = mAudioPatches.indexOfKey(*patchHandle);
4728 } else {
4729 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4730 }
4731 sp< AudioPatch> patchDesc;
4732 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4733 if (index >= 0) {
4734 patchDesc = mAudioPatches.valueAt(index);
4735 afPatchHandle = patchDesc->mAfPatchHandle;
4736 }
4737
Eric Laurent1c333e22014-05-20 10:48:17 -07004738 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004740 0);
4741 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004743 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 if (index < 0) {
4745 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4746 &patch, mUidCached);
4747 addAudioPatch(patchDesc->mHandle, patchDesc);
4748 } else {
4749 patchDesc->mPatch = patch;
4750 }
4751 patchDesc->mAfPatchHandle = afPatchHandle;
4752 patchDesc->mUid = mUidCached;
4753 if (patchHandle) {
4754 *patchHandle = patchDesc->mHandle;
4755 }
4756 inputDesc->mPatchHandle = patchDesc->mHandle;
4757 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004758 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004759 }
4760 }
4761 }
4762 return status;
4763}
4764
Eric Laurent6a94d692014-05-20 11:18:06 -07004765status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4766 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004767{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004768 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004769 ssize_t index;
4770 if (patchHandle) {
4771 index = mAudioPatches.indexOfKey(*patchHandle);
4772 } else {
4773 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4774 }
4775 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004776 return INVALID_OPERATION;
4777 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004778 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4779 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004780 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4781 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004782 removeAudioPatch(patchDesc->mHandle);
4783 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004784 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004785 return status;
4786}
4787
4788sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004789 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004790 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004791 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004792 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004793{
4794 // Choose an input profile based on the requested capture parameters: select the first available
4795 // profile supporting all requested parameters.
4796
4797 for (size_t i = 0; i < mHwModules.size(); i++)
4798 {
4799 if (mHwModules[i]->mHandle == 0) {
4800 continue;
4801 }
4802 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4803 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004804 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004805 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004806 if (profile->isCompatibleProfile(device, samplingRate,
4807 &samplingRate /*updatedSamplingRate*/,
4808 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004809 return profile;
4810 }
4811 }
4812 }
4813 return NULL;
4814}
4815
Eric Laurente0720872014-03-11 09:30:41 -07004816audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004817{
4818 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004819 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4820 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004821 switch (inputSource) {
4822 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004823 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004824 device = AUDIO_DEVICE_IN_VOICE_CALL;
4825 break;
4826 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004827 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004828
4829 case AUDIO_SOURCE_DEFAULT:
4830 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004831 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4832 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004833 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4834 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4835 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4836 device = AUDIO_DEVICE_IN_USB_DEVICE;
4837 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4838 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004839 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004840 break;
4841
4842 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4843 // Allow only use of devices on primary input if in call and HAL does not support routing
4844 // to voice call path.
4845 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4846 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4847 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4848 }
4849
4850 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4851 case AUDIO_POLICY_FORCE_BT_SCO:
4852 // if SCO device is requested but no SCO device is available, fall back to default case
4853 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4854 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4855 break;
4856 }
4857 // FALL THROUGH
4858
4859 default: // FORCE_NONE
4860 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4861 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4862 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4863 device = AUDIO_DEVICE_IN_USB_DEVICE;
4864 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4865 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4866 }
4867 break;
4868
4869 case AUDIO_POLICY_FORCE_SPEAKER:
4870 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4871 device = AUDIO_DEVICE_IN_BACK_MIC;
4872 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4873 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4874 }
4875 break;
4876 }
4877 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004878
Eric Laurente552edb2014-03-10 17:42:56 -07004879 case AUDIO_SOURCE_VOICE_RECOGNITION:
4880 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004881 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004882 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004883 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004884 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004885 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004886 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4887 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004888 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004889 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4890 }
4891 break;
4892 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004893 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004894 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004895 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004896 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4897 }
4898 break;
4899 case AUDIO_SOURCE_VOICE_DOWNLINK:
4900 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004901 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004902 device = AUDIO_DEVICE_IN_VOICE_CALL;
4903 }
4904 break;
4905 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004906 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004907 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4908 }
4909 break;
Hochi Huang327cb702014-09-21 09:47:31 +08004910 case AUDIO_SOURCE_FM_TUNER:
4911 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
4912 device = AUDIO_DEVICE_IN_FM_TUNER;
4913 }
4914 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004915 default:
4916 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4917 break;
4918 }
4919 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4920 return device;
4921}
4922
Eric Laurente0720872014-03-11 09:30:41 -07004923bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004924{
4925 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4926 device &= ~AUDIO_DEVICE_BIT_IN;
4927 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4928 return true;
4929 }
4930 return false;
4931}
4932
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004933bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4934 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4935}
4936
Eric Laurente0720872014-03-11 09:30:41 -07004937audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004938{
4939 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004940 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004941 if ((input_descriptor->mRefCount > 0)
4942 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4943 return mInputs.keyAt(i);
4944 }
4945 }
4946 return 0;
4947}
4948
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004949uint32_t AudioPolicyManager::activeInputsCount() const
4950{
4951 uint32_t count = 0;
4952 for (size_t i = 0; i < mInputs.size(); i++) {
4953 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4954 if (desc->mRefCount > 0) {
4955 return count++;
4956 }
4957 }
4958 return count;
4959}
4960
Eric Laurente552edb2014-03-10 17:42:56 -07004961
Eric Laurente0720872014-03-11 09:30:41 -07004962audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004963{
4964 if (device == AUDIO_DEVICE_NONE) {
4965 // this happens when forcing a route update and no track is active on an output.
4966 // In this case the returned category is not important.
4967 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004968 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004969 // Multiple device selection is either:
4970 // - speaker + one other device: give priority to speaker in this case.
4971 // - one A2DP device + another device: happens with duplicated output. In this case
4972 // retain the device on the A2DP output as the other must not correspond to an active
4973 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004974 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004975 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4976 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004977 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4978 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4979 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4980 device = AUDIO_DEVICE_OUT_AUX_LINE;
4981 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4982 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004983 } else {
4984 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4985 }
4986 }
4987
Jon Eklund11c9fb12014-06-23 14:47:03 -05004988 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4989 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4990 device = AUDIO_DEVICE_OUT_SPEAKER;
4991
Eric Laurent3b73df72014-03-11 09:06:29 -07004992 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004993 "getDeviceForVolume() invalid device combination: %08x",
4994 device);
4995
4996 return device;
4997}
4998
Eric Laurente0720872014-03-11 09:30:41 -07004999AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005000{
5001 switch(getDeviceForVolume(device)) {
5002 case AUDIO_DEVICE_OUT_EARPIECE:
5003 return DEVICE_CATEGORY_EARPIECE;
5004 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5005 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5006 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5007 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5008 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5009 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5010 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005011 case AUDIO_DEVICE_OUT_LINE:
5012 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5013 /*USB? Remote submix?*/
5014 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005015 case AUDIO_DEVICE_OUT_SPEAKER:
5016 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5017 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005018 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5019 case AUDIO_DEVICE_OUT_USB_DEVICE:
5020 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5021 default:
5022 return DEVICE_CATEGORY_SPEAKER;
5023 }
5024}
5025
Eric Laurent223fd5c2014-11-11 13:43:36 -08005026/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005027float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005028 int indexInUi)
5029{
5030 device_category deviceCategory = getDeviceCategory(device);
5031 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5032
5033 // the volume index in the UI is relative to the min and max volume indices for this stream type
5034 int nbSteps = 1 + curve[VOLMAX].mIndex -
5035 curve[VOLMIN].mIndex;
5036 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5037 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5038
5039 // find what part of the curve this index volume belongs to, or if it's out of bounds
5040 int segment = 0;
5041 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5042 return 0.0f;
5043 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5044 segment = 0;
5045 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5046 segment = 1;
5047 } else if (volIdx <= curve[VOLMAX].mIndex) {
5048 segment = 2;
5049 } else { // out of bounds
5050 return 1.0f;
5051 }
5052
5053 // linear interpolation in the attenuation table in dB
5054 float decibels = curve[segment].mDBAttenuation +
5055 ((float)(volIdx - curve[segment].mIndex)) *
5056 ( (curve[segment+1].mDBAttenuation -
5057 curve[segment].mDBAttenuation) /
5058 ((float)(curve[segment+1].mIndex -
5059 curve[segment].mIndex)) );
5060
5061 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5062
5063 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5064 curve[segment].mIndex, volIdx,
5065 curve[segment+1].mIndex,
5066 curve[segment].mDBAttenuation,
5067 decibels,
5068 curve[segment+1].mDBAttenuation,
5069 amplification);
5070
5071 return amplification;
5072}
5073
Eric Laurente0720872014-03-11 09:30:41 -07005074const AudioPolicyManager::VolumeCurvePoint
5075 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005076 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5077};
5078
Eric Laurente0720872014-03-11 09:30:41 -07005079const AudioPolicyManager::VolumeCurvePoint
5080 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005081 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5082};
5083
Eric Laurente0720872014-03-11 09:30:41 -07005084const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005085 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5086 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5087};
5088
5089const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005090 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005091 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5092};
5093
Eric Laurente0720872014-03-11 09:30:41 -07005094const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005095 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005096 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005097};
5098
5099const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005100 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005101 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5102};
5103
Eric Laurente0720872014-03-11 09:30:41 -07005104const AudioPolicyManager::VolumeCurvePoint
5105 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005106 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5107};
5108
5109// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5110// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5111// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5112// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5113
Eric Laurente0720872014-03-11 09:30:41 -07005114const AudioPolicyManager::VolumeCurvePoint
5115 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005116 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5117};
5118
Eric Laurente0720872014-03-11 09:30:41 -07005119const AudioPolicyManager::VolumeCurvePoint
5120 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005121 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5122};
5123
Eric Laurente0720872014-03-11 09:30:41 -07005124const AudioPolicyManager::VolumeCurvePoint
5125 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005126 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5127};
5128
Eric Laurente0720872014-03-11 09:30:41 -07005129const AudioPolicyManager::VolumeCurvePoint
5130 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005131 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5132};
5133
Eric Laurente0720872014-03-11 09:30:41 -07005134const AudioPolicyManager::VolumeCurvePoint
5135 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005136 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5137};
5138
Eric Laurente0720872014-03-11 09:30:41 -07005139const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005140 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5141 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5142};
5143
5144const AudioPolicyManager::VolumeCurvePoint
5145 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5146 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5147};
5148
5149const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005150 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5151 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5152};
5153
5154const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005155 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5156 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005157 { // AUDIO_STREAM_VOICE_CALL
5158 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5159 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005160 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5161 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005162 },
5163 { // AUDIO_STREAM_SYSTEM
5164 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5165 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005166 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5167 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005168 },
5169 { // AUDIO_STREAM_RING
5170 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5171 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005172 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5173 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005174 },
5175 { // AUDIO_STREAM_MUSIC
5176 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5177 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005178 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5179 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005180 },
5181 { // AUDIO_STREAM_ALARM
5182 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5183 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005184 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5185 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005186 },
5187 { // AUDIO_STREAM_NOTIFICATION
5188 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5189 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005190 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5191 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005192 },
5193 { // AUDIO_STREAM_BLUETOOTH_SCO
5194 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5195 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005196 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5197 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005198 },
5199 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5200 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5201 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005202 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5203 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005204 },
5205 { // AUDIO_STREAM_DTMF
5206 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5207 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005208 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5209 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005210 },
5211 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005212 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5213 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5214 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5215 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5216 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005217 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005218 { // AUDIO_STREAM_ACCESSIBILITY
5219 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5220 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5221 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5222 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5223 },
5224 { // AUDIO_STREAM_REROUTING
5225 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5226 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5227 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5228 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5229 },
5230 { // AUDIO_STREAM_PATCH
5231 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5232 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5233 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5234 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5235 },
Eric Laurente552edb2014-03-10 17:42:56 -07005236};
5237
Eric Laurente0720872014-03-11 09:30:41 -07005238void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005239{
5240 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5241 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5242 mStreams[i].mVolumeCurve[j] =
5243 sVolumeProfiles[i][j];
5244 }
5245 }
5246
5247 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5248 if (mSpeakerDrcEnabled) {
5249 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5250 sDefaultSystemVolumeCurveDrc;
5251 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5252 sSpeakerSonificationVolumeCurveDrc;
5253 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5254 sSpeakerSonificationVolumeCurveDrc;
5255 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5256 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005257 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5258 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005259 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5260 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005261 }
5262}
5263
Eric Laurente0720872014-03-11 09:30:41 -07005264float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005265 int index,
5266 audio_io_handle_t output,
5267 audio_devices_t device)
5268{
5269 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005270 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005271 StreamDescriptor &streamDesc = mStreams[stream];
5272
5273 if (device == AUDIO_DEVICE_NONE) {
5274 device = outputDesc->device();
5275 }
5276
Eric Laurente552edb2014-03-10 17:42:56 -07005277 volume = volIndexToAmpl(device, streamDesc, index);
5278
5279 // if a headset is connected, apply the following rules to ring tones and notifications
5280 // to avoid sound level bursts in user's ears:
5281 // - always attenuate ring tones and notifications volume by 6dB
5282 // - if music is playing, always limit the volume to current music volume,
5283 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005284 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005285 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5286 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5287 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5288 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5289 ((stream_strategy == STRATEGY_SONIFICATION)
5290 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005291 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005292 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005293 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005294 streamDesc.mCanBeMuted) {
5295 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5296 // when the phone is ringing we must consider that music could have been paused just before
5297 // by the music application and behave as if music was active if the last music track was
5298 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005299 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005300 mLimitRingtoneVolume) {
5301 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005302 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5303 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005304 output,
5305 musicDevice);
5306 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5307 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5308 if (volume > minVol) {
5309 volume = minVol;
5310 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5311 }
5312 }
5313 }
5314
5315 return volume;
5316}
5317
Eric Laurente0720872014-03-11 09:30:41 -07005318status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005319 int index,
5320 audio_io_handle_t output,
5321 audio_devices_t device,
5322 int delayMs,
5323 bool force)
5324{
5325
5326 // do not change actual stream volume if the stream is muted
5327 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5328 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5329 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5330 return NO_ERROR;
5331 }
5332
5333 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005334 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5335 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5336 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5337 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005338 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005339 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005340 return INVALID_OPERATION;
5341 }
5342
5343 float volume = computeVolume(stream, index, output, device);
5344 // We actually change the volume if:
5345 // - the float value returned by computeVolume() changed
5346 // - the force flag is set
5347 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5348 force) {
5349 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5350 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5351 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5352 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005353 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5354 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005355 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005356 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005357 }
5358
Eric Laurent3b73df72014-03-11 09:06:29 -07005359 if (stream == AUDIO_STREAM_VOICE_CALL ||
5360 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005361 float voiceVolume;
5362 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005363 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005364 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5365 } else {
5366 voiceVolume = 1.0;
5367 }
5368
5369 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5370 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5371 mLastVoiceVolume = voiceVolume;
5372 }
5373 }
5374
5375 return NO_ERROR;
5376}
5377
Eric Laurente0720872014-03-11 09:30:41 -07005378void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005379 audio_devices_t device,
5380 int delayMs,
5381 bool force)
5382{
5383 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5384
Eric Laurent3b73df72014-03-11 09:06:29 -07005385 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005386 if (stream == AUDIO_STREAM_PATCH) {
5387 continue;
5388 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005389 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005390 mStreams[stream].getVolumeIndex(device),
5391 output,
5392 device,
5393 delayMs,
5394 force);
5395 }
5396}
5397
Eric Laurente0720872014-03-11 09:30:41 -07005398void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005399 bool on,
5400 audio_io_handle_t output,
5401 int delayMs,
5402 audio_devices_t device)
5403{
5404 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005405 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005406 if (stream == AUDIO_STREAM_PATCH) {
5407 continue;
5408 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005409 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5410 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005411 }
5412 }
5413}
5414
Eric Laurente0720872014-03-11 09:30:41 -07005415void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005416 bool on,
5417 audio_io_handle_t output,
5418 int delayMs,
5419 audio_devices_t device)
5420{
5421 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005422 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005423 if (device == AUDIO_DEVICE_NONE) {
5424 device = outputDesc->device();
5425 }
5426
5427 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5428 stream, on, output, outputDesc->mMuteCount[stream], device);
5429
5430 if (on) {
5431 if (outputDesc->mMuteCount[stream] == 0) {
5432 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005433 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5434 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005435 checkAndSetVolume(stream, 0, output, device, delayMs);
5436 }
5437 }
5438 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5439 outputDesc->mMuteCount[stream]++;
5440 } else {
5441 if (outputDesc->mMuteCount[stream] == 0) {
5442 ALOGV("setStreamMute() unmuting non muted stream!");
5443 return;
5444 }
5445 if (--outputDesc->mMuteCount[stream] == 0) {
5446 checkAndSetVolume(stream,
5447 streamDesc.getVolumeIndex(device),
5448 output,
5449 device,
5450 delayMs);
5451 }
5452 }
5453}
5454
Eric Laurente0720872014-03-11 09:30:41 -07005455void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005456 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005457{
5458 // if the stream pertains to sonification strategy and we are in call we must
5459 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5460 // in the device used for phone strategy and play the tone if the selected device does not
5461 // interfere with the device used for phone strategy
5462 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5463 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005464 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005465 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5466 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005467 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005468 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5469 stream, starting, outputDesc->mDevice, stateChange);
5470 if (outputDesc->mRefCount[stream]) {
5471 int muteCount = 1;
5472 if (stateChange) {
5473 muteCount = outputDesc->mRefCount[stream];
5474 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005475 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005476 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5477 for (int i = 0; i < muteCount; i++) {
5478 setStreamMute(stream, starting, mPrimaryOutput);
5479 }
5480 } else {
5481 ALOGV("handleIncallSonification() high visibility");
5482 if (outputDesc->device() &
5483 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5484 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5485 for (int i = 0; i < muteCount; i++) {
5486 setStreamMute(stream, starting, mPrimaryOutput);
5487 }
5488 }
5489 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005490 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5491 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005492 } else {
5493 mpClientInterface->stopTone();
5494 }
5495 }
5496 }
5497 }
5498}
5499
Eric Laurente0720872014-03-11 09:30:41 -07005500bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005501{
5502 return isStateInCall(mPhoneState);
5503}
5504
Eric Laurente0720872014-03-11 09:30:41 -07005505bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005506 return ((state == AUDIO_MODE_IN_CALL) ||
5507 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005508}
5509
Eric Laurente0720872014-03-11 09:30:41 -07005510uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005511{
5512 return MAX_EFFECTS_CPU_LOAD;
5513}
5514
Eric Laurente0720872014-03-11 09:30:41 -07005515uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005516{
5517 return MAX_EFFECTS_MEMORY;
5518}
5519
Eric Laurent6a94d692014-05-20 11:18:06 -07005520
Eric Laurente552edb2014-03-10 17:42:56 -07005521// --- AudioOutputDescriptor class implementation
5522
Eric Laurente0720872014-03-11 09:30:41 -07005523AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005524 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005525 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005526 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005527 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5528{
5529 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005530 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005531 mRefCount[i] = 0;
5532 mCurVolume[i] = -1.0;
5533 mMuteCount[i] = 0;
5534 mStopTime[i] = 0;
5535 }
5536 for (int i = 0; i < NUM_STRATEGIES; i++) {
5537 mStrategyMutedByDevice[i] = false;
5538 }
5539 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005540 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005541 mSamplingRate = profile->pickSamplingRate();
5542 mFormat = profile->pickFormat();
5543 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005544 if (profile->mGains.size() > 0) {
5545 profile->mGains[0]->getDefaultConfig(&mGain);
5546 }
Eric Laurente552edb2014-03-10 17:42:56 -07005547 }
5548}
5549
Eric Laurente0720872014-03-11 09:30:41 -07005550audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005551{
5552 if (isDuplicated()) {
5553 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5554 } else {
5555 return mDevice;
5556 }
5557}
5558
Eric Laurente0720872014-03-11 09:30:41 -07005559uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005560{
5561 if (isDuplicated()) {
5562 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5563 } else {
5564 return mLatency;
5565 }
5566}
5567
Eric Laurente0720872014-03-11 09:30:41 -07005568bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005569 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005570{
5571 if (isDuplicated()) {
5572 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5573 } else if (outputDesc->isDuplicated()){
5574 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5575 } else {
5576 return (mProfile->mModule == outputDesc->mProfile->mModule);
5577 }
5578}
5579
Eric Laurente0720872014-03-11 09:30:41 -07005580void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005581 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005582{
5583 // forward usage count change to attached outputs
5584 if (isDuplicated()) {
5585 mOutput1->changeRefCount(stream, delta);
5586 mOutput2->changeRefCount(stream, delta);
5587 }
5588 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005589 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5590 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005591 mRefCount[stream] = 0;
5592 return;
5593 }
5594 mRefCount[stream] += delta;
5595 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5596}
5597
Eric Laurente0720872014-03-11 09:30:41 -07005598audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005599{
5600 if (isDuplicated()) {
5601 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5602 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005603 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005604 }
5605}
5606
Eric Laurente0720872014-03-11 09:30:41 -07005607bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005608{
5609 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5610}
5611
Eric Laurente0720872014-03-11 09:30:41 -07005612bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005613 uint32_t inPastMs,
5614 nsecs_t sysTime) const
5615{
5616 if ((sysTime == 0) && (inPastMs != 0)) {
5617 sysTime = systemTime();
5618 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005619 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005620 if (i == AUDIO_STREAM_PATCH) {
5621 continue;
5622 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005623 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005624 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005625 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005626 return true;
5627 }
5628 }
5629 return false;
5630}
5631
Eric Laurente0720872014-03-11 09:30:41 -07005632bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005633 uint32_t inPastMs,
5634 nsecs_t sysTime) const
5635{
5636 if (mRefCount[stream] != 0) {
5637 return true;
5638 }
5639 if (inPastMs == 0) {
5640 return false;
5641 }
5642 if (sysTime == 0) {
5643 sysTime = systemTime();
5644 }
5645 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5646 return true;
5647 }
5648 return false;
5649}
5650
Eric Laurent1c333e22014-05-20 10:48:17 -07005651void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005652 struct audio_port_config *dstConfig,
5653 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005654{
Eric Laurent84c70242014-06-23 08:46:27 -07005655 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5656
Eric Laurent1f2f2232014-06-02 12:01:23 -07005657 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5658 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5659 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005660 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005661 }
5662 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5663
Eric Laurent6a94d692014-05-20 11:18:06 -07005664 dstConfig->id = mId;
5665 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5666 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005667 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5668 dstConfig->ext.mix.handle = mIoHandle;
5669 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005670}
5671
5672void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5673 struct audio_port *port) const
5674{
Eric Laurent84c70242014-06-23 08:46:27 -07005675 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005676 mProfile->toAudioPort(port);
5677 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005678 toAudioPortConfig(&port->active_config);
5679 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005680 port->ext.mix.handle = mIoHandle;
5681 port->ext.mix.latency_class =
5682 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5683}
Eric Laurente552edb2014-03-10 17:42:56 -07005684
Eric Laurente0720872014-03-11 09:30:41 -07005685status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005686{
5687 const size_t SIZE = 256;
5688 char buffer[SIZE];
5689 String8 result;
5690
Eric Laurent4d416952014-08-10 14:07:09 -07005691 snprintf(buffer, SIZE, " ID: %d\n", mId);
5692 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005693 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5694 result.append(buffer);
5695 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5696 result.append(buffer);
5697 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5698 result.append(buffer);
5699 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5700 result.append(buffer);
5701 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5702 result.append(buffer);
5703 snprintf(buffer, SIZE, " Devices %08x\n", device());
5704 result.append(buffer);
5705 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5706 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005707 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5708 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5709 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005710 result.append(buffer);
5711 }
5712 write(fd, result.string(), result.size());
5713
5714 return NO_ERROR;
5715}
5716
5717// --- AudioInputDescriptor class implementation
5718
Eric Laurent1c333e22014-05-20 10:48:17 -07005719AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005720 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005721 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005722 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005723{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005724 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005725 mSamplingRate = profile->pickSamplingRate();
5726 mFormat = profile->pickFormat();
5727 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005728 if (profile->mGains.size() > 0) {
5729 profile->mGains[0]->getDefaultConfig(&mGain);
5730 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005731 }
Eric Laurente552edb2014-03-10 17:42:56 -07005732}
5733
Eric Laurent1c333e22014-05-20 10:48:17 -07005734void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005735 struct audio_port_config *dstConfig,
5736 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005737{
Eric Laurent84c70242014-06-23 08:46:27 -07005738 ALOG_ASSERT(mProfile != 0,
5739 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005740 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5741 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5742 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005743 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005744 }
5745
5746 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5747
Eric Laurent6a94d692014-05-20 11:18:06 -07005748 dstConfig->id = mId;
5749 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5750 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005751 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5752 dstConfig->ext.mix.handle = mIoHandle;
5753 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005754}
5755
5756void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5757 struct audio_port *port) const
5758{
Eric Laurent84c70242014-06-23 08:46:27 -07005759 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5760
Eric Laurent1c333e22014-05-20 10:48:17 -07005761 mProfile->toAudioPort(port);
5762 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005763 toAudioPortConfig(&port->active_config);
5764 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005765 port->ext.mix.handle = mIoHandle;
5766 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5767}
5768
Eric Laurente0720872014-03-11 09:30:41 -07005769status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005770{
5771 const size_t SIZE = 256;
5772 char buffer[SIZE];
5773 String8 result;
5774
Eric Laurent4d416952014-08-10 14:07:09 -07005775 snprintf(buffer, SIZE, " ID: %d\n", mId);
5776 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005777 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5778 result.append(buffer);
5779 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5780 result.append(buffer);
5781 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5782 result.append(buffer);
5783 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5784 result.append(buffer);
5785 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5786 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005787 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5788 result.append(buffer);
5789
Eric Laurente552edb2014-03-10 17:42:56 -07005790 write(fd, result.string(), result.size());
5791
5792 return NO_ERROR;
5793}
5794
5795// --- StreamDescriptor class implementation
5796
Eric Laurente0720872014-03-11 09:30:41 -07005797AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005798 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5799{
5800 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5801}
5802
Eric Laurente0720872014-03-11 09:30:41 -07005803int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005804{
Eric Laurente0720872014-03-11 09:30:41 -07005805 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005806 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5807 if (mIndexCur.indexOfKey(device) < 0) {
5808 device = AUDIO_DEVICE_OUT_DEFAULT;
5809 }
5810 return mIndexCur.valueFor(device);
5811}
5812
Eric Laurente0720872014-03-11 09:30:41 -07005813void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005814{
5815 const size_t SIZE = 256;
5816 char buffer[SIZE];
5817 String8 result;
5818
5819 snprintf(buffer, SIZE, "%s %02d %02d ",
5820 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5821 result.append(buffer);
5822 for (size_t i = 0; i < mIndexCur.size(); i++) {
5823 snprintf(buffer, SIZE, "%04x : %02d, ",
5824 mIndexCur.keyAt(i),
5825 mIndexCur.valueAt(i));
5826 result.append(buffer);
5827 }
5828 result.append("\n");
5829
5830 write(fd, result.string(), result.size());
5831}
5832
5833// --- EffectDescriptor class implementation
5834
Eric Laurente0720872014-03-11 09:30:41 -07005835status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005836{
5837 const size_t SIZE = 256;
5838 char buffer[SIZE];
5839 String8 result;
5840
5841 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5842 result.append(buffer);
5843 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5844 result.append(buffer);
5845 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5846 result.append(buffer);
5847 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5848 result.append(buffer);
5849 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5850 result.append(buffer);
5851 write(fd, result.string(), result.size());
5852
5853 return NO_ERROR;
5854}
5855
Eric Laurent1c333e22014-05-20 10:48:17 -07005856// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005857
Eric Laurente0720872014-03-11 09:30:41 -07005858AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005859 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5860 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005861{
5862}
5863
Eric Laurente0720872014-03-11 09:30:41 -07005864AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005865{
5866 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005867 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005868 }
5869 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005870 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005871 }
5872 free((void *)mName);
5873}
5874
Eric Laurent1afeecb2014-05-14 08:52:28 -07005875status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5876{
5877 cnode *node = root->first_child;
5878
5879 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5880
5881 while (node) {
5882 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5883 profile->loadSamplingRates((char *)node->value);
5884 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5885 profile->loadFormats((char *)node->value);
5886 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5887 profile->loadInChannels((char *)node->value);
5888 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5889 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5890 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005891 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5892 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005893 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5894 profile->loadGains(node);
5895 }
5896 node = node->next;
5897 }
5898 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5899 "loadInput() invalid supported devices");
5900 ALOGW_IF(profile->mChannelMasks.size() == 0,
5901 "loadInput() invalid supported channel masks");
5902 ALOGW_IF(profile->mSamplingRates.size() == 0,
5903 "loadInput() invalid supported sampling rates");
5904 ALOGW_IF(profile->mFormats.size() == 0,
5905 "loadInput() invalid supported formats");
5906 if (!profile->mSupportedDevices.isEmpty() &&
5907 (profile->mChannelMasks.size() != 0) &&
5908 (profile->mSamplingRates.size() != 0) &&
5909 (profile->mFormats.size() != 0)) {
5910
5911 ALOGV("loadInput() adding input Supported Devices %04x",
5912 profile->mSupportedDevices.types());
5913
5914 mInputProfiles.add(profile);
5915 return NO_ERROR;
5916 } else {
5917 return BAD_VALUE;
5918 }
5919}
5920
5921status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5922{
5923 cnode *node = root->first_child;
5924
5925 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5926
5927 while (node) {
5928 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5929 profile->loadSamplingRates((char *)node->value);
5930 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5931 profile->loadFormats((char *)node->value);
5932 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5933 profile->loadOutChannels((char *)node->value);
5934 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5935 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5936 mDeclaredDevices);
5937 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005938 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005939 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5940 profile->loadGains(node);
5941 }
5942 node = node->next;
5943 }
5944 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5945 "loadOutput() invalid supported devices");
5946 ALOGW_IF(profile->mChannelMasks.size() == 0,
5947 "loadOutput() invalid supported channel masks");
5948 ALOGW_IF(profile->mSamplingRates.size() == 0,
5949 "loadOutput() invalid supported sampling rates");
5950 ALOGW_IF(profile->mFormats.size() == 0,
5951 "loadOutput() invalid supported formats");
5952 if (!profile->mSupportedDevices.isEmpty() &&
5953 (profile->mChannelMasks.size() != 0) &&
5954 (profile->mSamplingRates.size() != 0) &&
5955 (profile->mFormats.size() != 0)) {
5956
5957 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5958 profile->mSupportedDevices.types(), profile->mFlags);
5959
5960 mOutputProfiles.add(profile);
5961 return NO_ERROR;
5962 } else {
5963 return BAD_VALUE;
5964 }
5965}
5966
5967status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5968{
5969 cnode *node = root->first_child;
5970
5971 audio_devices_t type = AUDIO_DEVICE_NONE;
5972 while (node) {
5973 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5974 type = parseDeviceNames((char *)node->value);
5975 break;
5976 }
5977 node = node->next;
5978 }
5979 if (type == AUDIO_DEVICE_NONE ||
5980 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5981 ALOGW("loadDevice() bad type %08x", type);
5982 return BAD_VALUE;
5983 }
5984 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5985 deviceDesc->mModule = this;
5986
5987 node = root->first_child;
5988 while (node) {
5989 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5990 deviceDesc->mAddress = String8((char *)node->value);
5991 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5992 if (audio_is_input_device(type)) {
5993 deviceDesc->loadInChannels((char *)node->value);
5994 } else {
5995 deviceDesc->loadOutChannels((char *)node->value);
5996 }
5997 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5998 deviceDesc->loadGains(node);
5999 }
6000 node = node->next;
6001 }
6002
6003 ALOGV("loadDevice() adding device name %s type %08x address %s",
6004 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6005
6006 mDeclaredDevices.add(deviceDesc);
6007
6008 return NO_ERROR;
6009}
6010
Eric Laurente0720872014-03-11 09:30:41 -07006011void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006012{
6013 const size_t SIZE = 256;
6014 char buffer[SIZE];
6015 String8 result;
6016
6017 snprintf(buffer, SIZE, " - name: %s\n", mName);
6018 result.append(buffer);
6019 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6020 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006021 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6022 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006023 write(fd, result.string(), result.size());
6024 if (mOutputProfiles.size()) {
6025 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6026 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006027 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006028 write(fd, buffer, strlen(buffer));
6029 mOutputProfiles[i]->dump(fd);
6030 }
6031 }
6032 if (mInputProfiles.size()) {
6033 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6034 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006035 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006036 write(fd, buffer, strlen(buffer));
6037 mInputProfiles[i]->dump(fd);
6038 }
6039 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006040 if (mDeclaredDevices.size()) {
6041 write(fd, " - devices:\n", strlen(" - devices:\n"));
6042 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6043 mDeclaredDevices[i]->dump(fd, 4, i);
6044 }
6045 }
Eric Laurente552edb2014-03-10 17:42:56 -07006046}
6047
Eric Laurent1c333e22014-05-20 10:48:17 -07006048// --- AudioPort class implementation
6049
Eric Laurenta121f902014-06-03 13:32:54 -07006050
6051AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6052 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006053 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006054{
6055 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6056 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6057}
6058
Eric Laurent1c333e22014-05-20 10:48:17 -07006059void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6060{
6061 port->role = mRole;
6062 port->type = mType;
6063 unsigned int i;
6064 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006065 if (mSamplingRates[i] != 0) {
6066 port->sample_rates[i] = mSamplingRates[i];
6067 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006068 }
6069 port->num_sample_rates = i;
6070 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006071 if (mChannelMasks[i] != 0) {
6072 port->channel_masks[i] = mChannelMasks[i];
6073 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006074 }
6075 port->num_channel_masks = i;
6076 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006077 if (mFormats[i] != 0) {
6078 port->formats[i] = mFormats[i];
6079 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006080 }
6081 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006082
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006083 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006084
6085 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6086 port->gains[i] = mGains[i]->mGain;
6087 }
6088 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006089}
6090
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006091void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6092 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6093 const uint32_t rate = port->mSamplingRates.itemAt(k);
6094 if (rate != 0) { // skip "dynamic" rates
6095 bool hasRate = false;
6096 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6097 if (rate == mSamplingRates.itemAt(l)) {
6098 hasRate = true;
6099 break;
6100 }
6101 }
6102 if (!hasRate) { // never import a sampling rate twice
6103 mSamplingRates.add(rate);
6104 }
6105 }
6106 }
6107 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6108 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6109 if (mask != 0) { // skip "dynamic" masks
6110 bool hasMask = false;
6111 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6112 if (mask == mChannelMasks.itemAt(l)) {
6113 hasMask = true;
6114 break;
6115 }
6116 }
6117 if (!hasMask) { // never import a channel mask twice
6118 mChannelMasks.add(mask);
6119 }
6120 }
6121 }
6122 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6123 const audio_format_t format = port->mFormats.itemAt(k);
6124 if (format != 0) { // skip "dynamic" formats
6125 bool hasFormat = false;
6126 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6127 if (format == mFormats.itemAt(l)) {
6128 hasFormat = true;
6129 break;
6130 }
6131 }
6132 if (!hasFormat) { // never import a channel mask twice
6133 mFormats.add(format);
6134 }
6135 }
6136 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006137 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6138 sp<AudioGain> gain = port->mGains.itemAt(k);
6139 if (gain != 0) {
6140 bool hasGain = false;
6141 for (size_t l = 0 ; l < mGains.size() ; l++) {
6142 if (gain == mGains.itemAt(l)) {
6143 hasGain = true;
6144 break;
6145 }
6146 }
6147 if (!hasGain) { // never import a gain twice
6148 mGains.add(gain);
6149 }
6150 }
6151 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006152}
6153
6154void AudioPolicyManager::AudioPort::clearCapabilities() {
6155 mChannelMasks.clear();
6156 mFormats.clear();
6157 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006158 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006159}
Eric Laurent1c333e22014-05-20 10:48:17 -07006160
6161void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6162{
6163 char *str = strtok(name, "|");
6164
6165 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6166 // rates should be read from the output stream after it is opened for the first time
6167 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6168 mSamplingRates.add(0);
6169 return;
6170 }
6171
6172 while (str != NULL) {
6173 uint32_t rate = atoi(str);
6174 if (rate != 0) {
6175 ALOGV("loadSamplingRates() adding rate %d", rate);
6176 mSamplingRates.add(rate);
6177 }
6178 str = strtok(NULL, "|");
6179 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006180}
6181
6182void AudioPolicyManager::AudioPort::loadFormats(char *name)
6183{
6184 char *str = strtok(name, "|");
6185
6186 // by convention, "0' in the first entry in mFormats indicates the supported formats
6187 // should be read from the output stream after it is opened for the first time
6188 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6189 mFormats.add(AUDIO_FORMAT_DEFAULT);
6190 return;
6191 }
6192
6193 while (str != NULL) {
6194 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6195 ARRAY_SIZE(sFormatNameToEnumTable),
6196 str);
6197 if (format != AUDIO_FORMAT_DEFAULT) {
6198 mFormats.add(format);
6199 }
6200 str = strtok(NULL, "|");
6201 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006202}
6203
6204void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6205{
6206 const char *str = strtok(name, "|");
6207
6208 ALOGV("loadInChannels() %s", name);
6209
6210 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6211 mChannelMasks.add(0);
6212 return;
6213 }
6214
6215 while (str != NULL) {
6216 audio_channel_mask_t channelMask =
6217 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6218 ARRAY_SIZE(sInChannelsNameToEnumTable),
6219 str);
6220 if (channelMask != 0) {
6221 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6222 mChannelMasks.add(channelMask);
6223 }
6224 str = strtok(NULL, "|");
6225 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006226}
6227
6228void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6229{
6230 const char *str = strtok(name, "|");
6231
6232 ALOGV("loadOutChannels() %s", name);
6233
6234 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6235 // masks should be read from the output stream after it is opened for the first time
6236 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6237 mChannelMasks.add(0);
6238 return;
6239 }
6240
6241 while (str != NULL) {
6242 audio_channel_mask_t channelMask =
6243 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6244 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6245 str);
6246 if (channelMask != 0) {
6247 mChannelMasks.add(channelMask);
6248 }
6249 str = strtok(NULL, "|");
6250 }
6251 return;
6252}
6253
Eric Laurent1afeecb2014-05-14 08:52:28 -07006254audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6255{
6256 const char *str = strtok(name, "|");
6257
6258 ALOGV("loadGainMode() %s", name);
6259 audio_gain_mode_t mode = 0;
6260 while (str != NULL) {
6261 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6262 ARRAY_SIZE(sGainModeNameToEnumTable),
6263 str);
6264 str = strtok(NULL, "|");
6265 }
6266 return mode;
6267}
6268
Eric Laurenta121f902014-06-03 13:32:54 -07006269void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006270{
6271 cnode *node = root->first_child;
6272
Eric Laurenta121f902014-06-03 13:32:54 -07006273 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006274
6275 while (node) {
6276 if (strcmp(node->name, GAIN_MODE) == 0) {
6277 gain->mGain.mode = loadGainMode((char *)node->value);
6278 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006279 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006280 gain->mGain.channel_mask =
6281 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6282 ARRAY_SIZE(sInChannelsNameToEnumTable),
6283 (char *)node->value);
6284 } else {
6285 gain->mGain.channel_mask =
6286 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6287 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6288 (char *)node->value);
6289 }
6290 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6291 gain->mGain.min_value = atoi((char *)node->value);
6292 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6293 gain->mGain.max_value = atoi((char *)node->value);
6294 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6295 gain->mGain.default_value = atoi((char *)node->value);
6296 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6297 gain->mGain.step_value = atoi((char *)node->value);
6298 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6299 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6300 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6301 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6302 }
6303 node = node->next;
6304 }
6305
6306 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6307 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6308
6309 if (gain->mGain.mode == 0) {
6310 return;
6311 }
6312 mGains.add(gain);
6313}
6314
6315void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6316{
6317 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006318 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006319 while (node) {
6320 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006321 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006322 node = node->next;
6323 }
6324}
6325
Glenn Kastencbd48022014-07-24 13:46:44 -07006326status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006327{
6328 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6329 if (mSamplingRates[i] == samplingRate) {
6330 return NO_ERROR;
6331 }
6332 }
6333 return BAD_VALUE;
6334}
6335
Glenn Kastencbd48022014-07-24 13:46:44 -07006336status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6337 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006338{
Glenn Kastencbd48022014-07-24 13:46:44 -07006339 // Search for the closest supported sampling rate that is above (preferred)
6340 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6341 // The sampling rates do not need to be sorted in ascending order.
6342 ssize_t maxBelow = -1;
6343 ssize_t minAbove = -1;
6344 uint32_t candidate;
6345 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6346 candidate = mSamplingRates[i];
6347 if (candidate == samplingRate) {
6348 if (updatedSamplingRate != NULL) {
6349 *updatedSamplingRate = candidate;
6350 }
6351 return NO_ERROR;
6352 }
6353 // candidate < desired
6354 if (candidate < samplingRate) {
6355 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6356 maxBelow = i;
6357 }
6358 // candidate > desired
6359 } else {
6360 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6361 minAbove = i;
6362 }
6363 }
6364 }
6365 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6366 // TODO Move these assumptions out.
6367 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6368 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6369 // due to approximation by an int32_t of the
6370 // phase increments
6371 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6372 if (minAbove >= 0) {
6373 candidate = mSamplingRates[minAbove];
6374 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6375 if (updatedSamplingRate != NULL) {
6376 *updatedSamplingRate = candidate;
6377 }
6378 return NO_ERROR;
6379 }
6380 }
6381 // But if we have to up-sample from a lower sampling rate, that's OK.
6382 if (maxBelow >= 0) {
6383 candidate = mSamplingRates[maxBelow];
6384 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6385 if (updatedSamplingRate != NULL) {
6386 *updatedSamplingRate = candidate;
6387 }
6388 return NO_ERROR;
6389 }
6390 }
6391 // leave updatedSamplingRate unmodified
6392 return BAD_VALUE;
6393}
6394
6395status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6396{
6397 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006398 if (mChannelMasks[i] == channelMask) {
6399 return NO_ERROR;
6400 }
6401 }
6402 return BAD_VALUE;
6403}
6404
Glenn Kastencbd48022014-07-24 13:46:44 -07006405status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6406 const
6407{
6408 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6409 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6410 // FIXME Does not handle multi-channel automatic conversions yet
6411 audio_channel_mask_t supported = mChannelMasks[i];
6412 if (supported == channelMask) {
6413 return NO_ERROR;
6414 }
6415 if (isRecordThread) {
6416 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6417 // FIXME Abstract this out to a table.
6418 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6419 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6420 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6421 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6422 return NO_ERROR;
6423 }
6424 }
6425 }
6426 return BAD_VALUE;
6427}
6428
Eric Laurenta121f902014-06-03 13:32:54 -07006429status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6430{
6431 for (size_t i = 0; i < mFormats.size(); i ++) {
6432 if (mFormats[i] == format) {
6433 return NO_ERROR;
6434 }
6435 }
6436 return BAD_VALUE;
6437}
6438
Eric Laurent1e693b52014-07-09 15:03:28 -07006439
6440uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6441{
6442 // special case for uninitialized dynamic profile
6443 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6444 return 0;
6445 }
6446
Eric Laurent828bcff2014-09-07 12:26:06 -07006447 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6448 // channel count / sampling rate combination chosen will be supported by the connected
6449 // sink
6450 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6451 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6452 uint32_t samplingRate = UINT_MAX;
6453 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6454 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6455 samplingRate = mSamplingRates[i];
6456 }
6457 }
6458 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6459 }
6460
Eric Laurent1e693b52014-07-09 15:03:28 -07006461 uint32_t samplingRate = 0;
6462 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6463
6464 // For mixed output and inputs, use max mixer sampling rates. Do not
6465 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006466 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006467 maxRate = UINT_MAX;
6468 }
6469 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6470 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6471 samplingRate = mSamplingRates[i];
6472 }
6473 }
6474 return samplingRate;
6475}
6476
6477audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6478{
6479 // special case for uninitialized dynamic profile
6480 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6481 return AUDIO_CHANNEL_NONE;
6482 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006483 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006484
6485 // For direct outputs, pick minimum channel count: this helps ensuring that the
6486 // channel count / sampling rate combination chosen will be supported by the connected
6487 // sink
6488 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6489 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6490 uint32_t channelCount = UINT_MAX;
6491 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6492 uint32_t cnlCount;
6493 if (mUseInChannelMask) {
6494 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6495 } else {
6496 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6497 }
6498 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6499 channelMask = mChannelMasks[i];
6500 channelCount = cnlCount;
6501 }
6502 }
6503 return channelMask;
6504 }
6505
Eric Laurent1e693b52014-07-09 15:03:28 -07006506 uint32_t channelCount = 0;
6507 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6508
6509 // For mixed output and inputs, use max mixer channel count. Do not
6510 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006511 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006512 maxCount = UINT_MAX;
6513 }
6514 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6515 uint32_t cnlCount;
6516 if (mUseInChannelMask) {
6517 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6518 } else {
6519 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6520 }
6521 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6522 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006523 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006524 }
6525 }
6526 return channelMask;
6527}
6528
Andy Hung9a605382014-07-28 16:16:31 -07006529/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006530const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6531 AUDIO_FORMAT_DEFAULT,
6532 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006533 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006534 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006535 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006536 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006537};
6538
6539int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6540 audio_format_t format2)
6541{
6542 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6543 // compressed format and better than any PCM format. This is by design of pickFormat()
6544 if (!audio_is_linear_pcm(format1)) {
6545 if (!audio_is_linear_pcm(format2)) {
6546 return 0;
6547 }
6548 return 1;
6549 }
6550 if (!audio_is_linear_pcm(format2)) {
6551 return -1;
6552 }
6553
6554 int index1 = -1, index2 = -1;
6555 for (size_t i = 0;
6556 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6557 i ++) {
6558 if (sPcmFormatCompareTable[i] == format1) {
6559 index1 = i;
6560 }
6561 if (sPcmFormatCompareTable[i] == format2) {
6562 index2 = i;
6563 }
6564 }
6565 // format1 not found => index1 < 0 => format2 > format1
6566 // format2 not found => index2 < 0 => format2 < format1
6567 return index1 - index2;
6568}
6569
6570audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6571{
6572 // special case for uninitialized dynamic profile
6573 if (mFormats.size() == 1 && mFormats[0] == 0) {
6574 return AUDIO_FORMAT_DEFAULT;
6575 }
6576
6577 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006578 audio_format_t bestFormat =
6579 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6580 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006581 // For mixed output and inputs, use best mixer output format. Do not
6582 // limit format otherwise
6583 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6584 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006585 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006586 bestFormat = AUDIO_FORMAT_INVALID;
6587 }
6588
6589 for (size_t i = 0; i < mFormats.size(); i ++) {
6590 if ((compareFormats(mFormats[i], format) > 0) &&
6591 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6592 format = mFormats[i];
6593 }
6594 }
6595 return format;
6596}
6597
Eric Laurenta121f902014-06-03 13:32:54 -07006598status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6599 int index) const
6600{
6601 if (index < 0 || (size_t)index >= mGains.size()) {
6602 return BAD_VALUE;
6603 }
6604 return mGains[index]->checkConfig(gainConfig);
6605}
6606
Eric Laurent1afeecb2014-05-14 08:52:28 -07006607void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6608{
6609 const size_t SIZE = 256;
6610 char buffer[SIZE];
6611 String8 result;
6612
6613 if (mName.size() != 0) {
6614 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6615 result.append(buffer);
6616 }
6617
6618 if (mSamplingRates.size() != 0) {
6619 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6620 result.append(buffer);
6621 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006622 if (i == 0 && mSamplingRates[i] == 0) {
6623 snprintf(buffer, SIZE, "Dynamic");
6624 } else {
6625 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6626 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006627 result.append(buffer);
6628 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6629 }
6630 result.append("\n");
6631 }
6632
6633 if (mChannelMasks.size() != 0) {
6634 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6635 result.append(buffer);
6636 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006637 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6638
6639 if (i == 0 && mChannelMasks[i] == 0) {
6640 snprintf(buffer, SIZE, "Dynamic");
6641 } else {
6642 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6643 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006644 result.append(buffer);
6645 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6646 }
6647 result.append("\n");
6648 }
6649
6650 if (mFormats.size() != 0) {
6651 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6652 result.append(buffer);
6653 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006654 const char *formatStr = enumToString(sFormatNameToEnumTable,
6655 ARRAY_SIZE(sFormatNameToEnumTable),
6656 mFormats[i]);
6657 if (i == 0 && strcmp(formatStr, "") == 0) {
6658 snprintf(buffer, SIZE, "Dynamic");
6659 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006660 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006661 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006662 result.append(buffer);
6663 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6664 }
6665 result.append("\n");
6666 }
6667 write(fd, result.string(), result.size());
6668 if (mGains.size() != 0) {
6669 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6670 write(fd, buffer, strlen(buffer) + 1);
6671 result.append(buffer);
6672 for (size_t i = 0; i < mGains.size(); i++) {
6673 mGains[i]->dump(fd, spaces + 2, i);
6674 }
6675 }
6676}
6677
6678// --- AudioGain class implementation
6679
Eric Laurenta121f902014-06-03 13:32:54 -07006680AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006681{
Eric Laurenta121f902014-06-03 13:32:54 -07006682 mIndex = index;
6683 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006684 memset(&mGain, 0, sizeof(struct audio_gain));
6685}
6686
Eric Laurenta121f902014-06-03 13:32:54 -07006687void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6688{
6689 config->index = mIndex;
6690 config->mode = mGain.mode;
6691 config->channel_mask = mGain.channel_mask;
6692 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6693 config->values[0] = mGain.default_value;
6694 } else {
6695 uint32_t numValues;
6696 if (mUseInChannelMask) {
6697 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6698 } else {
6699 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6700 }
6701 for (size_t i = 0; i < numValues; i++) {
6702 config->values[i] = mGain.default_value;
6703 }
6704 }
6705 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6706 config->ramp_duration_ms = mGain.min_ramp_ms;
6707 }
6708}
6709
6710status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6711{
6712 if ((config->mode & ~mGain.mode) != 0) {
6713 return BAD_VALUE;
6714 }
6715 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6716 if ((config->values[0] < mGain.min_value) ||
6717 (config->values[0] > mGain.max_value)) {
6718 return BAD_VALUE;
6719 }
6720 } else {
6721 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6722 return BAD_VALUE;
6723 }
6724 uint32_t numValues;
6725 if (mUseInChannelMask) {
6726 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6727 } else {
6728 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6729 }
6730 for (size_t i = 0; i < numValues; i++) {
6731 if ((config->values[i] < mGain.min_value) ||
6732 (config->values[i] > mGain.max_value)) {
6733 return BAD_VALUE;
6734 }
6735 }
6736 }
6737 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6738 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6739 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6740 return BAD_VALUE;
6741 }
6742 }
6743 return NO_ERROR;
6744}
6745
Eric Laurent1afeecb2014-05-14 08:52:28 -07006746void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6747{
6748 const size_t SIZE = 256;
6749 char buffer[SIZE];
6750 String8 result;
6751
6752 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6753 result.append(buffer);
6754 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6755 result.append(buffer);
6756 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6757 result.append(buffer);
6758 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6759 result.append(buffer);
6760 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6761 result.append(buffer);
6762 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6763 result.append(buffer);
6764 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6765 result.append(buffer);
6766 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6767 result.append(buffer);
6768 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6769 result.append(buffer);
6770
6771 write(fd, result.string(), result.size());
6772}
6773
Eric Laurent1f2f2232014-06-02 12:01:23 -07006774// --- AudioPortConfig class implementation
6775
6776AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6777{
6778 mSamplingRate = 0;
6779 mChannelMask = AUDIO_CHANNEL_NONE;
6780 mFormat = AUDIO_FORMAT_INVALID;
6781 mGain.index = -1;
6782}
6783
Eric Laurenta121f902014-06-03 13:32:54 -07006784status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6785 const struct audio_port_config *config,
6786 struct audio_port_config *backupConfig)
6787{
6788 struct audio_port_config localBackupConfig;
6789 status_t status = NO_ERROR;
6790
6791 localBackupConfig.config_mask = config->config_mask;
6792 toAudioPortConfig(&localBackupConfig);
6793
Marco Nelissen961ec212014-08-25 15:58:39 -07006794 sp<AudioPort> audioport = getAudioPort();
6795 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006796 status = NO_INIT;
6797 goto exit;
6798 }
6799 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006800 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006801 if (status != NO_ERROR) {
6802 goto exit;
6803 }
6804 mSamplingRate = config->sample_rate;
6805 }
6806 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006807 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006808 if (status != NO_ERROR) {
6809 goto exit;
6810 }
6811 mChannelMask = config->channel_mask;
6812 }
6813 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006814 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006815 if (status != NO_ERROR) {
6816 goto exit;
6817 }
6818 mFormat = config->format;
6819 }
6820 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006821 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006822 if (status != NO_ERROR) {
6823 goto exit;
6824 }
6825 mGain = config->gain;
6826 }
6827
6828exit:
6829 if (status != NO_ERROR) {
6830 applyAudioPortConfig(&localBackupConfig);
6831 }
6832 if (backupConfig != NULL) {
6833 *backupConfig = localBackupConfig;
6834 }
6835 return status;
6836}
6837
Eric Laurent1f2f2232014-06-02 12:01:23 -07006838void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6839 struct audio_port_config *dstConfig,
6840 const struct audio_port_config *srcConfig) const
6841{
6842 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6843 dstConfig->sample_rate = mSamplingRate;
6844 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6845 dstConfig->sample_rate = srcConfig->sample_rate;
6846 }
6847 } else {
6848 dstConfig->sample_rate = 0;
6849 }
6850 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6851 dstConfig->channel_mask = mChannelMask;
6852 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6853 dstConfig->channel_mask = srcConfig->channel_mask;
6854 }
6855 } else {
6856 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6857 }
6858 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6859 dstConfig->format = mFormat;
6860 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6861 dstConfig->format = srcConfig->format;
6862 }
6863 } else {
6864 dstConfig->format = AUDIO_FORMAT_INVALID;
6865 }
6866 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6867 dstConfig->gain = mGain;
6868 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6869 dstConfig->gain = srcConfig->gain;
6870 }
6871 } else {
6872 dstConfig->gain.index = -1;
6873 }
6874 if (dstConfig->gain.index != -1) {
6875 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6876 } else {
6877 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6878 }
6879}
6880
Eric Laurent1c333e22014-05-20 10:48:17 -07006881// --- IOProfile class implementation
6882
Eric Laurent1afeecb2014-05-14 08:52:28 -07006883AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006884 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006885 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006886{
6887}
6888
Eric Laurente0720872014-03-11 09:30:41 -07006889AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006890{
6891}
6892
6893// checks if the IO profile is compatible with specified parameters.
6894// Sampling rate, format and channel mask must be specified in order to
6895// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006896bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006897 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006898 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006899 audio_format_t format,
6900 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006901 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006902{
Glenn Kastencbd48022014-07-24 13:46:44 -07006903 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6904 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6905 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006906
Glenn Kastencbd48022014-07-24 13:46:44 -07006907 if ((mSupportedDevices.types() & device) != device) {
6908 return false;
6909 }
6910
6911 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006912 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006913 }
6914 uint32_t myUpdatedSamplingRate = samplingRate;
6915 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006916 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006917 }
6918 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6919 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006920 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006921 }
6922
6923 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6924 return false;
6925 }
6926
6927 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6928 checkExactChannelMask(channelMask) != NO_ERROR)) {
6929 return false;
6930 }
6931 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6932 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6933 return false;
6934 }
6935
6936 if (isPlaybackThread && (mFlags & flags) != flags) {
6937 return false;
6938 }
6939 // The only input flag that is allowed to be different is the fast flag.
6940 // An existing fast stream is compatible with a normal track request.
6941 // An existing normal stream is compatible with a fast track request,
6942 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006943 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006944 ~AUDIO_INPUT_FLAG_FAST)) {
6945 return false;
6946 }
6947
6948 if (updatedSamplingRate != NULL) {
6949 *updatedSamplingRate = myUpdatedSamplingRate;
6950 }
6951 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006952}
6953
Eric Laurente0720872014-03-11 09:30:41 -07006954void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006955{
6956 const size_t SIZE = 256;
6957 char buffer[SIZE];
6958 String8 result;
6959
Eric Laurent1afeecb2014-05-14 08:52:28 -07006960 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006961
Eric Laurente552edb2014-03-10 17:42:56 -07006962 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6963 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006964 snprintf(buffer, SIZE, " - devices:\n");
6965 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006966 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006967 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6968 mSupportedDevices[i]->dump(fd, 6, i);
6969 }
Eric Laurente552edb2014-03-10 17:42:56 -07006970}
6971
Eric Laurentd4692962014-05-05 18:13:44 -07006972void AudioPolicyManager::IOProfile::log()
6973{
6974 const size_t SIZE = 256;
6975 char buffer[SIZE];
6976 String8 result;
6977
6978 ALOGV(" - sampling rates: ");
6979 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6980 ALOGV(" %d", mSamplingRates[i]);
6981 }
6982
6983 ALOGV(" - channel masks: ");
6984 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6985 ALOGV(" 0x%04x", mChannelMasks[i]);
6986 }
6987
6988 ALOGV(" - formats: ");
6989 for (size_t i = 0; i < mFormats.size(); i++) {
6990 ALOGV(" 0x%08x", mFormats[i]);
6991 }
6992
6993 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6994 ALOGV(" - flags: 0x%04x\n", mFlags);
6995}
6996
6997
Eric Laurent3a4311c2014-03-17 12:00:47 -07006998// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006999
Eric Laurent1f2f2232014-06-02 12:01:23 -07007000
7001AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7002 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7003 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7004 AUDIO_PORT_ROLE_SOURCE,
7005 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007006 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007007{
Eric Laurenta121f902014-06-03 13:32:54 -07007008 if (mGains.size() > 0) {
7009 mGains[0]->getDefaultConfig(&mGain);
7010 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07007011}
7012
Eric Laurent3a4311c2014-03-17 12:00:47 -07007013bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007014{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007015 // Devices are considered equal if they:
7016 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7017 // - have the same address or one device does not specify the address
7018 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007019 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007020 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007021 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007022 mChannelMask == other->mChannelMask);
7023}
7024
7025void AudioPolicyManager::DeviceVector::refreshTypes()
7026{
Eric Laurent1c333e22014-05-20 10:48:17 -07007027 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007028 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007029 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007030 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007031 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007032}
7033
7034ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7035{
7036 for(size_t i = 0; i < size(); i++) {
7037 if (item->equals(itemAt(i))) {
7038 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007039 }
7040 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007041 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007042}
7043
Eric Laurent3a4311c2014-03-17 12:00:47 -07007044ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007045{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007046 ssize_t ret = indexOf(item);
7047
7048 if (ret < 0) {
7049 ret = SortedVector::add(item);
7050 if (ret >= 0) {
7051 refreshTypes();
7052 }
7053 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007054 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007055 ret = -1;
7056 }
7057 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007058}
7059
Eric Laurent3a4311c2014-03-17 12:00:47 -07007060ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7061{
7062 size_t i;
7063 ssize_t ret = indexOf(item);
7064
7065 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007066 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007067 } else {
7068 ret = SortedVector::removeAt(ret);
7069 if (ret >= 0) {
7070 refreshTypes();
7071 }
7072 }
7073 return ret;
7074}
7075
7076void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7077{
7078 DeviceVector deviceList;
7079
7080 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7081 types &= ~role_bit;
7082
7083 while (types) {
7084 uint32_t i = 31 - __builtin_clz(types);
7085 uint32_t type = 1 << i;
7086 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007087 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007088 }
7089}
7090
Eric Laurent1afeecb2014-05-14 08:52:28 -07007091void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7092 const DeviceVector& declaredDevices)
7093{
7094 char *devName = strtok(name, "|");
7095 while (devName != NULL) {
7096 if (strlen(devName) != 0) {
7097 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7098 ARRAY_SIZE(sDeviceNameToEnumTable),
7099 devName);
7100 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007101 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
7102 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
7103 dev->mAddress = String8("0");
7104 }
7105 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007106 } else {
7107 sp<DeviceDescriptor> deviceDesc =
7108 declaredDevices.getDeviceFromName(String8(devName));
7109 if (deviceDesc != 0) {
7110 add(deviceDesc);
7111 }
7112 }
7113 }
7114 devName = strtok(NULL, "|");
7115 }
7116}
7117
Eric Laurent1c333e22014-05-20 10:48:17 -07007118sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7119 audio_devices_t type, String8 address) const
7120{
7121 sp<DeviceDescriptor> device;
7122 for (size_t i = 0; i < size(); i++) {
7123 if (itemAt(i)->mDeviceType == type) {
7124 device = itemAt(i);
7125 if (itemAt(i)->mAddress = address) {
7126 break;
7127 }
7128 }
7129 }
7130 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
7131 type, address.string(), device.get());
7132 return device;
7133}
7134
Eric Laurent6a94d692014-05-20 11:18:06 -07007135sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7136 audio_port_handle_t id) const
7137{
7138 sp<DeviceDescriptor> device;
7139 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007140 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007141 if (itemAt(i)->mId == id) {
7142 device = itemAt(i);
7143 break;
7144 }
7145 }
7146 return device;
7147}
7148
Eric Laurent1c333e22014-05-20 10:48:17 -07007149AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7150 audio_devices_t type) const
7151{
7152 DeviceVector devices;
7153 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7154 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7155 devices.add(itemAt(i));
7156 type &= ~itemAt(i)->mDeviceType;
7157 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7158 itemAt(i)->mDeviceType, itemAt(i).get());
7159 }
7160 }
7161 return devices;
7162}
7163
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007164AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7165 audio_devices_t type, String8 address) const
7166{
7167 DeviceVector devices;
7168 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
7169 for (size_t i = 0; i < size(); i++) {
7170 //ALOGV(" at i=%d: device=%x, addr=%s",
7171 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
7172 if (itemAt(i)->mDeviceType == type) {
7173 if (itemAt(i)->mAddress == address) {
7174 //ALOGV(" found matching address %s", address.string());
7175 devices.add(itemAt(i));
7176 }
7177 }
7178 }
7179 return devices;
7180}
7181
Eric Laurent1afeecb2014-05-14 08:52:28 -07007182sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7183 const String8& name) const
7184{
7185 sp<DeviceDescriptor> device;
7186 for (size_t i = 0; i < size(); i++) {
7187 if (itemAt(i)->mName == name) {
7188 device = itemAt(i);
7189 break;
7190 }
7191 }
7192 return device;
7193}
7194
Eric Laurent6a94d692014-05-20 11:18:06 -07007195void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7196 struct audio_port_config *dstConfig,
7197 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007198{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007199 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7200 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007201 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007202 }
7203
7204 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7205
Eric Laurent6a94d692014-05-20 11:18:06 -07007206 dstConfig->id = mId;
7207 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007208 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007209 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007210 dstConfig->ext.device.type = mDeviceType;
7211 dstConfig->ext.device.hw_module = mModule->mHandle;
7212 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007213}
7214
7215void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7216{
Eric Laurent83b88082014-06-20 18:31:16 -07007217 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007218 AudioPort::toAudioPort(port);
7219 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007220 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007221 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007222 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007223 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7224}
7225
Eric Laurent1afeecb2014-05-14 08:52:28 -07007226status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007227{
7228 const size_t SIZE = 256;
7229 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007230 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007231
Eric Laurent1afeecb2014-05-14 08:52:28 -07007232 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7233 result.append(buffer);
7234 if (mId != 0) {
7235 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7236 result.append(buffer);
7237 }
7238 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7239 enumToString(sDeviceNameToEnumTable,
7240 ARRAY_SIZE(sDeviceNameToEnumTable),
7241 mDeviceType));
7242 result.append(buffer);
7243 if (mAddress.size() != 0) {
7244 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7245 result.append(buffer);
7246 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007247 write(fd, result.string(), result.size());
7248 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007249
7250 return NO_ERROR;
7251}
7252
Eric Laurent4d416952014-08-10 14:07:09 -07007253status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7254{
7255 const size_t SIZE = 256;
7256 char buffer[SIZE];
7257 String8 result;
7258
7259
7260 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7261 result.append(buffer);
7262 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7263 result.append(buffer);
7264 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7265 result.append(buffer);
7266 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7267 result.append(buffer);
7268 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7269 result.append(buffer);
7270 for (size_t i = 0; i < mPatch.num_sources; i++) {
7271 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7272 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7273 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7274 ARRAY_SIZE(sDeviceNameToEnumTable),
7275 mPatch.sources[i].ext.device.type));
7276 } else {
7277 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7278 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7279 }
7280 result.append(buffer);
7281 }
7282 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7283 result.append(buffer);
7284 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7285 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7286 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7287 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7288 ARRAY_SIZE(sDeviceNameToEnumTable),
7289 mPatch.sinks[i].ext.device.type));
7290 } else {
7291 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7292 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7293 }
7294 result.append(buffer);
7295 }
7296
7297 write(fd, result.string(), result.size());
7298 return NO_ERROR;
7299}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007300
7301// --- audio_policy.conf file parsing
7302
Eric Laurent5dbe4712014-09-19 19:04:57 -07007303uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007304{
7305 uint32_t flag = 0;
7306
7307 // it is OK to cast name to non const here as we are not going to use it after
7308 // strtok() modifies it
7309 char *flagName = strtok(name, "|");
7310 while (flagName != NULL) {
7311 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007312 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7313 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007314 flagName);
7315 }
7316 flagName = strtok(NULL, "|");
7317 }
7318 //force direct flag if offload flag is set: offloading implies a direct output stream
7319 // and all common behaviors are driven by checking only the direct flag
7320 // this should normally be set appropriately in the policy configuration file
7321 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7322 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7323 }
7324
Eric Laurent5dbe4712014-09-19 19:04:57 -07007325 return flag;
7326}
7327
7328uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7329{
7330 uint32_t flag = 0;
7331
7332 // it is OK to cast name to non const here as we are not going to use it after
7333 // strtok() modifies it
7334 char *flagName = strtok(name, "|");
7335 while (flagName != NULL) {
7336 if (strlen(flagName) != 0) {
7337 flag |= stringToEnum(sInputFlagNameToEnumTable,
7338 ARRAY_SIZE(sInputFlagNameToEnumTable),
7339 flagName);
7340 }
7341 flagName = strtok(NULL, "|");
7342 }
7343 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007344}
7345
Eric Laurente0720872014-03-11 09:30:41 -07007346audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007347{
7348 uint32_t device = 0;
7349
7350 char *devName = strtok(name, "|");
7351 while (devName != NULL) {
7352 if (strlen(devName) != 0) {
7353 device |= stringToEnum(sDeviceNameToEnumTable,
7354 ARRAY_SIZE(sDeviceNameToEnumTable),
7355 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007356 }
Eric Laurente552edb2014-03-10 17:42:56 -07007357 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007358 }
Eric Laurente552edb2014-03-10 17:42:56 -07007359 return device;
7360}
7361
Eric Laurente0720872014-03-11 09:30:41 -07007362void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007363{
Eric Laurente552edb2014-03-10 17:42:56 -07007364 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007365 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007366 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007367
Eric Laurent1afeecb2014-05-14 08:52:28 -07007368 node = config_find(root, DEVICES_TAG);
7369 if (node != NULL) {
7370 node = node->first_child;
7371 while (node) {
7372 ALOGV("loadHwModule() loading device %s", node->name);
7373 status_t tmpStatus = module->loadDevice(node);
7374 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7375 status = tmpStatus;
7376 }
7377 node = node->next;
7378 }
7379 }
7380 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007381 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007382 node = node->first_child;
7383 while (node) {
7384 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007385 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007386 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7387 status = tmpStatus;
7388 }
7389 node = node->next;
7390 }
7391 }
7392 node = config_find(root, INPUTS_TAG);
7393 if (node != NULL) {
7394 node = node->first_child;
7395 while (node) {
7396 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007397 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007398 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7399 status = tmpStatus;
7400 }
7401 node = node->next;
7402 }
7403 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007404 loadGlobalConfig(root, module);
7405
Eric Laurente552edb2014-03-10 17:42:56 -07007406 if (status == NO_ERROR) {
7407 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007408 }
7409}
7410
Eric Laurente0720872014-03-11 09:30:41 -07007411void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007412{
7413 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7414 if (node == NULL) {
7415 return;
7416 }
7417
7418 node = node->first_child;
7419 while (node) {
7420 ALOGV("loadHwModules() loading module %s", node->name);
7421 loadHwModule(node);
7422 node = node->next;
7423 }
7424}
7425
Eric Laurent1f2f2232014-06-02 12:01:23 -07007426void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007427{
7428 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007429
Eric Laurente552edb2014-03-10 17:42:56 -07007430 if (node == NULL) {
7431 return;
7432 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007433 DeviceVector declaredDevices;
7434 if (module != NULL) {
7435 declaredDevices = module->mDeclaredDevices;
7436 }
7437
Eric Laurente552edb2014-03-10 17:42:56 -07007438 node = node->first_child;
7439 while (node) {
7440 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007441 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7442 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007443 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7444 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007445 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007446 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007447 ARRAY_SIZE(sDeviceNameToEnumTable),
7448 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007449 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007450 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007451 } else {
7452 ALOGW("loadGlobalConfig() default device not specified");
7453 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007454 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007455 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007456 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7457 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007458 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007459 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7460 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7461 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007462 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7463 uint32_t major, minor;
7464 sscanf((char *)node->value, "%u.%u", &major, &minor);
7465 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7466 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7467 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007468 }
7469 node = node->next;
7470 }
7471}
7472
Eric Laurente0720872014-03-11 09:30:41 -07007473status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007474{
7475 cnode *root;
7476 char *data;
7477
7478 data = (char *)load_file(path, NULL);
7479 if (data == NULL) {
7480 return -ENODEV;
7481 }
7482 root = config_node("", "");
7483 config_load(root, data);
7484
Eric Laurente552edb2014-03-10 17:42:56 -07007485 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007486 // legacy audio_policy.conf files have one global_configuration section
7487 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007488 config_free(root);
7489 free(root);
7490 free(data);
7491
7492 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7493
7494 return NO_ERROR;
7495}
7496
Eric Laurente0720872014-03-11 09:30:41 -07007497void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007498{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007499 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007500 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007501 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7502 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007503 mAvailableOutputDevices.add(mDefaultOutputDevice);
7504 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007505
7506 module = new HwModule("primary");
7507
Eric Laurent1afeecb2014-05-14 08:52:28 -07007508 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007509 profile->mSamplingRates.add(44100);
7510 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7511 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007512 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007513 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7514 module->mOutputProfiles.add(profile);
7515
Eric Laurent1afeecb2014-05-14 08:52:28 -07007516 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007517 profile->mSamplingRates.add(8000);
7518 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7519 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007520 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007521 module->mInputProfiles.add(profile);
7522
7523 mHwModules.add(module);
7524}
7525
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007526audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7527{
7528 // flags to stream type mapping
7529 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7530 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7531 }
7532 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7533 return AUDIO_STREAM_BLUETOOTH_SCO;
7534 }
7535
7536 // usage to stream type mapping
7537 switch (attr->usage) {
7538 case AUDIO_USAGE_MEDIA:
7539 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007540 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7541 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007542 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007543 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7544 return AUDIO_STREAM_ALARM;
7545 }
7546 if (isStreamActive(AUDIO_STREAM_RING)) {
7547 return AUDIO_STREAM_RING;
7548 }
7549 if (isInCall()) {
7550 return AUDIO_STREAM_VOICE_CALL;
7551 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08007552 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007553 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7554 return AUDIO_STREAM_SYSTEM;
7555 case AUDIO_USAGE_VOICE_COMMUNICATION:
7556 return AUDIO_STREAM_VOICE_CALL;
7557
7558 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7559 return AUDIO_STREAM_DTMF;
7560
7561 case AUDIO_USAGE_ALARM:
7562 return AUDIO_STREAM_ALARM;
7563 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7564 return AUDIO_STREAM_RING;
7565
7566 case AUDIO_USAGE_NOTIFICATION:
7567 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7568 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7569 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7570 case AUDIO_USAGE_NOTIFICATION_EVENT:
7571 return AUDIO_STREAM_NOTIFICATION;
7572
7573 case AUDIO_USAGE_UNKNOWN:
7574 default:
7575 return AUDIO_STREAM_MUSIC;
7576 }
7577}
Eric Laurente83b55d2014-11-14 10:06:21 -08007578
7579bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
7580 // has flags that map to a strategy?
7581 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7582 return true;
7583 }
7584
7585 // has known usage?
7586 switch (paa->usage) {
7587 case AUDIO_USAGE_UNKNOWN:
7588 case AUDIO_USAGE_MEDIA:
7589 case AUDIO_USAGE_VOICE_COMMUNICATION:
7590 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7591 case AUDIO_USAGE_ALARM:
7592 case AUDIO_USAGE_NOTIFICATION:
7593 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7594 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7595 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7596 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7597 case AUDIO_USAGE_NOTIFICATION_EVENT:
7598 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7599 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7600 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7601 case AUDIO_USAGE_GAME:
7602 break;
7603 default:
7604 return false;
7605 }
7606 return true;
7607}
7608
Eric Laurente552edb2014-03-10 17:42:56 -07007609}; // namespace android