blob: 8ca0b96c710e26120878d4cef4252dafedf8c489 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
Hochi Huang327cb702014-09-21 09:47:31 +080029#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
Eric Laurente552edb2014-03-10 17:42:56 -070030// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070047#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070048#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070049#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurent3b73df72014-03-11 09:06:29 -070051namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070052
53// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070054// Definitions for audio_policy.conf file parsing
55// ----------------------------------------------------------------------------
56
57struct StringToEnum {
58 const char *name;
59 uint32_t value;
60};
61
62#define STRING_TO_ENUM(string) { #string, string }
63#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64
65const StringToEnum sDeviceNameToEnumTable[] = {
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070069 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070081 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070087 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
91 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070092 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050093 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070094 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
98 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700108 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
110 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
111 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700112 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900113 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700114};
115
Eric Laurent5dbe4712014-09-19 19:04:57 -0700116const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700123 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700124};
125
Eric Laurent5dbe4712014-09-19 19:04:57 -0700126const StringToEnum sInputFlagNameToEnumTable[] = {
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
128 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
129};
130
Eric Laurent3a4311c2014-03-17 12:00:47 -0700131const StringToEnum sFormatNameToEnumTable[] = {
132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
137 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
138 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
149 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
152 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
153 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
154 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
155 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156};
157
158const StringToEnum sOutChannelsNameToEnumTable[] = {
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
163 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
164};
165
166const StringToEnum sInChannelsNameToEnumTable[] = {
167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
169 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
170};
171
Eric Laurent1afeecb2014-05-14 08:52:28 -0700172const StringToEnum sGainModeNameToEnumTable[] = {
173 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
174 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
175 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
176};
177
Eric Laurent3a4311c2014-03-17 12:00:47 -0700178
179uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
180 size_t size,
181 const char *name)
182{
183 for (size_t i = 0; i < size; i++) {
184 if (strcmp(table[i].name, name) == 0) {
185 ALOGV("stringToEnum() found %s", table[i].name);
186 return table[i].value;
187 }
188 }
189 return 0;
190}
191
192const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
193 size_t size,
194 uint32_t value)
195{
196 for (size_t i = 0; i < size; i++) {
197 if (table[i].value == value) {
198 return table[i].name;
199 }
200 }
201 return "";
202}
203
204bool AudioPolicyManager::stringToBool(const char *value)
205{
206 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
207}
208
209
210// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700211// AudioPolicyInterface implementation
212// ----------------------------------------------------------------------------
213
214
Eric Laurente0720872014-03-11 09:30:41 -0700215status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700216 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700217 const char *device_address)
218{
Eric Laurent22226012014-08-01 17:00:54 -0700219 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700220 // handle legacy remote submix case where the address was not always specified
221 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
222 address = String8("0");
223 }
Eric Laurente552edb2014-03-10 17:42:56 -0700224
Eric Laurent22226012014-08-01 17:00:54 -0700225 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
226 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700227
228 // connect/disconnect only 1 device at a time
229 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
230
Eric Laurente552edb2014-03-10 17:42:56 -0700231 // handle output devices
232 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700233 SortedVector <audio_io_handle_t> outputs;
234
Eric Laurent1afeecb2014-05-14 08:52:28 -0700235 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
236 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
238
Eric Laurente552edb2014-03-10 17:42:56 -0700239 // save a copy of the opened output descriptors before any output is opened or closed
240 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
241 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700242 switch (state)
243 {
244 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700245 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700246 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700247 ALOGW("setDeviceConnectionState() device already connected: %x", device);
248 return INVALID_OPERATION;
249 }
250 ALOGV("setDeviceConnectionState() connecting device %x", device);
251
Eric Laurente552edb2014-03-10 17:42:56 -0700252 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 index = mAvailableOutputDevices.add(devDesc);
254 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700255 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700256 if (module == 0) {
257 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
258 device);
259 mAvailableOutputDevices.remove(devDesc);
260 return INVALID_OPERATION;
261 }
262 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700263 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 } else {
265 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700266 }
267
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700268 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700269 mAvailableOutputDevices.remove(devDesc);
270 return INVALID_OPERATION;
271 }
272 // outputs should never be empty here
273 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
274 "checkOutputsForDevice() returned no outputs but status OK");
275 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
276 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700277 break;
278 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700279 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700280 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700281 ALOGW("setDeviceConnectionState() device not connected: %x", device);
282 return INVALID_OPERATION;
283 }
284
Paul McLean5c477aa2014-08-20 16:47:57 -0700285 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
286
287 // Set Disconnect to HALs
288 AudioParameter param = AudioParameter(address);
289 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
290 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
291
Eric Laurente552edb2014-03-10 17:42:56 -0700292 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700293 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700294
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700295 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700296 } break;
297
298 default:
299 ALOGE("setDeviceConnectionState() invalid state: %x", state);
300 return BAD_VALUE;
301 }
302
Eric Laurent3a4311c2014-03-17 12:00:47 -0700303 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
304 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700305 checkA2dpSuspend();
306 checkOutputForAllStrategies();
307 // outputs must be closed after checkOutputForAllStrategies() is executed
308 if (!outputs.isEmpty()) {
309 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700310 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700311 // close unused outputs after device disconnection or direct outputs that have been
312 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700313 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700314 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
315 (desc->mDirectOpenCount == 0))) {
316 closeOutput(outputs[i]);
317 }
318 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700319 // check again after closing A2DP output to reset mA2dpSuspended if needed
320 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700321 }
322
323 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 if (mPhoneState == AUDIO_MODE_IN_CALL) {
325 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
326 updateCallRouting(newDevice);
327 }
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700329 audio_io_handle_t output = mOutputs.keyAt(i);
330 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
331 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
332 true /*fromCache*/);
333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
336 bool force = !mOutputs.valueAt(i)->isDuplicated()
337 && (!deviceDistinguishesOnAddress(device)
338 // always force when disconnecting (a non-duplicated device)
339 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
340 setOutputDevice(output, newDevice, force, 0);
341 }
Eric Laurente552edb2014-03-10 17:42:56 -0700342 }
343
Eric Laurent72aa32f2014-05-30 18:51:48 -0700344 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700345 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700346 } // end if is output device
347
Eric Laurente552edb2014-03-10 17:42:56 -0700348 // handle input devices
349 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700350 SortedVector <audio_io_handle_t> inputs;
351
Eric Laurent1afeecb2014-05-14 08:52:28 -0700352 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
353 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700355 switch (state)
356 {
357 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700358 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700360 ALOGW("setDeviceConnectionState() device already connected: %d", device);
361 return INVALID_OPERATION;
362 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700363 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700364 if (module == NULL) {
365 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
366 device);
367 return INVALID_OPERATION;
368 }
Eric Laurentd4692962014-05-05 18:13:44 -0700369 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
370 return INVALID_OPERATION;
371 }
372
Eric Laurent3a4311c2014-03-17 12:00:47 -0700373 index = mAvailableInputDevices.add(devDesc);
374 if (index >= 0) {
375 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700376 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700377 } else {
378 return NO_MEMORY;
379 }
Eric Laurentd4692962014-05-05 18:13:44 -0700380 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700381
382 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700383 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700384 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700385 ALOGW("setDeviceConnectionState() device not connected: %d", device);
386 return INVALID_OPERATION;
387 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700388
389 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
390
391 // Set Disconnect to HALs
392 AudioParameter param = AudioParameter(address);
393 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
394 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
395
Eric Laurentd4692962014-05-05 18:13:44 -0700396 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700397 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700398
Eric Laurentd4692962014-05-05 18:13:44 -0700399 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700400
401 default:
402 ALOGE("setDeviceConnectionState() invalid state: %x", state);
403 return BAD_VALUE;
404 }
405
Eric Laurentd4692962014-05-05 18:13:44 -0700406 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700407
Eric Laurentc2730ba2014-07-20 15:47:07 -0700408 if (mPhoneState == AUDIO_MODE_IN_CALL) {
409 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
410 updateCallRouting(newDevice);
411 }
412
Eric Laurentb52c1522014-05-20 11:27:36 -0700413 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700414 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700415 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700416
417 ALOGW("setDeviceConnectionState() invalid device: %x", device);
418 return BAD_VALUE;
419}
420
Eric Laurente0720872014-03-11 09:30:41 -0700421audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700422 const char *device_address)
423{
Eric Laurent3b73df72014-03-11 09:06:29 -0700424 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700425 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700426 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700427 // handle legacy remote submix case where the address was not always specified
428 if (deviceDistinguishesOnAddress(device) && (devDesc->mAddress.length() == 0)) {
429 devDesc->mAddress = String8("0");
430 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700431 ssize_t index;
432 DeviceVector *deviceVector;
433
Eric Laurente552edb2014-03-10 17:42:56 -0700434 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700435 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700436 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700437 deviceVector = &mAvailableInputDevices;
438 } else {
439 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
440 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700441 }
442
Eric Laurent3a4311c2014-03-17 12:00:47 -0700443 index = deviceVector->indexOf(devDesc);
444 if (index >= 0) {
445 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
446 } else {
447 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
448 }
Eric Laurente552edb2014-03-10 17:42:56 -0700449}
450
Eric Laurentc2730ba2014-07-20 15:47:07 -0700451void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
452{
453 bool createTxPatch = false;
454 struct audio_patch patch;
455 patch.num_sources = 1;
456 patch.num_sinks = 1;
457 status_t status;
458 audio_patch_handle_t afPatchHandle;
459 DeviceVector deviceList;
460
461 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
462 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
463
464 // release existing RX patch if any
465 if (mCallRxPatch != 0) {
466 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
467 mCallRxPatch.clear();
468 }
469 // release TX patch if any
470 if (mCallTxPatch != 0) {
471 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
472 mCallTxPatch.clear();
473 }
474
475 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
476 // via setOutputDevice() on primary output.
477 // Otherwise, create two audio patches for TX and RX path.
478 if (availablePrimaryOutputDevices() & rxDevice) {
479 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
480 // If the TX device is also on the primary HW module, setOutputDevice() will take care
481 // of it due to legacy implementation. If not, create a patch.
482 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
483 == AUDIO_DEVICE_NONE) {
484 createTxPatch = true;
485 }
486 } else {
487 // create RX path audio patch
488 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
489 ALOG_ASSERT(!deviceList.isEmpty(),
490 "updateCallRouting() selected device not in output device list");
491 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
492 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
493 ALOG_ASSERT(!deviceList.isEmpty(),
494 "updateCallRouting() no telephony RX device");
495 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
496
497 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
498 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
499
500 // request to reuse existing output stream if one is already opened to reach the RX device
501 SortedVector<audio_io_handle_t> outputs =
502 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700503 audio_io_handle_t output = selectOutput(outputs,
504 AUDIO_OUTPUT_FLAG_NONE,
505 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700506 if (output != AUDIO_IO_HANDLE_NONE) {
507 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
508 ALOG_ASSERT(!outputDesc->isDuplicated(),
509 "updateCallRouting() RX device output is duplicated");
510 outputDesc->toAudioPortConfig(&patch.sources[1]);
511 patch.num_sources = 2;
512 }
513
514 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
515 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
516 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
517 status);
518 if (status == NO_ERROR) {
519 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
520 &patch, mUidCached);
521 mCallRxPatch->mAfPatchHandle = afPatchHandle;
522 mCallRxPatch->mUid = mUidCached;
523 }
524 createTxPatch = true;
525 }
526 if (createTxPatch) {
527
528 struct audio_patch patch;
529 patch.num_sources = 1;
530 patch.num_sinks = 1;
531 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
532 ALOG_ASSERT(!deviceList.isEmpty(),
533 "updateCallRouting() selected device not in input device list");
534 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
535 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
536 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
537 ALOG_ASSERT(!deviceList.isEmpty(),
538 "updateCallRouting() no telephony TX device");
539 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
540 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
541
542 SortedVector<audio_io_handle_t> outputs =
543 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700544 audio_io_handle_t output = selectOutput(outputs,
545 AUDIO_OUTPUT_FLAG_NONE,
546 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700547 // request to reuse existing output stream if one is already opened to reach the TX
548 // path output device
549 if (output != AUDIO_IO_HANDLE_NONE) {
550 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
551 ALOG_ASSERT(!outputDesc->isDuplicated(),
552 "updateCallRouting() RX device output is duplicated");
553 outputDesc->toAudioPortConfig(&patch.sources[1]);
554 patch.num_sources = 2;
555 }
556
557 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
558 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
559 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
560 status);
561 if (status == NO_ERROR) {
562 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
563 &patch, mUidCached);
564 mCallTxPatch->mAfPatchHandle = afPatchHandle;
565 mCallTxPatch->mUid = mUidCached;
566 }
567 }
568}
569
Eric Laurente0720872014-03-11 09:30:41 -0700570void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700571{
572 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700573 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700574 ALOGW("setPhoneState() invalid state %d", state);
575 return;
576 }
577
578 if (state == mPhoneState ) {
579 ALOGW("setPhoneState() setting same state %d", state);
580 return;
581 }
582
583 // if leaving call state, handle special case of active streams
584 // pertaining to sonification strategy see handleIncallSonification()
585 if (isInCall()) {
586 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700587 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800588 if (stream == AUDIO_STREAM_PATCH) {
589 continue;
590 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700591 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700592 }
593 }
594
595 // store previous phone state for management of sonification strategy below
596 int oldState = mPhoneState;
597 mPhoneState = state;
598 bool force = false;
599
600 // are we entering or starting a call
601 if (!isStateInCall(oldState) && isStateInCall(state)) {
602 ALOGV(" Entering call in setPhoneState()");
603 // force routing command to audio hardware when starting a call
604 // even if no device change is needed
605 force = true;
606 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
607 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
608 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
609 }
610 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
611 ALOGV(" Exiting call in setPhoneState()");
612 // force routing command to audio hardware when exiting a call
613 // even if no device change is needed
614 force = true;
615 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
616 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
617 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
618 }
619 } else if (isStateInCall(state) && (state != oldState)) {
620 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
621 // force routing command to audio hardware when switching between telephony and VoIP
622 // even if no device change is needed
623 force = true;
624 }
625
626 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700627 checkA2dpSuspend();
628 checkOutputForAllStrategies();
629 updateDevicesAndOutputs();
630
Eric Laurent1f2f2232014-06-02 12:01:23 -0700631 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700632
Eric Laurente552edb2014-03-10 17:42:56 -0700633 int delayMs = 0;
634 if (isStateInCall(state)) {
635 nsecs_t sysTime = systemTime();
636 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700637 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700638 // mute media and sonification strategies and delay device switch by the largest
639 // latency of any output where either strategy is active.
640 // This avoid sending the ring tone or music tail into the earpiece or headset.
641 if ((desc->isStrategyActive(STRATEGY_MEDIA,
642 SONIFICATION_HEADSET_MUSIC_DELAY,
643 sysTime) ||
644 desc->isStrategyActive(STRATEGY_SONIFICATION,
645 SONIFICATION_HEADSET_MUSIC_DELAY,
646 sysTime)) &&
647 (delayMs < (int)desc->mLatency*2)) {
648 delayMs = desc->mLatency*2;
649 }
650 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
651 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
652 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
653 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
654 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
655 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
656 }
657 }
658
Eric Laurentc2730ba2014-07-20 15:47:07 -0700659 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
660 // the device returned is not necessarily reachable via this output
661 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
662 // force routing command to audio hardware when ending call
663 // even if no device change is needed
664 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
665 rxDevice = hwOutputDesc->device();
666 }
Eric Laurente552edb2014-03-10 17:42:56 -0700667
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668 if (state == AUDIO_MODE_IN_CALL) {
669 updateCallRouting(rxDevice, delayMs);
670 } else if (oldState == AUDIO_MODE_IN_CALL) {
671 if (mCallRxPatch != 0) {
672 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
673 mCallRxPatch.clear();
674 }
675 if (mCallTxPatch != 0) {
676 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
677 mCallTxPatch.clear();
678 }
679 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
680 } else {
681 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
682 }
Eric Laurente552edb2014-03-10 17:42:56 -0700683 // if entering in call state, handle special case of active streams
684 // pertaining to sonification strategy see handleIncallSonification()
685 if (isStateInCall(state)) {
686 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700687 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800688 if (stream == AUDIO_STREAM_PATCH) {
689 continue;
690 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700691 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700692 }
693 }
694
695 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700696 if (state == AUDIO_MODE_RINGTONE &&
697 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700698 mLimitRingtoneVolume = true;
699 } else {
700 mLimitRingtoneVolume = false;
701 }
702}
703
Eric Laurente0720872014-03-11 09:30:41 -0700704void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700705 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700706{
707 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
708
709 bool forceVolumeReeval = false;
710 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700711 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
712 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
713 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700714 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
715 return;
716 }
717 forceVolumeReeval = true;
718 mForceUse[usage] = config;
719 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700720 case AUDIO_POLICY_FORCE_FOR_MEDIA:
721 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
722 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
723 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
724 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800725 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700726 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
727 return;
728 }
729 mForceUse[usage] = config;
730 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700731 case AUDIO_POLICY_FORCE_FOR_RECORD:
732 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
733 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700734 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
735 return;
736 }
737 mForceUse[usage] = config;
738 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700739 case AUDIO_POLICY_FORCE_FOR_DOCK:
740 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
741 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
742 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
743 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
744 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700745 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
746 }
747 forceVolumeReeval = true;
748 mForceUse[usage] = config;
749 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700750 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
751 if (config != AUDIO_POLICY_FORCE_NONE &&
752 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700753 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
754 }
755 forceVolumeReeval = true;
756 mForceUse[usage] = config;
757 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900758 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
759 if (config != AUDIO_POLICY_FORCE_NONE &&
760 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
761 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
762 }
763 mForceUse[usage] = config;
764 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700765 default:
766 ALOGW("setForceUse() invalid usage %d", usage);
767 break;
768 }
769
770 // check for device and output changes triggered by new force usage
771 checkA2dpSuspend();
772 checkOutputForAllStrategies();
773 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700774 if (mPhoneState == AUDIO_MODE_IN_CALL) {
775 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
776 updateCallRouting(newDevice);
777 }
Eric Laurente552edb2014-03-10 17:42:56 -0700778 for (size_t i = 0; i < mOutputs.size(); i++) {
779 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700780 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700781 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
782 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
783 }
Eric Laurente552edb2014-03-10 17:42:56 -0700784 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
785 applyStreamVolumes(output, newDevice, 0, true);
786 }
787 }
788
789 audio_io_handle_t activeInput = getActiveInput();
790 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700791 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700792 }
793
794}
795
Eric Laurente0720872014-03-11 09:30:41 -0700796audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700797{
798 return mForceUse[usage];
799}
800
Eric Laurente0720872014-03-11 09:30:41 -0700801void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700802{
803 ALOGV("setSystemProperty() property %s, value %s", property, value);
804}
805
806// Find a direct output profile compatible with the parameters passed, even if the input flags do
807// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700808sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700809 audio_devices_t device,
810 uint32_t samplingRate,
811 audio_format_t format,
812 audio_channel_mask_t channelMask,
813 audio_output_flags_t flags)
814{
815 for (size_t i = 0; i < mHwModules.size(); i++) {
816 if (mHwModules[i]->mHandle == 0) {
817 continue;
818 }
819 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700820 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700821 bool found = profile->isCompatibleProfile(device, samplingRate,
822 NULL /*updatedSamplingRate*/, format, channelMask,
823 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
824 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700825 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
826 return profile;
827 }
Eric Laurente552edb2014-03-10 17:42:56 -0700828 }
829 }
830 return 0;
831}
832
Eric Laurente0720872014-03-11 09:30:41 -0700833audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700834 uint32_t samplingRate,
835 audio_format_t format,
836 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700837 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700838 const audio_offload_info_t *offloadInfo)
839{
Eric Laurent3b73df72014-03-11 09:06:29 -0700840 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700841 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
842 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
843 device, stream, samplingRate, format, channelMask, flags);
844
Eric Laurente83b55d2014-11-14 10:06:21 -0800845 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
846 stream, samplingRate,format, channelMask,
847 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848}
849
Eric Laurente83b55d2014-11-14 10:06:21 -0800850status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
851 audio_io_handle_t *output,
852 audio_session_t session,
853 audio_stream_type_t *stream,
854 uint32_t samplingRate,
855 audio_format_t format,
856 audio_channel_mask_t channelMask,
857 audio_output_flags_t flags,
858 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700859{
Eric Laurente83b55d2014-11-14 10:06:21 -0800860 audio_attributes_t attributes;
861 if (attr != NULL) {
862 if (!isValidAttributes(attr)) {
863 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
864 attr->usage, attr->content_type, attr->flags,
865 attr->tags);
866 return BAD_VALUE;
867 }
868 attributes = *attr;
869 } else {
870 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
871 ALOGE("getOutputForAttr(): invalid stream type");
872 return BAD_VALUE;
873 }
874 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700875 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800876
Eric Laurent93c3d412014-08-01 14:48:35 -0700877 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800878 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700879
880 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
Eric Laurente83b55d2014-11-14 10:06:21 -0800881 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700882 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700883
Eric Laurente83b55d2014-11-14 10:06:21 -0800884 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700885 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
886 }
887
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700888 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700889 device, samplingRate, format, channelMask, flags);
890
Eric Laurente83b55d2014-11-14 10:06:21 -0800891 *stream = streamTypefromAttributesInt(&attributes);
892 *output = getOutputForDevice(device, session, *stream,
893 samplingRate, format, channelMask,
894 flags, offloadInfo);
895 if (*output == AUDIO_IO_HANDLE_NONE) {
896 return INVALID_OPERATION;
897 }
898 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700899}
900
901audio_io_handle_t AudioPolicyManager::getOutputForDevice(
902 audio_devices_t device,
Eric Laurente83b55d2014-11-14 10:06:21 -0800903 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700904 audio_stream_type_t stream,
905 uint32_t samplingRate,
906 audio_format_t format,
907 audio_channel_mask_t channelMask,
908 audio_output_flags_t flags,
909 const audio_offload_info_t *offloadInfo)
910{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700911 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700912 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700913 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700914
Eric Laurente552edb2014-03-10 17:42:56 -0700915#ifdef AUDIO_POLICY_TEST
916 if (mCurOutput != 0) {
917 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
918 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
919
920 if (mTestOutputs[mCurOutput] == 0) {
921 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700922 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700923 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700924 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700925 outputDesc->mFlags =
926 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700927 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700928 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
929 config.sample_rate = mTestSamplingRate;
930 config.channel_mask = mTestChannels;
931 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700932 if (offloadInfo != NULL) {
933 config.offload_info = *offloadInfo;
934 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700935 status = mpClientInterface->openOutput(0,
936 &mTestOutputs[mCurOutput],
937 &config,
938 &outputDesc->mDevice,
939 String8(""),
940 &outputDesc->mLatency,
941 outputDesc->mFlags);
942 if (status == NO_ERROR) {
943 outputDesc->mSamplingRate = config.sample_rate;
944 outputDesc->mFormat = config.format;
945 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700946 AudioParameter outputCmd = AudioParameter();
947 outputCmd.addInt(String8("set_id"),mCurOutput);
948 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
949 addOutput(mTestOutputs[mCurOutput], outputDesc);
950 }
951 }
952 return mTestOutputs[mCurOutput];
953 }
954#endif //AUDIO_POLICY_TEST
955
956 // open a direct output if required by specified parameters
957 //force direct flag if offload flag is set: offloading implies a direct output stream
958 // and all common behaviors are driven by checking only the direct flag
959 // this should normally be set appropriately in the policy configuration file
960 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700961 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700962 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700963 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
964 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
965 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800966 // only allow deep buffering for music stream type
967 if (stream != AUDIO_STREAM_MUSIC) {
968 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
969 }
Eric Laurente552edb2014-03-10 17:42:56 -0700970
Eric Laurentb732cf52014-09-24 19:08:21 -0700971 sp<IOProfile> profile;
972
973 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700974 // and not explicitly requested
975 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
976 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700977 audio_channel_count_from_out_mask(channelMask) <= 2) {
978 goto non_direct_output;
979 }
980
Eric Laurente552edb2014-03-10 17:42:56 -0700981 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
982 // creating an offloaded track and tearing it down immediately after start when audioflinger
983 // detects there is an active non offloadable effect.
984 // FIXME: We should check the audio session here but we do not have it in this context.
985 // This may prevent offloading in rare situations where effects are left active by apps
986 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700987
Eric Laurente552edb2014-03-10 17:42:56 -0700988 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
989 !isNonOffloadableEffectEnabled()) {
990 profile = getProfileForDirectOutput(device,
991 samplingRate,
992 format,
993 channelMask,
994 (audio_output_flags_t)flags);
995 }
996
Eric Laurent1c333e22014-05-20 10:48:17 -0700997 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700998 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700999
1000 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001001 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001002 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1003 outputDesc = desc;
1004 // reuse direct output if currently open and configured with same parameters
1005 if ((samplingRate == outputDesc->mSamplingRate) &&
1006 (format == outputDesc->mFormat) &&
1007 (channelMask == outputDesc->mChannelMask)) {
1008 outputDesc->mDirectOpenCount++;
1009 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1010 return mOutputs.keyAt(i);
1011 }
1012 }
1013 }
1014 // close direct output if currently open and configured with different parameters
1015 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001016 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001017 }
1018 outputDesc = new AudioOutputDescriptor(profile);
1019 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001020 outputDesc->mLatency = 0;
1021 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001022 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1023 config.sample_rate = samplingRate;
1024 config.channel_mask = channelMask;
1025 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001026 if (offloadInfo != NULL) {
1027 config.offload_info = *offloadInfo;
1028 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001029 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1030 &output,
1031 &config,
1032 &outputDesc->mDevice,
1033 String8(""),
1034 &outputDesc->mLatency,
1035 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001036
1037 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001038 if (status != NO_ERROR ||
1039 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1040 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1041 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001042 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1043 "format %d %d, channelMask %04x %04x", output, samplingRate,
1044 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1045 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001046 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001047 mpClientInterface->closeOutput(output);
1048 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001049 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001050 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001051 outputDesc->mSamplingRate = config.sample_rate;
1052 outputDesc->mChannelMask = config.channel_mask;
1053 outputDesc->mFormat = config.format;
1054 outputDesc->mRefCount[stream] = 0;
1055 outputDesc->mStopTime[stream] = 0;
1056 outputDesc->mDirectOpenCount = 1;
1057
Eric Laurente552edb2014-03-10 17:42:56 -07001058 audio_io_handle_t srcOutput = getOutputForEffect();
1059 addOutput(output, outputDesc);
1060 audio_io_handle_t dstOutput = getOutputForEffect();
1061 if (dstOutput == output) {
1062 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1063 }
1064 mPreviousOutputs = mOutputs;
1065 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001066 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001067 return output;
1068 }
1069
Eric Laurentb732cf52014-09-24 19:08:21 -07001070non_direct_output:
1071
Eric Laurente552edb2014-03-10 17:42:56 -07001072 // ignoring channel mask due to downmix capability in mixer
1073
1074 // open a non direct output
1075
1076 // for non direct outputs, only PCM is supported
1077 if (audio_is_linear_pcm(format)) {
1078 // get which output is suitable for the specified stream. The actual
1079 // routing change will happen when startOutput() will be called
1080 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1081
Eric Laurent8838a382014-09-08 16:44:28 -07001082 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1083 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1084 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001085 }
1086 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1087 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1088
1089 ALOGV("getOutput() returns output %d", output);
1090
1091 return output;
1092}
1093
Eric Laurente0720872014-03-11 09:30:41 -07001094audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001095 audio_output_flags_t flags,
1096 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001097{
1098 // select one output among several that provide a path to a particular device or set of
1099 // devices (the list was previously build by getOutputsForDevice()).
1100 // The priority is as follows:
1101 // 1: the output with the highest number of requested policy flags
1102 // 2: the primary output
1103 // 3: the first output in the list
1104
1105 if (outputs.size() == 0) {
1106 return 0;
1107 }
1108 if (outputs.size() == 1) {
1109 return outputs[0];
1110 }
1111
1112 int maxCommonFlags = 0;
1113 audio_io_handle_t outputFlags = 0;
1114 audio_io_handle_t outputPrimary = 0;
1115
1116 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001117 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001118 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001119 // if a valid format is specified, skip output if not compatible
1120 if (format != AUDIO_FORMAT_INVALID) {
1121 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1122 if (format != outputDesc->mFormat) {
1123 continue;
1124 }
1125 } else if (!audio_is_linear_pcm(format)) {
1126 continue;
1127 }
1128 }
1129
Eric Laurent3b73df72014-03-11 09:06:29 -07001130 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001131 if (commonFlags > maxCommonFlags) {
1132 outputFlags = outputs[i];
1133 maxCommonFlags = commonFlags;
1134 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1135 }
1136 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1137 outputPrimary = outputs[i];
1138 }
1139 }
1140 }
1141
1142 if (outputFlags != 0) {
1143 return outputFlags;
1144 }
1145 if (outputPrimary != 0) {
1146 return outputPrimary;
1147 }
1148
1149 return outputs[0];
1150}
1151
Eric Laurente0720872014-03-11 09:30:41 -07001152status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001153 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001154 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001155{
1156 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1157 ssize_t index = mOutputs.indexOfKey(output);
1158 if (index < 0) {
1159 ALOGW("startOutput() unknown output %d", output);
1160 return BAD_VALUE;
1161 }
1162
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001163 // cannot start playback of STREAM_TTS if any other output is being used
1164 uint32_t beaconMuteLatency = 0;
1165 if (stream == AUDIO_STREAM_TTS) {
1166 ALOGV("\t found BEACON stream");
1167 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1168 return INVALID_OPERATION;
1169 } else {
1170 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1171 }
1172 } else {
1173 // some playback other than beacon starts
1174 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1175 }
1176
Eric Laurent1f2f2232014-06-02 12:01:23 -07001177 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001178
1179 // increment usage count for this stream on the requested output:
1180 // NOTE that the usage count is the same for duplicated output and hardware output which is
1181 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1182 outputDesc->changeRefCount(stream, 1);
1183
1184 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001185 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001186 routing_strategy strategy = getStrategy(stream);
1187 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001188 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1189 (beaconMuteLatency > 0);
1190 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001191 bool force = false;
1192 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001193 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001194 if (desc != outputDesc) {
1195 // force a device change if any other output is managed by the same hw
1196 // module and has a current device selection that differs from selected device.
1197 // In this case, the audio HAL must receive the new device selection so that it can
1198 // change the device currently selected by the other active output.
1199 if (outputDesc->sharesHwModuleWith(desc) &&
1200 desc->device() != newDevice) {
1201 force = true;
1202 }
1203 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001204 // a notification so that audio focus effect can propagate, or that a mute/unmute
1205 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001206 uint32_t latency = desc->latency();
1207 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1208 waitMs = latency;
1209 }
1210 }
1211 }
1212 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1213
1214 // handle special case for sonification while in call
1215 if (isInCall()) {
1216 handleIncallSonification(stream, true, false);
1217 }
1218
1219 // apply volume rules for current stream and device if necessary
1220 checkAndSetVolume(stream,
1221 mStreams[stream].getVolumeIndex(newDevice),
1222 output,
1223 newDevice);
1224
1225 // update the outputs if starting an output with a stream that can affect notification
1226 // routing
1227 handleNotificationRoutingForStream(stream);
1228 if (waitMs > muteWaitMs) {
1229 usleep((waitMs - muteWaitMs) * 2 * 1000);
1230 }
1231 }
1232 return NO_ERROR;
1233}
1234
1235
Eric Laurente0720872014-03-11 09:30:41 -07001236status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001237 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001238 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001239{
1240 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1241 ssize_t index = mOutputs.indexOfKey(output);
1242 if (index < 0) {
1243 ALOGW("stopOutput() unknown output %d", output);
1244 return BAD_VALUE;
1245 }
1246
Eric Laurent1f2f2232014-06-02 12:01:23 -07001247 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001248
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001249 // always handle stream stop, check which stream type is stopping
1250 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1251
Eric Laurente552edb2014-03-10 17:42:56 -07001252 // handle special case for sonification while in call
1253 if (isInCall()) {
1254 handleIncallSonification(stream, false, false);
1255 }
1256
1257 if (outputDesc->mRefCount[stream] > 0) {
1258 // decrement usage count of this stream on the output
1259 outputDesc->changeRefCount(stream, -1);
1260 // store time at which the stream was stopped - see isStreamActive()
1261 if (outputDesc->mRefCount[stream] == 0) {
1262 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001263 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001264 // delay the device switch by twice the latency because stopOutput() is executed when
1265 // the track stop() command is received and at that time the audio track buffer can
1266 // still contain data that needs to be drained. The latency only covers the audio HAL
1267 // and kernel buffers. Also the latency does not always include additional delay in the
1268 // audio path (audio DSP, CODEC ...)
1269 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1270
1271 // force restoring the device selection on other active outputs if it differs from the
1272 // one being selected for this output
1273 for (size_t i = 0; i < mOutputs.size(); i++) {
1274 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001275 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001276 if (curOutput != output &&
1277 desc->isActive() &&
1278 outputDesc->sharesHwModuleWith(desc) &&
1279 (newDevice != desc->device())) {
1280 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001281 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001282 true,
1283 outputDesc->mLatency*2);
1284 }
1285 }
1286 // update the outputs if stopping one with a stream that can affect notification routing
1287 handleNotificationRoutingForStream(stream);
1288 }
1289 return NO_ERROR;
1290 } else {
1291 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1292 return INVALID_OPERATION;
1293 }
1294}
1295
Eric Laurente83b55d2014-11-14 10:06:21 -08001296void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
1297 audio_stream_type_t stream,
1298 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001299{
1300 ALOGV("releaseOutput() %d", output);
1301 ssize_t index = mOutputs.indexOfKey(output);
1302 if (index < 0) {
1303 ALOGW("releaseOutput() releasing unknown output %d", output);
1304 return;
1305 }
1306
1307#ifdef AUDIO_POLICY_TEST
1308 int testIndex = testOutputIndex(output);
1309 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001310 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001311 if (outputDesc->isActive()) {
1312 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001313 mOutputs.removeItem(output);
1314 mTestOutputs[testIndex] = 0;
1315 }
1316 return;
1317 }
1318#endif //AUDIO_POLICY_TEST
1319
Eric Laurent1f2f2232014-06-02 12:01:23 -07001320 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001321 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001322 if (desc->mDirectOpenCount <= 0) {
1323 ALOGW("releaseOutput() invalid open count %d for output %d",
1324 desc->mDirectOpenCount, output);
1325 return;
1326 }
1327 if (--desc->mDirectOpenCount == 0) {
1328 closeOutput(output);
1329 // If effects where present on the output, audioflinger moved them to the primary
1330 // output by default: move them back to the appropriate output.
1331 audio_io_handle_t dstOutput = getOutputForEffect();
1332 if (dstOutput != mPrimaryOutput) {
1333 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1334 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001335 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001336 }
1337 }
1338}
1339
1340
Eric Laurente0720872014-03-11 09:30:41 -07001341audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001342 uint32_t samplingRate,
1343 audio_format_t format,
1344 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001345 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001346 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001347{
Eric Laurent4dc68062014-07-28 17:26:49 -07001348 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001349 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001350 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001351
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001352 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001353
1354 if (device == AUDIO_DEVICE_NONE) {
1355 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001356 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001357 }
1358
1359 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001360 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001361 case AUDIO_SOURCE_VOICE_UPLINK:
1362 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1363 break;
1364 case AUDIO_SOURCE_VOICE_DOWNLINK:
1365 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1366 break;
1367 case AUDIO_SOURCE_VOICE_CALL:
1368 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1369 break;
1370 default:
1371 break;
1372 }
1373
Eric Laurent5dbe4712014-09-19 19:04:57 -07001374 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1375 bool isSoundTrigger = false;
1376 audio_source_t halInputSource = inputSource;
1377 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1378 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1379 if (index >= 0) {
1380 input = mSoundTriggerSessions.valueFor(session);
1381 isSoundTrigger = true;
1382 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1383 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1384 } else {
1385 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1386 }
1387 }
1388
Eric Laurent1c333e22014-05-20 10:48:17 -07001389 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001390 samplingRate,
1391 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001392 channelMask,
1393 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001394 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001395 //retry without flags
1396 audio_input_flags_t log_flags = flags;
1397 flags = AUDIO_INPUT_FLAG_NONE;
1398 profile = getInputProfile(device,
1399 samplingRate,
1400 format,
1401 channelMask,
1402 flags);
1403 if (profile == 0) {
1404 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1405 "channelMask 0x%X, flags %#x",
1406 device, samplingRate, format, channelMask, log_flags);
1407 return AUDIO_IO_HANDLE_NONE;
1408 }
Eric Laurente552edb2014-03-10 17:42:56 -07001409 }
1410
1411 if (profile->mModule->mHandle == 0) {
1412 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001413 return AUDIO_IO_HANDLE_NONE;
1414 }
1415
1416 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1417 config.sample_rate = samplingRate;
1418 config.channel_mask = channelMask;
1419 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001420
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001421 // handle legacy remote submix case where the address was not always specified
1422 String8 address = deviceDistinguishesOnAddress(device) ? String8("0") : String8("");
1423
Eric Laurentcf2c0212014-07-25 16:20:43 -07001424 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1425 &input,
1426 &config,
1427 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001428 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001429 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001430 flags);
1431
1432 // only accept input with the exact requested set of parameters
1433 if (status != NO_ERROR ||
1434 (samplingRate != config.sample_rate) ||
1435 (format != config.format) ||
1436 (channelMask != config.channel_mask)) {
1437 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1438 samplingRate, format, channelMask);
1439 if (input != AUDIO_IO_HANDLE_NONE) {
1440 mpClientInterface->closeInput(input);
1441 }
1442 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001443 }
1444
Eric Laurent1f2f2232014-06-02 12:01:23 -07001445 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001446 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001447 inputDesc->mRefCount = 0;
1448 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001449 inputDesc->mSamplingRate = samplingRate;
1450 inputDesc->mFormat = format;
1451 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001452 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001453 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001454 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001455
Eric Laurentd4692962014-05-05 18:13:44 -07001456 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001457 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001458 return input;
1459}
1460
Eric Laurent4dc68062014-07-28 17:26:49 -07001461status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1462 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001463{
1464 ALOGV("startInput() input %d", input);
1465 ssize_t index = mInputs.indexOfKey(input);
1466 if (index < 0) {
1467 ALOGW("startInput() unknown input %d", input);
1468 return BAD_VALUE;
1469 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001470 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001471
Eric Laurent4dc68062014-07-28 17:26:49 -07001472 index = inputDesc->mSessions.indexOf(session);
1473 if (index < 0) {
1474 ALOGW("startInput() unknown session %d on input %d", session, input);
1475 return BAD_VALUE;
1476 }
1477
Glenn Kasten74a8e252014-07-24 14:09:55 -07001478 // virtual input devices are compatible with other input devices
1479 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1480
1481 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001482 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001483 if (activeInput != 0 && activeInput != input) {
1484
1485 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1486 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001487 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001488 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001489 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001490 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1491 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001492 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001493 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001494 return INVALID_OPERATION;
1495 }
1496 }
1497 }
1498
Glenn Kasten74a8e252014-07-24 14:09:55 -07001499 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001500 if (activeInputsCount() == 0) {
1501 SoundTrigger::setCaptureState(true);
1502 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001503 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001504
Glenn Kasten74a8e252014-07-24 14:09:55 -07001505 // Automatically enable the remote submix output when input is started.
1506 // For remote submix (a virtual device), we open only one input per capture request.
1507 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1508 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1509 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1510 }
Eric Laurente552edb2014-03-10 17:42:56 -07001511 }
1512
Eric Laurente552edb2014-03-10 17:42:56 -07001513 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1514
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001515 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001516 return NO_ERROR;
1517}
1518
Eric Laurent4dc68062014-07-28 17:26:49 -07001519status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1520 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001521{
1522 ALOGV("stopInput() input %d", input);
1523 ssize_t index = mInputs.indexOfKey(input);
1524 if (index < 0) {
1525 ALOGW("stopInput() unknown input %d", input);
1526 return BAD_VALUE;
1527 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001528 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001529
Eric Laurent4dc68062014-07-28 17:26:49 -07001530 index = inputDesc->mSessions.indexOf(session);
1531 if (index < 0) {
1532 ALOGW("stopInput() unknown session %d on input %d", session, input);
1533 return BAD_VALUE;
1534 }
1535
Eric Laurente552edb2014-03-10 17:42:56 -07001536 if (inputDesc->mRefCount == 0) {
1537 ALOGW("stopInput() input %d already stopped", input);
1538 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001539 }
1540
1541 inputDesc->mRefCount--;
1542 if (inputDesc->mRefCount == 0) {
1543
Eric Laurente552edb2014-03-10 17:42:56 -07001544 // automatically disable the remote submix output when input is stopped
1545 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1546 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001547 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001548 }
1549
Eric Laurent1c333e22014-05-20 10:48:17 -07001550 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001551
1552 if (activeInputsCount() == 0) {
1553 SoundTrigger::setCaptureState(false);
1554 }
Eric Laurente552edb2014-03-10 17:42:56 -07001555 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001556 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001557}
1558
Eric Laurent4dc68062014-07-28 17:26:49 -07001559void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1560 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001561{
1562 ALOGV("releaseInput() %d", input);
1563 ssize_t index = mInputs.indexOfKey(input);
1564 if (index < 0) {
1565 ALOGW("releaseInput() releasing unknown input %d", input);
1566 return;
1567 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001568 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1569 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001570
1571 index = inputDesc->mSessions.indexOf(session);
1572 if (index < 0) {
1573 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1574 return;
1575 }
1576 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001577 if (inputDesc->mOpenRefCount == 0) {
1578 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1579 return;
1580 }
1581 inputDesc->mOpenRefCount--;
1582 if (inputDesc->mOpenRefCount > 0) {
1583 ALOGV("releaseInput() exit > 0");
1584 return;
1585 }
1586
Eric Laurent05b90f82014-08-27 15:32:29 -07001587 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001588 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001589 ALOGV("releaseInput() exit");
1590}
1591
Eric Laurentd4692962014-05-05 18:13:44 -07001592void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001593 bool patchRemoved = false;
1594
Eric Laurentd4692962014-05-05 18:13:44 -07001595 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001596 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1597 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1598 if (patch_index >= 0) {
1599 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1600 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1601 mAudioPatches.removeItemsAt(patch_index);
1602 patchRemoved = true;
1603 }
Eric Laurentd4692962014-05-05 18:13:44 -07001604 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1605 }
1606 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001607 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001608
1609 if (patchRemoved) {
1610 mpClientInterface->onAudioPatchListUpdate();
1611 }
Eric Laurentd4692962014-05-05 18:13:44 -07001612}
1613
Eric Laurente0720872014-03-11 09:30:41 -07001614void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001615 int indexMin,
1616 int indexMax)
1617{
1618 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1619 if (indexMin < 0 || indexMin >= indexMax) {
1620 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1621 return;
1622 }
1623 mStreams[stream].mIndexMin = indexMin;
1624 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001625 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1626 if (stream == AUDIO_STREAM_MUSIC) {
1627 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1628 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1629 }
Eric Laurente552edb2014-03-10 17:42:56 -07001630}
1631
Eric Laurente0720872014-03-11 09:30:41 -07001632status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001633 int index,
1634 audio_devices_t device)
1635{
1636
1637 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1638 return BAD_VALUE;
1639 }
1640 if (!audio_is_output_device(device)) {
1641 return BAD_VALUE;
1642 }
1643
1644 // Force max volume if stream cannot be muted
1645 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1646
1647 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1648 stream, device, index);
1649
1650 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1651 // clear all device specific values
1652 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1653 mStreams[stream].mIndexCur.clear();
1654 }
1655 mStreams[stream].mIndexCur.add(device, index);
1656
Eric Laurent31551f82014-10-10 18:21:56 -07001657 // update volume on all outputs whose current device is also selected by the same
1658 // strategy as the device specified by the caller
1659 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001660
1661
1662 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1663 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1664 if (stream == AUDIO_STREAM_MUSIC) {
1665 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1666 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1667 }
1668 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1669 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001670 return NO_ERROR;
1671 }
Eric Laurente552edb2014-03-10 17:42:56 -07001672 status_t status = NO_ERROR;
1673 for (size_t i = 0; i < mOutputs.size(); i++) {
1674 audio_devices_t curDevice =
1675 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001676 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001677 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1678 if (volStatus != NO_ERROR) {
1679 status = volStatus;
1680 }
1681 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001682 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1683 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1684 index, mOutputs.keyAt(i), curDevice);
1685 }
Eric Laurente552edb2014-03-10 17:42:56 -07001686 }
1687 return status;
1688}
1689
Eric Laurente0720872014-03-11 09:30:41 -07001690status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001691 int *index,
1692 audio_devices_t device)
1693{
1694 if (index == NULL) {
1695 return BAD_VALUE;
1696 }
1697 if (!audio_is_output_device(device)) {
1698 return BAD_VALUE;
1699 }
1700 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1701 // the strategy the stream belongs to.
1702 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1703 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1704 }
1705 device = getDeviceForVolume(device);
1706
1707 *index = mStreams[stream].getVolumeIndex(device);
1708 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1709 return NO_ERROR;
1710}
1711
Eric Laurente0720872014-03-11 09:30:41 -07001712audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001713 const SortedVector<audio_io_handle_t>& outputs)
1714{
1715 // select one output among several suitable for global effects.
1716 // The priority is as follows:
1717 // 1: An offloaded output. If the effect ends up not being offloadable,
1718 // AudioFlinger will invalidate the track and the offloaded output
1719 // will be closed causing the effect to be moved to a PCM output.
1720 // 2: A deep buffer output
1721 // 3: the first output in the list
1722
1723 if (outputs.size() == 0) {
1724 return 0;
1725 }
1726
1727 audio_io_handle_t outputOffloaded = 0;
1728 audio_io_handle_t outputDeepBuffer = 0;
1729
1730 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001731 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001732 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001733 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1734 outputOffloaded = outputs[i];
1735 }
1736 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1737 outputDeepBuffer = outputs[i];
1738 }
1739 }
1740
1741 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1742 outputOffloaded, outputDeepBuffer);
1743 if (outputOffloaded != 0) {
1744 return outputOffloaded;
1745 }
1746 if (outputDeepBuffer != 0) {
1747 return outputDeepBuffer;
1748 }
1749
1750 return outputs[0];
1751}
1752
Eric Laurente0720872014-03-11 09:30:41 -07001753audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001754{
1755 // apply simple rule where global effects are attached to the same output as MUSIC streams
1756
Eric Laurent3b73df72014-03-11 09:06:29 -07001757 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001758 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1759 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1760
1761 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1762 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1763 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1764
1765 return output;
1766}
1767
Eric Laurente0720872014-03-11 09:30:41 -07001768status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001769 audio_io_handle_t io,
1770 uint32_t strategy,
1771 int session,
1772 int id)
1773{
1774 ssize_t index = mOutputs.indexOfKey(io);
1775 if (index < 0) {
1776 index = mInputs.indexOfKey(io);
1777 if (index < 0) {
1778 ALOGW("registerEffect() unknown io %d", io);
1779 return INVALID_OPERATION;
1780 }
1781 }
1782
1783 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1784 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1785 desc->name, desc->memoryUsage);
1786 return INVALID_OPERATION;
1787 }
1788 mTotalEffectsMemory += desc->memoryUsage;
1789 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1790 desc->name, io, strategy, session, id);
1791 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1792
Eric Laurent1f2f2232014-06-02 12:01:23 -07001793 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1794 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1795 effectDesc->mIo = io;
1796 effectDesc->mStrategy = (routing_strategy)strategy;
1797 effectDesc->mSession = session;
1798 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001799
Eric Laurent1f2f2232014-06-02 12:01:23 -07001800 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001801
1802 return NO_ERROR;
1803}
1804
Eric Laurente0720872014-03-11 09:30:41 -07001805status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001806{
1807 ssize_t index = mEffects.indexOfKey(id);
1808 if (index < 0) {
1809 ALOGW("unregisterEffect() unknown effect ID %d", id);
1810 return INVALID_OPERATION;
1811 }
1812
Eric Laurent1f2f2232014-06-02 12:01:23 -07001813 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001814
Eric Laurent1f2f2232014-06-02 12:01:23 -07001815 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001816
Eric Laurent1f2f2232014-06-02 12:01:23 -07001817 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001818 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001819 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1820 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001821 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001822 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001823 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001824 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001825
1826 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001827
1828 return NO_ERROR;
1829}
1830
Eric Laurente0720872014-03-11 09:30:41 -07001831status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001832{
1833 ssize_t index = mEffects.indexOfKey(id);
1834 if (index < 0) {
1835 ALOGW("unregisterEffect() unknown effect ID %d", id);
1836 return INVALID_OPERATION;
1837 }
1838
1839 return setEffectEnabled(mEffects.valueAt(index), enabled);
1840}
1841
Eric Laurent1f2f2232014-06-02 12:01:23 -07001842status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001843{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001844 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001845 ALOGV("setEffectEnabled(%s) effect already %s",
1846 enabled?"true":"false", enabled?"enabled":"disabled");
1847 return INVALID_OPERATION;
1848 }
1849
1850 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001851 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001852 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001853 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001854 return INVALID_OPERATION;
1855 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001856 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001857 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1858 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001859 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001860 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001861 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1862 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001863 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001864 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001865 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1866 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001867 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001868 return NO_ERROR;
1869}
1870
Eric Laurente0720872014-03-11 09:30:41 -07001871bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001872{
1873 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001874 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1875 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1876 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001877 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001878 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001879 return true;
1880 }
1881 }
1882 return false;
1883}
1884
Eric Laurente0720872014-03-11 09:30:41 -07001885bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001886{
1887 nsecs_t sysTime = systemTime();
1888 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001889 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001890 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001891 return true;
1892 }
1893 }
1894 return false;
1895}
1896
Eric Laurente0720872014-03-11 09:30:41 -07001897bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001898 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001899{
1900 nsecs_t sysTime = systemTime();
1901 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001902 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001903 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001904 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001905 return true;
1906 }
1907 }
1908 return false;
1909}
1910
Eric Laurente0720872014-03-11 09:30:41 -07001911bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001912{
1913 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001914 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001915 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001916 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001917 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1918 && (inputDescriptor->mRefCount > 0)) {
1919 return true;
1920 }
1921 }
1922 return false;
1923}
1924
1925
Eric Laurente0720872014-03-11 09:30:41 -07001926status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001927{
1928 const size_t SIZE = 256;
1929 char buffer[SIZE];
1930 String8 result;
1931
1932 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1933 result.append(buffer);
1934
1935 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1936 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001937 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1938 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001939 snprintf(buffer, SIZE, " Force use for communications %d\n",
1940 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001941 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001942 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001943 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001944 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001945 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001946 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001947 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001948 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001949 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001950 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1951 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1952 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001953
Eric Laurent3a4311c2014-03-17 12:00:47 -07001954 snprintf(buffer, SIZE, " Available output devices:\n");
1955 result.append(buffer);
1956 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001957 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001958 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001959 }
1960 snprintf(buffer, SIZE, "\n Available input devices:\n");
1961 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001962 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001963 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001964 }
Eric Laurente552edb2014-03-10 17:42:56 -07001965
1966 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1967 write(fd, buffer, strlen(buffer));
1968 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001969 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001970 write(fd, buffer, strlen(buffer));
1971 mHwModules[i]->dump(fd);
1972 }
1973
1974 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1975 write(fd, buffer, strlen(buffer));
1976 for (size_t i = 0; i < mOutputs.size(); i++) {
1977 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1978 write(fd, buffer, strlen(buffer));
1979 mOutputs.valueAt(i)->dump(fd);
1980 }
1981
1982 snprintf(buffer, SIZE, "\nInputs dump:\n");
1983 write(fd, buffer, strlen(buffer));
1984 for (size_t i = 0; i < mInputs.size(); i++) {
1985 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1986 write(fd, buffer, strlen(buffer));
1987 mInputs.valueAt(i)->dump(fd);
1988 }
1989
1990 snprintf(buffer, SIZE, "\nStreams dump:\n");
1991 write(fd, buffer, strlen(buffer));
1992 snprintf(buffer, SIZE,
1993 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1994 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001995 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001996 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001997 write(fd, buffer, strlen(buffer));
1998 mStreams[i].dump(fd);
1999 }
2000
2001 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2002 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2003 write(fd, buffer, strlen(buffer));
2004
2005 snprintf(buffer, SIZE, "Registered effects:\n");
2006 write(fd, buffer, strlen(buffer));
2007 for (size_t i = 0; i < mEffects.size(); i++) {
2008 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2009 write(fd, buffer, strlen(buffer));
2010 mEffects.valueAt(i)->dump(fd);
2011 }
2012
Eric Laurent4d416952014-08-10 14:07:09 -07002013 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2014 write(fd, buffer, strlen(buffer));
2015 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2016 mAudioPatches[i]->dump(fd, 2, i);
2017 }
Eric Laurente552edb2014-03-10 17:42:56 -07002018
2019 return NO_ERROR;
2020}
2021
2022// This function checks for the parameters which can be offloaded.
2023// This can be enhanced depending on the capability of the DSP and policy
2024// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002025bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002026{
2027 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002028 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002029 offloadInfo.sample_rate, offloadInfo.channel_mask,
2030 offloadInfo.format,
2031 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2032 offloadInfo.has_video);
2033
2034 // Check if offload has been disabled
2035 char propValue[PROPERTY_VALUE_MAX];
2036 if (property_get("audio.offload.disable", propValue, "0")) {
2037 if (atoi(propValue) != 0) {
2038 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2039 return false;
2040 }
2041 }
2042
2043 // Check if stream type is music, then only allow offload as of now.
2044 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2045 {
2046 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2047 return false;
2048 }
2049
2050 //TODO: enable audio offloading with video when ready
2051 if (offloadInfo.has_video)
2052 {
2053 ALOGV("isOffloadSupported: has_video == true, returning false");
2054 return false;
2055 }
2056
2057 //If duration is less than minimum value defined in property, return false
2058 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2059 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2060 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2061 return false;
2062 }
2063 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2064 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2065 return false;
2066 }
2067
2068 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2069 // creating an offloaded track and tearing it down immediately after start when audioflinger
2070 // detects there is an active non offloadable effect.
2071 // FIXME: We should check the audio session here but we do not have it in this context.
2072 // This may prevent offloading in rare situations where effects are left active by apps
2073 // in the background.
2074 if (isNonOffloadableEffectEnabled()) {
2075 return false;
2076 }
2077
2078 // See if there is a profile to support this.
2079 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002080 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002081 offloadInfo.sample_rate,
2082 offloadInfo.format,
2083 offloadInfo.channel_mask,
2084 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002085 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2086 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002087}
2088
Eric Laurent6a94d692014-05-20 11:18:06 -07002089status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2090 audio_port_type_t type,
2091 unsigned int *num_ports,
2092 struct audio_port *ports,
2093 unsigned int *generation)
2094{
2095 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2096 generation == NULL) {
2097 return BAD_VALUE;
2098 }
2099 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2100 if (ports == NULL) {
2101 *num_ports = 0;
2102 }
2103
2104 size_t portsWritten = 0;
2105 size_t portsMax = *num_ports;
2106 *num_ports = 0;
2107 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2108 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2109 for (size_t i = 0;
2110 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2111 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2112 }
2113 *num_ports += mAvailableOutputDevices.size();
2114 }
2115 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2116 for (size_t i = 0;
2117 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2118 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2119 }
2120 *num_ports += mAvailableInputDevices.size();
2121 }
2122 }
2123 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2124 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2125 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2126 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2127 }
2128 *num_ports += mInputs.size();
2129 }
2130 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002131 size_t numOutputs = 0;
2132 for (size_t i = 0; i < mOutputs.size(); i++) {
2133 if (!mOutputs[i]->isDuplicated()) {
2134 numOutputs++;
2135 if (portsWritten < portsMax) {
2136 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2137 }
2138 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002139 }
Eric Laurent84c70242014-06-23 08:46:27 -07002140 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002141 }
2142 }
2143 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002144 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002145 return NO_ERROR;
2146}
2147
2148status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2149{
2150 return NO_ERROR;
2151}
2152
Eric Laurent1f2f2232014-06-02 12:01:23 -07002153sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002154 audio_port_handle_t id) const
2155{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002156 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002157 for (size_t i = 0; i < mOutputs.size(); i++) {
2158 outputDesc = mOutputs.valueAt(i);
2159 if (outputDesc->mId == id) {
2160 break;
2161 }
2162 }
2163 return outputDesc;
2164}
2165
Eric Laurent1f2f2232014-06-02 12:01:23 -07002166sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002167 audio_port_handle_t id) const
2168{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002169 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002170 for (size_t i = 0; i < mInputs.size(); i++) {
2171 inputDesc = mInputs.valueAt(i);
2172 if (inputDesc->mId == id) {
2173 break;
2174 }
2175 }
2176 return inputDesc;
2177}
2178
Eric Laurent1f2f2232014-06-02 12:01:23 -07002179sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2180 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002181{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002182 sp <HwModule> module;
2183
Eric Laurent6a94d692014-05-20 11:18:06 -07002184 for (size_t i = 0; i < mHwModules.size(); i++) {
2185 if (mHwModules[i]->mHandle == 0) {
2186 continue;
2187 }
2188 if (audio_is_output_device(device)) {
2189 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2190 {
2191 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2192 return mHwModules[i];
2193 }
2194 }
2195 } else {
2196 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2197 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2198 device & ~AUDIO_DEVICE_BIT_IN) {
2199 return mHwModules[i];
2200 }
2201 }
2202 }
2203 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002204 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002205}
2206
Eric Laurent1f2f2232014-06-02 12:01:23 -07002207sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002208{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002209 sp <HwModule> module;
2210
Eric Laurent1afeecb2014-05-14 08:52:28 -07002211 for (size_t i = 0; i < mHwModules.size(); i++)
2212 {
2213 if (strcmp(mHwModules[i]->mName, name) == 0) {
2214 return mHwModules[i];
2215 }
2216 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002217 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002218}
2219
Eric Laurentc2730ba2014-07-20 15:47:07 -07002220audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2221{
2222 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2223 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2224 return devices & mAvailableOutputDevices.types();
2225}
2226
2227audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2228{
2229 audio_module_handle_t primaryHandle =
2230 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2231 audio_devices_t devices = AUDIO_DEVICE_NONE;
2232 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2233 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2234 devices |= mAvailableInputDevices[i]->mDeviceType;
2235 }
2236 }
2237 return devices;
2238}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002239
Eric Laurent6a94d692014-05-20 11:18:06 -07002240status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2241 audio_patch_handle_t *handle,
2242 uid_t uid)
2243{
2244 ALOGV("createAudioPatch()");
2245
2246 if (handle == NULL || patch == NULL) {
2247 return BAD_VALUE;
2248 }
2249 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2250
Eric Laurent874c42872014-08-08 15:13:39 -07002251 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2252 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2253 return BAD_VALUE;
2254 }
2255 // only one source per audio patch supported for now
2256 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002257 return INVALID_OPERATION;
2258 }
Eric Laurent874c42872014-08-08 15:13:39 -07002259
2260 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002261 return INVALID_OPERATION;
2262 }
Eric Laurent874c42872014-08-08 15:13:39 -07002263 for (size_t i = 0; i < patch->num_sinks; i++) {
2264 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2265 return INVALID_OPERATION;
2266 }
2267 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002268
2269 sp<AudioPatch> patchDesc;
2270 ssize_t index = mAudioPatches.indexOfKey(*handle);
2271
Eric Laurent6a94d692014-05-20 11:18:06 -07002272 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2273 patch->sources[0].role,
2274 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002275#if LOG_NDEBUG == 0
2276 for (size_t i = 0; i < patch->num_sinks; i++) {
2277 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2278 patch->sinks[i].role,
2279 patch->sinks[i].type);
2280 }
2281#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002282
2283 if (index >= 0) {
2284 patchDesc = mAudioPatches.valueAt(index);
2285 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2286 mUidCached, patchDesc->mUid, uid);
2287 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2288 return INVALID_OPERATION;
2289 }
2290 } else {
2291 *handle = 0;
2292 }
2293
2294 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002295 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002296 if (outputDesc == NULL) {
2297 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2298 return BAD_VALUE;
2299 }
Eric Laurent84c70242014-06-23 08:46:27 -07002300 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2301 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002302 if (patchDesc != 0) {
2303 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2304 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2305 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2306 return BAD_VALUE;
2307 }
2308 }
Eric Laurent874c42872014-08-08 15:13:39 -07002309 DeviceVector devices;
2310 for (size_t i = 0; i < patch->num_sinks; i++) {
2311 // Only support mix to devices connection
2312 // TODO add support for mix to mix connection
2313 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2314 ALOGV("createAudioPatch() source mix but sink is not a device");
2315 return INVALID_OPERATION;
2316 }
2317 sp<DeviceDescriptor> devDesc =
2318 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2319 if (devDesc == 0) {
2320 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2321 return BAD_VALUE;
2322 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002323
Eric Laurent874c42872014-08-08 15:13:39 -07002324 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2325 patch->sources[0].sample_rate,
2326 NULL, // updatedSamplingRate
2327 patch->sources[0].format,
2328 patch->sources[0].channel_mask,
2329 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2330 ALOGV("createAudioPatch() profile not supported for device %08x",
2331 devDesc->mDeviceType);
2332 return INVALID_OPERATION;
2333 }
2334 devices.add(devDesc);
2335 }
2336 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002337 return INVALID_OPERATION;
2338 }
Eric Laurent874c42872014-08-08 15:13:39 -07002339
Eric Laurent6a94d692014-05-20 11:18:06 -07002340 // TODO: reconfigure output format and channels here
2341 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002342 devices.types(), outputDesc->mIoHandle);
2343 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002344 index = mAudioPatches.indexOfKey(*handle);
2345 if (index >= 0) {
2346 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2347 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2348 }
2349 patchDesc = mAudioPatches.valueAt(index);
2350 patchDesc->mUid = uid;
2351 ALOGV("createAudioPatch() success");
2352 } else {
2353 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2354 return INVALID_OPERATION;
2355 }
2356 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2357 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2358 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002359 // only one sink supported when connecting an input device to a mix
2360 if (patch->num_sinks > 1) {
2361 return INVALID_OPERATION;
2362 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002363 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002364 if (inputDesc == NULL) {
2365 return BAD_VALUE;
2366 }
2367 if (patchDesc != 0) {
2368 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2369 return BAD_VALUE;
2370 }
2371 }
2372 sp<DeviceDescriptor> devDesc =
2373 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2374 if (devDesc == 0) {
2375 return BAD_VALUE;
2376 }
2377
Eric Laurent84c70242014-06-23 08:46:27 -07002378 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002379 patch->sinks[0].sample_rate,
2380 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002381 patch->sinks[0].format,
2382 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002383 // FIXME for the parameter type,
2384 // and the NONE
2385 (audio_output_flags_t)
2386 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002387 return INVALID_OPERATION;
2388 }
2389 // TODO: reconfigure output format and channels here
2390 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002391 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002392 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002393 index = mAudioPatches.indexOfKey(*handle);
2394 if (index >= 0) {
2395 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2396 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2397 }
2398 patchDesc = mAudioPatches.valueAt(index);
2399 patchDesc->mUid = uid;
2400 ALOGV("createAudioPatch() success");
2401 } else {
2402 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2403 return INVALID_OPERATION;
2404 }
2405 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2406 // device to device connection
2407 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002408 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002409 return BAD_VALUE;
2410 }
2411 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002412 sp<DeviceDescriptor> srcDeviceDesc =
2413 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002414 if (srcDeviceDesc == 0) {
2415 return BAD_VALUE;
2416 }
Eric Laurent874c42872014-08-08 15:13:39 -07002417
Eric Laurent6a94d692014-05-20 11:18:06 -07002418 //update source and sink with our own data as the data passed in the patch may
2419 // be incomplete.
2420 struct audio_patch newPatch = *patch;
2421 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002422
Eric Laurent874c42872014-08-08 15:13:39 -07002423 for (size_t i = 0; i < patch->num_sinks; i++) {
2424 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2425 ALOGV("createAudioPatch() source device but one sink is not a device");
2426 return INVALID_OPERATION;
2427 }
2428
2429 sp<DeviceDescriptor> sinkDeviceDesc =
2430 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2431 if (sinkDeviceDesc == 0) {
2432 return BAD_VALUE;
2433 }
2434 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2435
2436 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2437 // only one sink supported when connected devices across HW modules
2438 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002439 return INVALID_OPERATION;
2440 }
Eric Laurent874c42872014-08-08 15:13:39 -07002441 SortedVector<audio_io_handle_t> outputs =
2442 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2443 mOutputs);
2444 // if the sink device is reachable via an opened output stream, request to go via
2445 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002446 audio_io_handle_t output = selectOutput(outputs,
2447 AUDIO_OUTPUT_FLAG_NONE,
2448 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002449 if (output != AUDIO_IO_HANDLE_NONE) {
2450 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2451 if (outputDesc->isDuplicated()) {
2452 return INVALID_OPERATION;
2453 }
2454 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2455 newPatch.num_sources = 2;
2456 }
Eric Laurent83b88082014-06-20 18:31:16 -07002457 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002458 }
2459 // TODO: check from routing capabilities in config file and other conflicting patches
2460
2461 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2462 if (index >= 0) {
2463 afPatchHandle = patchDesc->mAfPatchHandle;
2464 }
2465
2466 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2467 &afPatchHandle,
2468 0);
2469 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2470 status, afPatchHandle);
2471 if (status == NO_ERROR) {
2472 if (index < 0) {
2473 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2474 &newPatch, uid);
2475 addAudioPatch(patchDesc->mHandle, patchDesc);
2476 } else {
2477 patchDesc->mPatch = newPatch;
2478 }
2479 patchDesc->mAfPatchHandle = afPatchHandle;
2480 *handle = patchDesc->mHandle;
2481 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002482 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002483 } else {
2484 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2485 status);
2486 return INVALID_OPERATION;
2487 }
2488 } else {
2489 return BAD_VALUE;
2490 }
2491 } else {
2492 return BAD_VALUE;
2493 }
2494 return NO_ERROR;
2495}
2496
2497status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2498 uid_t uid)
2499{
2500 ALOGV("releaseAudioPatch() patch %d", handle);
2501
2502 ssize_t index = mAudioPatches.indexOfKey(handle);
2503
2504 if (index < 0) {
2505 return BAD_VALUE;
2506 }
2507 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2508 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2509 mUidCached, patchDesc->mUid, uid);
2510 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2511 return INVALID_OPERATION;
2512 }
2513
2514 struct audio_patch *patch = &patchDesc->mPatch;
2515 patchDesc->mUid = mUidCached;
2516 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002517 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002518 if (outputDesc == NULL) {
2519 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2520 return BAD_VALUE;
2521 }
2522
2523 setOutputDevice(outputDesc->mIoHandle,
2524 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2525 true,
2526 0,
2527 NULL);
2528 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2529 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002530 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002531 if (inputDesc == NULL) {
2532 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2533 return BAD_VALUE;
2534 }
2535 setInputDevice(inputDesc->mIoHandle,
2536 getNewInputDevice(inputDesc->mIoHandle),
2537 true,
2538 NULL);
2539 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2540 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2541 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2542 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2543 status, patchDesc->mAfPatchHandle);
2544 removeAudioPatch(patchDesc->mHandle);
2545 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002546 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002547 } else {
2548 return BAD_VALUE;
2549 }
2550 } else {
2551 return BAD_VALUE;
2552 }
2553 return NO_ERROR;
2554}
2555
2556status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2557 struct audio_patch *patches,
2558 unsigned int *generation)
2559{
2560 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2561 generation == NULL) {
2562 return BAD_VALUE;
2563 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002564 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002565 *num_patches, patches, mAudioPatches.size());
2566 if (patches == NULL) {
2567 *num_patches = 0;
2568 }
2569
2570 size_t patchesWritten = 0;
2571 size_t patchesMax = *num_patches;
2572 for (size_t i = 0;
2573 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2574 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2575 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002576 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002577 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2578 }
2579 *num_patches = mAudioPatches.size();
2580
2581 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002582 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002583 return NO_ERROR;
2584}
2585
Eric Laurente1715a42014-05-20 11:30:42 -07002586status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002587{
Eric Laurente1715a42014-05-20 11:30:42 -07002588 ALOGV("setAudioPortConfig()");
2589
2590 if (config == NULL) {
2591 return BAD_VALUE;
2592 }
2593 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2594 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002595 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2596 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002597 }
2598
Eric Laurenta121f902014-06-03 13:32:54 -07002599 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002600 if (config->type == AUDIO_PORT_TYPE_MIX) {
2601 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002602 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002603 if (outputDesc == NULL) {
2604 return BAD_VALUE;
2605 }
Eric Laurent84c70242014-06-23 08:46:27 -07002606 ALOG_ASSERT(!outputDesc->isDuplicated(),
2607 "setAudioPortConfig() called on duplicated output %d",
2608 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002609 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002610 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002611 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002612 if (inputDesc == NULL) {
2613 return BAD_VALUE;
2614 }
Eric Laurenta121f902014-06-03 13:32:54 -07002615 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002616 } else {
2617 return BAD_VALUE;
2618 }
2619 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2620 sp<DeviceDescriptor> deviceDesc;
2621 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2622 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2623 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2624 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2625 } else {
2626 return BAD_VALUE;
2627 }
2628 if (deviceDesc == NULL) {
2629 return BAD_VALUE;
2630 }
Eric Laurenta121f902014-06-03 13:32:54 -07002631 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002632 } else {
2633 return BAD_VALUE;
2634 }
2635
Eric Laurenta121f902014-06-03 13:32:54 -07002636 struct audio_port_config backupConfig;
2637 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2638 if (status == NO_ERROR) {
2639 struct audio_port_config newConfig;
2640 audioPortConfig->toAudioPortConfig(&newConfig, config);
2641 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002642 }
Eric Laurenta121f902014-06-03 13:32:54 -07002643 if (status != NO_ERROR) {
2644 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002645 }
Eric Laurente1715a42014-05-20 11:30:42 -07002646
2647 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002648}
2649
2650void AudioPolicyManager::clearAudioPatches(uid_t uid)
2651{
2652 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2653 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2654 if (patchDesc->mUid == uid) {
2655 // releaseAudioPatch() removes the patch from mAudioPatches
2656 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2657 i--;
2658 }
2659 }
2660 }
2661}
2662
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002663status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2664 audio_io_handle_t *ioHandle,
2665 audio_devices_t *device)
2666{
2667 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2668 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2669 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2670
2671 mSoundTriggerSessions.add(*session, *ioHandle);
2672
2673 return NO_ERROR;
2674}
2675
2676status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2677{
2678 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2679 if (index < 0) {
2680 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2681 return BAD_VALUE;
2682 }
2683
2684 mSoundTriggerSessions.removeItem(session);
2685 return NO_ERROR;
2686}
2687
Eric Laurent6a94d692014-05-20 11:18:06 -07002688status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2689 const sp<AudioPatch>& patch)
2690{
2691 ssize_t index = mAudioPatches.indexOfKey(handle);
2692
2693 if (index >= 0) {
2694 ALOGW("addAudioPatch() patch %d already in", handle);
2695 return ALREADY_EXISTS;
2696 }
2697 mAudioPatches.add(handle, patch);
2698 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2699 "sink handle %d",
2700 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2701 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2702 return NO_ERROR;
2703}
2704
2705status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2706{
2707 ssize_t index = mAudioPatches.indexOfKey(handle);
2708
2709 if (index < 0) {
2710 ALOGW("removeAudioPatch() patch %d not in", handle);
2711 return ALREADY_EXISTS;
2712 }
2713 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2714 mAudioPatches.valueAt(index)->mAfPatchHandle);
2715 mAudioPatches.removeItemsAt(index);
2716 return NO_ERROR;
2717}
2718
Eric Laurente552edb2014-03-10 17:42:56 -07002719// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002720// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002721// ----------------------------------------------------------------------------
2722
Eric Laurent3a4311c2014-03-17 12:00:47 -07002723uint32_t AudioPolicyManager::nextUniqueId()
2724{
2725 return android_atomic_inc(&mNextUniqueId);
2726}
2727
Eric Laurent6a94d692014-05-20 11:18:06 -07002728uint32_t AudioPolicyManager::nextAudioPortGeneration()
2729{
2730 return android_atomic_inc(&mAudioPortGeneration);
2731}
2732
Eric Laurente0720872014-03-11 09:30:41 -07002733AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002734 :
2735#ifdef AUDIO_POLICY_TEST
2736 Thread(false),
2737#endif //AUDIO_POLICY_TEST
2738 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002739 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002740 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2741 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002742 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002743 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002744 mAudioPortGeneration(1),
2745 mBeaconMuteRefCount(0),
2746 mBeaconPlayingRefCount(0),
2747 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002748{
Eric Laurent6a94d692014-05-20 11:18:06 -07002749 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002750 mpClientInterface = clientInterface;
2751
Eric Laurent3b73df72014-03-11 09:06:29 -07002752 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2753 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002754 }
2755
Eric Laurent1afeecb2014-05-14 08:52:28 -07002756 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002757 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2758 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2759 ALOGE("could not load audio policy configuration file, setting defaults");
2760 defaultAudioPolicyConfig();
2761 }
2762 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002763 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002764
2765 // must be done after reading the policy
2766 initializeVolumeCurves();
2767
2768 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002769 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2770 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002771 for (size_t i = 0; i < mHwModules.size(); i++) {
2772 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2773 if (mHwModules[i]->mHandle == 0) {
2774 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2775 continue;
2776 }
2777 // open all output streams needed to access attached devices
2778 // except for direct output streams that are only opened when they are actually
2779 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002780 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002781 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2782 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002783 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002784
Eric Laurent3a4311c2014-03-17 12:00:47 -07002785 if (outProfile->mSupportedDevices.isEmpty()) {
2786 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2787 continue;
2788 }
2789
Eric Laurentd78f1532014-09-16 16:38:20 -07002790 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2791 continue;
2792 }
Eric Laurent83b88082014-06-20 18:31:16 -07002793 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2794 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2795 profileType = mDefaultOutputDevice->mDeviceType;
2796 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002797 // chose first device present in mSupportedDevices also part of
2798 // outputDeviceTypes
2799 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2800 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2801 if ((profileType & outputDeviceTypes) != 0) {
2802 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002803 }
Eric Laurente552edb2014-03-10 17:42:56 -07002804 }
2805 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002806 if ((profileType & outputDeviceTypes) == 0) {
2807 continue;
2808 }
2809 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2810
2811 outputDesc->mDevice = profileType;
2812 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2813 config.sample_rate = outputDesc->mSamplingRate;
2814 config.channel_mask = outputDesc->mChannelMask;
2815 config.format = outputDesc->mFormat;
2816 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2817 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2818 &output,
2819 &config,
2820 &outputDesc->mDevice,
2821 String8(""),
2822 &outputDesc->mLatency,
2823 outputDesc->mFlags);
2824
2825 if (status != NO_ERROR) {
2826 ALOGW("Cannot open output stream for device %08x on hw module %s",
2827 outputDesc->mDevice,
2828 mHwModules[i]->mName);
2829 } else {
2830 outputDesc->mSamplingRate = config.sample_rate;
2831 outputDesc->mChannelMask = config.channel_mask;
2832 outputDesc->mFormat = config.format;
2833
2834 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2835 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2836 ssize_t index =
2837 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2838 // give a valid ID to an attached device once confirmed it is reachable
2839 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2840 mAvailableOutputDevices[index]->mId = nextUniqueId();
2841 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2842 }
2843 }
2844 if (mPrimaryOutput == 0 &&
2845 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2846 mPrimaryOutput = output;
2847 }
2848 addOutput(output, outputDesc);
2849 setOutputDevice(output,
2850 outputDesc->mDevice,
2851 true);
2852 }
Eric Laurente552edb2014-03-10 17:42:56 -07002853 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002854 // open input streams needed to access attached devices to validate
2855 // mAvailableInputDevices list
2856 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2857 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002858 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002859
Eric Laurent3a4311c2014-03-17 12:00:47 -07002860 if (inProfile->mSupportedDevices.isEmpty()) {
2861 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2862 continue;
2863 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002864 // chose first device present in mSupportedDevices also part of
2865 // inputDeviceTypes
2866 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2867 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2868 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2869 if (profileType & inputDeviceTypes) {
2870 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002871 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002872 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002873 if ((profileType & inputDeviceTypes) == 0) {
2874 continue;
2875 }
2876 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2877
2878 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2879 inputDesc->mDevice = profileType;
2880
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002881 // find the address
2882 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
2883 // the inputs vector must be of size 1, but we don't want to crash here
2884 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
2885 : String8("");
2886 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
2887 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
2888
Eric Laurentd78f1532014-09-16 16:38:20 -07002889 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2890 config.sample_rate = inputDesc->mSamplingRate;
2891 config.channel_mask = inputDesc->mChannelMask;
2892 config.format = inputDesc->mFormat;
2893 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2894 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2895 &input,
2896 &config,
2897 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002898 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07002899 AUDIO_SOURCE_MIC,
2900 AUDIO_INPUT_FLAG_NONE);
2901
2902 if (status == NO_ERROR) {
2903 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2904 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2905 ssize_t index =
2906 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2907 // give a valid ID to an attached device once confirmed it is reachable
2908 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2909 mAvailableInputDevices[index]->mId = nextUniqueId();
2910 mAvailableInputDevices[index]->mModule = mHwModules[i];
2911 }
2912 }
2913 mpClientInterface->closeInput(input);
2914 } else {
2915 ALOGW("Cannot open input stream for device %08x on hw module %s",
2916 inputDesc->mDevice,
2917 mHwModules[i]->mName);
2918 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002919 }
2920 }
2921 // make sure all attached devices have been allocated a unique ID
2922 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2923 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002924 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002925 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2926 continue;
2927 }
2928 i++;
2929 }
2930 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2931 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002932 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002933 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2934 continue;
2935 }
2936 i++;
2937 }
2938 // make sure default device is reachable
2939 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002940 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002941 }
Eric Laurente552edb2014-03-10 17:42:56 -07002942
2943 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2944
2945 updateDevicesAndOutputs();
2946
2947#ifdef AUDIO_POLICY_TEST
2948 if (mPrimaryOutput != 0) {
2949 AudioParameter outputCmd = AudioParameter();
2950 outputCmd.addInt(String8("set_id"), 0);
2951 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2952
2953 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2954 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002955 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2956 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002957 mTestLatencyMs = 0;
2958 mCurOutput = 0;
2959 mDirectOutput = false;
2960 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2961 mTestOutputs[i] = 0;
2962 }
2963
2964 const size_t SIZE = 256;
2965 char buffer[SIZE];
2966 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2967 run(buffer, ANDROID_PRIORITY_AUDIO);
2968 }
2969#endif //AUDIO_POLICY_TEST
2970}
2971
Eric Laurente0720872014-03-11 09:30:41 -07002972AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002973{
2974#ifdef AUDIO_POLICY_TEST
2975 exit();
2976#endif //AUDIO_POLICY_TEST
2977 for (size_t i = 0; i < mOutputs.size(); i++) {
2978 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002979 }
2980 for (size_t i = 0; i < mInputs.size(); i++) {
2981 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002982 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002983 mAvailableOutputDevices.clear();
2984 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002985 mOutputs.clear();
2986 mInputs.clear();
2987 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002988}
2989
Eric Laurente0720872014-03-11 09:30:41 -07002990status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002991{
2992 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2993}
2994
2995#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002996bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002997{
2998 ALOGV("entering threadLoop()");
2999 while (!exitPending())
3000 {
3001 String8 command;
3002 int valueInt;
3003 String8 value;
3004
3005 Mutex::Autolock _l(mLock);
3006 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3007
3008 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3009 AudioParameter param = AudioParameter(command);
3010
3011 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3012 valueInt != 0) {
3013 ALOGV("Test command %s received", command.string());
3014 String8 target;
3015 if (param.get(String8("target"), target) != NO_ERROR) {
3016 target = "Manager";
3017 }
3018 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3019 param.remove(String8("test_cmd_policy_output"));
3020 mCurOutput = valueInt;
3021 }
3022 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3023 param.remove(String8("test_cmd_policy_direct"));
3024 if (value == "false") {
3025 mDirectOutput = false;
3026 } else if (value == "true") {
3027 mDirectOutput = true;
3028 }
3029 }
3030 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3031 param.remove(String8("test_cmd_policy_input"));
3032 mTestInput = valueInt;
3033 }
3034
3035 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3036 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003037 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003038 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003039 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003040 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003041 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003042 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003043 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003044 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003045 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003046 if (target == "Manager") {
3047 mTestFormat = format;
3048 } else if (mTestOutputs[mCurOutput] != 0) {
3049 AudioParameter outputParam = AudioParameter();
3050 outputParam.addInt(String8("format"), format);
3051 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3052 }
3053 }
3054 }
3055 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3056 param.remove(String8("test_cmd_policy_channels"));
3057 int channels = 0;
3058
3059 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003060 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003061 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003062 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003063 }
3064 if (channels != 0) {
3065 if (target == "Manager") {
3066 mTestChannels = channels;
3067 } else if (mTestOutputs[mCurOutput] != 0) {
3068 AudioParameter outputParam = AudioParameter();
3069 outputParam.addInt(String8("channels"), channels);
3070 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3071 }
3072 }
3073 }
3074 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3075 param.remove(String8("test_cmd_policy_sampleRate"));
3076 if (valueInt >= 0 && valueInt <= 96000) {
3077 int samplingRate = valueInt;
3078 if (target == "Manager") {
3079 mTestSamplingRate = samplingRate;
3080 } else if (mTestOutputs[mCurOutput] != 0) {
3081 AudioParameter outputParam = AudioParameter();
3082 outputParam.addInt(String8("sampling_rate"), samplingRate);
3083 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3084 }
3085 }
3086 }
3087
3088 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3089 param.remove(String8("test_cmd_policy_reopen"));
3090
Eric Laurent1f2f2232014-06-02 12:01:23 -07003091 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003092 mpClientInterface->closeOutput(mPrimaryOutput);
3093
3094 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3095
Eric Laurente552edb2014-03-10 17:42:56 -07003096 mOutputs.removeItem(mPrimaryOutput);
3097
Eric Laurent1f2f2232014-06-02 12:01:23 -07003098 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003099 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003100 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3101 config.sample_rate = outputDesc->mSamplingRate;
3102 config.channel_mask = outputDesc->mChannelMask;
3103 config.format = outputDesc->mFormat;
3104 status_t status = mpClientInterface->openOutput(moduleHandle,
3105 &mPrimaryOutput,
3106 &config,
3107 &outputDesc->mDevice,
3108 String8(""),
3109 &outputDesc->mLatency,
3110 outputDesc->mFlags);
3111 if (status != NO_ERROR) {
3112 ALOGE("Failed to reopen hardware output stream, "
3113 "samplingRate: %d, format %d, channels %d",
3114 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003115 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003116 outputDesc->mSamplingRate = config.sample_rate;
3117 outputDesc->mChannelMask = config.channel_mask;
3118 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003119 AudioParameter outputCmd = AudioParameter();
3120 outputCmd.addInt(String8("set_id"), 0);
3121 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3122 addOutput(mPrimaryOutput, outputDesc);
3123 }
3124 }
3125
3126
3127 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3128 }
3129 }
3130 return false;
3131}
3132
Eric Laurente0720872014-03-11 09:30:41 -07003133void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003134{
3135 {
3136 AutoMutex _l(mLock);
3137 requestExit();
3138 mWaitWorkCV.signal();
3139 }
3140 requestExitAndWait();
3141}
3142
Eric Laurente0720872014-03-11 09:30:41 -07003143int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003144{
3145 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3146 if (output == mTestOutputs[i]) return i;
3147 }
3148 return 0;
3149}
3150#endif //AUDIO_POLICY_TEST
3151
3152// ---
3153
Eric Laurent1f2f2232014-06-02 12:01:23 -07003154void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003155{
Eric Laurent1c333e22014-05-20 10:48:17 -07003156 outputDesc->mIoHandle = output;
3157 outputDesc->mId = nextUniqueId();
3158 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003159 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003160}
3161
Eric Laurent1f2f2232014-06-02 12:01:23 -07003162void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003163{
Eric Laurent1c333e22014-05-20 10:48:17 -07003164 inputDesc->mIoHandle = input;
3165 inputDesc->mId = nextUniqueId();
3166 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003167 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003168}
Eric Laurente552edb2014-03-10 17:42:56 -07003169
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003170void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3171 const String8 address /*in*/,
3172 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3173 // look for a match on the given address on the addresses of the outputs:
3174 // find the address by finding the patch that maps to this output
3175 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3176 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3177 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3178 if (patchIdx >= 0) {
3179 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3180 const int numSinks = patchDesc->mPatch.num_sinks;
3181 for (ssize_t j=0; j < numSinks; j++) {
3182 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3183 const char* patchAddr =
3184 patchDesc->mPatch.sinks[j].ext.device.address;
3185 if (strncmp(patchAddr,
3186 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003187 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003188 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3189 outputs.add(desc->mIoHandle);
3190 break;
3191 }
3192 }
3193 }
3194 }
3195}
3196
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003197status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003198 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003199 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003200 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003201{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003202 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003203 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003204 // erase all current sample rates, formats and channel masks
3205 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003206
Eric Laurent3b73df72014-03-11 09:06:29 -07003207 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003208 // first list already open outputs that can be routed to this device
3209 for (size_t i = 0; i < mOutputs.size(); i++) {
3210 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003211 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003212 if (!deviceDistinguishesOnAddress(device)) {
3213 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3214 outputs.add(mOutputs.keyAt(i));
3215 } else {
3216 ALOGV(" checking address match due to device 0x%x", device);
3217 findIoHandlesByAddress(desc, address, outputs);
3218 }
Eric Laurente552edb2014-03-10 17:42:56 -07003219 }
3220 }
3221 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003222 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003223 for (size_t i = 0; i < mHwModules.size(); i++)
3224 {
3225 if (mHwModules[i]->mHandle == 0) {
3226 continue;
3227 }
3228 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3229 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003230 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003231 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003232 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3233 }
3234 }
3235 }
3236
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003237 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3238
Eric Laurente552edb2014-03-10 17:42:56 -07003239 if (profiles.isEmpty() && outputs.isEmpty()) {
3240 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3241 return BAD_VALUE;
3242 }
3243
3244 // open outputs for matching profiles if needed. Direct outputs are also opened to
3245 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3246 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003247 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003248
3249 // nothing to do if one output is already opened for this profile
3250 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003251 for (j = 0; j < outputs.size(); j++) {
3252 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003253 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003254 // matching profile: save the sample rates, format and channel masks supported
3255 // by the profile in our device descriptor
3256 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003257 break;
3258 }
3259 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003260 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003261 continue;
3262 }
3263
Eric Laurent83b88082014-06-20 18:31:16 -07003264 ALOGV("opening output for device %08x with params %s profile %p",
3265 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003266 desc = new AudioOutputDescriptor(profile);
3267 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003268 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3269 config.sample_rate = desc->mSamplingRate;
3270 config.channel_mask = desc->mChannelMask;
3271 config.format = desc->mFormat;
3272 config.offload_info.sample_rate = desc->mSamplingRate;
3273 config.offload_info.channel_mask = desc->mChannelMask;
3274 config.offload_info.format = desc->mFormat;
3275 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3276 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3277 &output,
3278 &config,
3279 &desc->mDevice,
3280 address,
3281 &desc->mLatency,
3282 desc->mFlags);
3283 if (status == NO_ERROR) {
3284 desc->mSamplingRate = config.sample_rate;
3285 desc->mChannelMask = config.channel_mask;
3286 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003287
Eric Laurentd4692962014-05-05 18:13:44 -07003288 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003289 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003290 char *param = audio_device_address_to_parameter(device, address);
3291 mpClientInterface->setParameters(output, String8(param));
3292 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003293 }
3294
Eric Laurentd4692962014-05-05 18:13:44 -07003295 // Here is where we step through and resolve any "dynamic" fields
3296 String8 reply;
3297 char *value;
3298 if (profile->mSamplingRates[0] == 0) {
3299 reply = mpClientInterface->getParameters(output,
3300 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003301 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003302 reply.string());
3303 value = strpbrk((char *)reply.string(), "=");
3304 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003305 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003306 }
Eric Laurentd4692962014-05-05 18:13:44 -07003307 }
3308 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3309 reply = mpClientInterface->getParameters(output,
3310 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003311 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003312 reply.string());
3313 value = strpbrk((char *)reply.string(), "=");
3314 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003315 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003316 }
Eric Laurentd4692962014-05-05 18:13:44 -07003317 }
3318 if (profile->mChannelMasks[0] == 0) {
3319 reply = mpClientInterface->getParameters(output,
3320 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003321 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003322 reply.string());
3323 value = strpbrk((char *)reply.string(), "=");
3324 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003325 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003326 }
Eric Laurentd4692962014-05-05 18:13:44 -07003327 }
3328 if (((profile->mSamplingRates[0] == 0) &&
3329 (profile->mSamplingRates.size() < 2)) ||
3330 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3331 (profile->mFormats.size() < 2)) ||
3332 ((profile->mChannelMasks[0] == 0) &&
3333 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003334 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003335 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003336 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003337 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3338 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003339 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003340 config.sample_rate = profile->pickSamplingRate();
3341 config.channel_mask = profile->pickChannelMask();
3342 config.format = profile->pickFormat();
3343 config.offload_info.sample_rate = config.sample_rate;
3344 config.offload_info.channel_mask = config.channel_mask;
3345 config.offload_info.format = config.format;
3346 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3347 &output,
3348 &config,
3349 &desc->mDevice,
3350 address,
3351 &desc->mLatency,
3352 desc->mFlags);
3353 if (status == NO_ERROR) {
3354 desc->mSamplingRate = config.sample_rate;
3355 desc->mChannelMask = config.channel_mask;
3356 desc->mFormat = config.format;
3357 } else {
3358 output = AUDIO_IO_HANDLE_NONE;
3359 }
Eric Laurentd4692962014-05-05 18:13:44 -07003360 }
3361
Eric Laurentcf2c0212014-07-25 16:20:43 -07003362 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003363 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003364 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003365 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003366
Eric Laurentd4692962014-05-05 18:13:44 -07003367 // set initial stream volume for device
3368 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003369
Eric Laurentd4692962014-05-05 18:13:44 -07003370 //TODO: configure audio effect output stage here
3371
3372 // open a duplicating output thread for the new output and the primary output
3373 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3374 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003375 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003376 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003377 sp<AudioOutputDescriptor> dupOutputDesc =
3378 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003379 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3380 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3381 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3382 dupOutputDesc->mFormat = desc->mFormat;
3383 dupOutputDesc->mChannelMask = desc->mChannelMask;
3384 dupOutputDesc->mLatency = desc->mLatency;
3385 addOutput(duplicatedOutput, dupOutputDesc);
3386 applyStreamVolumes(duplicatedOutput, device, 0, true);
3387 } else {
3388 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3389 mPrimaryOutput, output);
3390 mpClientInterface->closeOutput(output);
3391 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003392 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003393 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003394 }
Eric Laurente552edb2014-03-10 17:42:56 -07003395 }
3396 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003397 } else {
3398 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003399 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003400 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003401 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003402 profiles.removeAt(profile_index);
3403 profile_index--;
3404 } else {
3405 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003406 devDesc->importAudioPort(profile);
3407
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003408 if (deviceDistinguishesOnAddress(device)) {
3409 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3410 device, address.string());
3411 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3412 NULL/*patch handle*/, address.string());
3413 }
Eric Laurente552edb2014-03-10 17:42:56 -07003414 ALOGV("checkOutputsForDevice(): adding output %d", output);
3415 }
3416 }
3417
3418 if (profiles.isEmpty()) {
3419 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3420 return BAD_VALUE;
3421 }
Eric Laurentd4692962014-05-05 18:13:44 -07003422 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003423 // check if one opened output is not needed any more after disconnecting one device
3424 for (size_t i = 0; i < mOutputs.size(); i++) {
3425 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003426 if (!desc->isDuplicated()) {
3427 if (!(desc->mProfile->mSupportedDevices.types()
3428 & mAvailableOutputDevices.types())) {
3429 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3430 mOutputs.keyAt(i));
3431 outputs.add(mOutputs.keyAt(i));
3432 } else if (deviceDistinguishesOnAddress(device) &&
3433 // exact match on device
3434 (desc->mProfile->mSupportedDevices.types() == device)) {
3435 findIoHandlesByAddress(desc, address, outputs);
3436 }
Eric Laurente552edb2014-03-10 17:42:56 -07003437 }
3438 }
Eric Laurentd4692962014-05-05 18:13:44 -07003439 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003440 for (size_t i = 0; i < mHwModules.size(); i++)
3441 {
3442 if (mHwModules[i]->mHandle == 0) {
3443 continue;
3444 }
3445 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3446 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003447 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003448 if (profile->mSupportedDevices.types() & device) {
3449 ALOGV("checkOutputsForDevice(): "
3450 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003451 if (profile->mSamplingRates[0] == 0) {
3452 profile->mSamplingRates.clear();
3453 profile->mSamplingRates.add(0);
3454 }
3455 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3456 profile->mFormats.clear();
3457 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3458 }
3459 if (profile->mChannelMasks[0] == 0) {
3460 profile->mChannelMasks.clear();
3461 profile->mChannelMasks.add(0);
3462 }
3463 }
3464 }
3465 }
3466 }
3467 return NO_ERROR;
3468}
3469
Eric Laurentd4692962014-05-05 18:13:44 -07003470status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3471 audio_policy_dev_state_t state,
3472 SortedVector<audio_io_handle_t>& inputs,
3473 const String8 address)
3474{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003475 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003476 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3477 // first list already open inputs that can be routed to this device
3478 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3479 desc = mInputs.valueAt(input_index);
3480 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3481 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3482 inputs.add(mInputs.keyAt(input_index));
3483 }
3484 }
3485
3486 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003487 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003488 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3489 {
3490 if (mHwModules[module_idx]->mHandle == 0) {
3491 continue;
3492 }
3493 for (size_t profile_index = 0;
3494 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3495 profile_index++)
3496 {
3497 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3498 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003499 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003500 profile_index, module_idx);
3501 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3502 }
3503 }
3504 }
3505
3506 if (profiles.isEmpty() && inputs.isEmpty()) {
3507 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3508 return BAD_VALUE;
3509 }
3510
3511 // open inputs for matching profiles if needed. Direct inputs are also opened to
3512 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3513 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3514
Eric Laurent1c333e22014-05-20 10:48:17 -07003515 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003516 // nothing to do if one input is already opened for this profile
3517 size_t input_index;
3518 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3519 desc = mInputs.valueAt(input_index);
3520 if (desc->mProfile == profile) {
3521 break;
3522 }
3523 }
3524 if (input_index != mInputs.size()) {
3525 continue;
3526 }
3527
3528 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3529 desc = new AudioInputDescriptor(profile);
3530 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003531 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3532 config.sample_rate = desc->mSamplingRate;
3533 config.channel_mask = desc->mChannelMask;
3534 config.format = desc->mFormat;
3535 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3536 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3537 &input,
3538 &config,
3539 &desc->mDevice,
3540 address,
3541 AUDIO_SOURCE_MIC,
3542 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003543
Eric Laurentcf2c0212014-07-25 16:20:43 -07003544 if (status == NO_ERROR) {
3545 desc->mSamplingRate = config.sample_rate;
3546 desc->mChannelMask = config.channel_mask;
3547 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003548
Eric Laurentd4692962014-05-05 18:13:44 -07003549 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003550 char *param = audio_device_address_to_parameter(device, address);
3551 mpClientInterface->setParameters(input, String8(param));
3552 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003553 }
3554
3555 // Here is where we step through and resolve any "dynamic" fields
3556 String8 reply;
3557 char *value;
3558 if (profile->mSamplingRates[0] == 0) {
3559 reply = mpClientInterface->getParameters(input,
3560 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3561 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3562 reply.string());
3563 value = strpbrk((char *)reply.string(), "=");
3564 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003565 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003566 }
3567 }
3568 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3569 reply = mpClientInterface->getParameters(input,
3570 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3571 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3572 value = strpbrk((char *)reply.string(), "=");
3573 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003574 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003575 }
3576 }
3577 if (profile->mChannelMasks[0] == 0) {
3578 reply = mpClientInterface->getParameters(input,
3579 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3580 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3581 reply.string());
3582 value = strpbrk((char *)reply.string(), "=");
3583 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003584 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003585 }
3586 }
3587 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3588 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3589 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3590 ALOGW("checkInputsForDevice() direct input missing param");
3591 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003592 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003593 }
3594
3595 if (input != 0) {
3596 addInput(input, desc);
3597 }
3598 } // endif input != 0
3599
Eric Laurentcf2c0212014-07-25 16:20:43 -07003600 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003601 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003602 profiles.removeAt(profile_index);
3603 profile_index--;
3604 } else {
3605 inputs.add(input);
3606 ALOGV("checkInputsForDevice(): adding input %d", input);
3607 }
3608 } // end scan profiles
3609
3610 if (profiles.isEmpty()) {
3611 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3612 return BAD_VALUE;
3613 }
3614 } else {
3615 // Disconnect
3616 // check if one opened input is not needed any more after disconnecting one device
3617 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3618 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003619 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3620 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003621 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3622 mInputs.keyAt(input_index));
3623 inputs.add(mInputs.keyAt(input_index));
3624 }
3625 }
3626 // Clear any profiles associated with the disconnected device.
3627 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3628 if (mHwModules[module_index]->mHandle == 0) {
3629 continue;
3630 }
3631 for (size_t profile_index = 0;
3632 profile_index < mHwModules[module_index]->mInputProfiles.size();
3633 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003634 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003635 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003636 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003637 profile_index, module_index);
3638 if (profile->mSamplingRates[0] == 0) {
3639 profile->mSamplingRates.clear();
3640 profile->mSamplingRates.add(0);
3641 }
3642 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3643 profile->mFormats.clear();
3644 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3645 }
3646 if (profile->mChannelMasks[0] == 0) {
3647 profile->mChannelMasks.clear();
3648 profile->mChannelMasks.add(0);
3649 }
3650 }
3651 }
3652 }
3653 } // end disconnect
3654
3655 return NO_ERROR;
3656}
3657
3658
Eric Laurente0720872014-03-11 09:30:41 -07003659void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003660{
3661 ALOGV("closeOutput(%d)", output);
3662
Eric Laurent1f2f2232014-06-02 12:01:23 -07003663 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003664 if (outputDesc == NULL) {
3665 ALOGW("closeOutput() unknown output %d", output);
3666 return;
3667 }
3668
3669 // look for duplicated outputs connected to the output being removed.
3670 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003671 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003672 if (dupOutputDesc->isDuplicated() &&
3673 (dupOutputDesc->mOutput1 == outputDesc ||
3674 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003675 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003676 if (dupOutputDesc->mOutput1 == outputDesc) {
3677 outputDesc2 = dupOutputDesc->mOutput2;
3678 } else {
3679 outputDesc2 = dupOutputDesc->mOutput1;
3680 }
3681 // As all active tracks on duplicated output will be deleted,
3682 // and as they were also referenced on the other output, the reference
3683 // count for their stream type must be adjusted accordingly on
3684 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003685 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003686 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003687 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003688 }
3689 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3690 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3691
3692 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003693 mOutputs.removeItem(duplicatedOutput);
3694 }
3695 }
3696
Eric Laurent05b90f82014-08-27 15:32:29 -07003697 nextAudioPortGeneration();
3698
3699 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3700 if (index >= 0) {
3701 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3702 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3703 mAudioPatches.removeItemsAt(index);
3704 mpClientInterface->onAudioPatchListUpdate();
3705 }
3706
Eric Laurente552edb2014-03-10 17:42:56 -07003707 AudioParameter param;
3708 param.add(String8("closing"), String8("true"));
3709 mpClientInterface->setParameters(output, param.toString());
3710
3711 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003712 mOutputs.removeItem(output);
3713 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003714}
3715
3716void AudioPolicyManager::closeInput(audio_io_handle_t input)
3717{
3718 ALOGV("closeInput(%d)", input);
3719
3720 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3721 if (inputDesc == NULL) {
3722 ALOGW("closeInput() unknown input %d", input);
3723 return;
3724 }
3725
Eric Laurent6a94d692014-05-20 11:18:06 -07003726 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003727
3728 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3729 if (index >= 0) {
3730 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3731 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3732 mAudioPatches.removeItemsAt(index);
3733 mpClientInterface->onAudioPatchListUpdate();
3734 }
3735
3736 mpClientInterface->closeInput(input);
3737 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003738}
3739
Eric Laurente0720872014-03-11 09:30:41 -07003740SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003741 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003742{
3743 SortedVector<audio_io_handle_t> outputs;
3744
3745 ALOGVV("getOutputsForDevice() device %04x", device);
3746 for (size_t i = 0; i < openOutputs.size(); i++) {
3747 ALOGVV("output %d isDuplicated=%d device=%04x",
3748 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3749 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3750 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3751 outputs.add(openOutputs.keyAt(i));
3752 }
3753 }
3754 return outputs;
3755}
3756
Eric Laurente0720872014-03-11 09:30:41 -07003757bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003758 SortedVector<audio_io_handle_t>& outputs2)
3759{
3760 if (outputs1.size() != outputs2.size()) {
3761 return false;
3762 }
3763 for (size_t i = 0; i < outputs1.size(); i++) {
3764 if (outputs1[i] != outputs2[i]) {
3765 return false;
3766 }
3767 }
3768 return true;
3769}
3770
Eric Laurente0720872014-03-11 09:30:41 -07003771void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003772{
3773 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3774 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3775 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3776 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3777
3778 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3779 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3780 strategy, srcOutputs[0], dstOutputs[0]);
3781 // mute strategy while moving tracks from one output to another
3782 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003783 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003784 if (desc->isStrategyActive(strategy)) {
3785 setStrategyMute(strategy, true, srcOutputs[i]);
3786 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3787 }
3788 }
3789
3790 // Move effects associated to this strategy from previous output to new output
3791 if (strategy == STRATEGY_MEDIA) {
3792 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3793 SortedVector<audio_io_handle_t> moved;
3794 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003795 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3796 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3797 effectDesc->mIo != fxOutput) {
3798 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003799 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3800 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003801 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003802 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003803 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003804 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003805 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003806 }
3807 }
3808 }
3809 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003810 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08003811 if (i == AUDIO_STREAM_PATCH) {
3812 continue;
3813 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003814 if (getStrategy((audio_stream_type_t)i) == strategy) {
3815 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003816 }
3817 }
3818 }
3819}
3820
Eric Laurente0720872014-03-11 09:30:41 -07003821void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003822{
Jon Eklund966095e2014-09-09 15:39:49 -05003823 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3824 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003825 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003826 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3827 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003828 checkOutputForStrategy(STRATEGY_SONIFICATION);
3829 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003830 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07003831 checkOutputForStrategy(STRATEGY_MEDIA);
3832 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003833 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07003834}
3835
Eric Laurente0720872014-03-11 09:30:41 -07003836audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003837{
Eric Laurente552edb2014-03-10 17:42:56 -07003838 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003839 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003840 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3841 return mOutputs.keyAt(i);
3842 }
3843 }
3844
3845 return 0;
3846}
3847
Eric Laurente0720872014-03-11 09:30:41 -07003848void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003849{
Eric Laurente552edb2014-03-10 17:42:56 -07003850 audio_io_handle_t a2dpOutput = getA2dpOutput();
3851 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003852 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003853 return;
3854 }
3855
Eric Laurent3a4311c2014-03-17 12:00:47 -07003856 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08003857 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
3858 ~AUDIO_DEVICE_BIT_IN) != 0) ||
3859 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003860 // suspend A2DP output if:
3861 // (NOT already suspended) &&
3862 // ((SCO device is connected &&
3863 // (forced usage for communication || for record is SCO))) ||
3864 // (phone state is ringing || in call)
3865 //
3866 // restore A2DP output if:
3867 // (Already suspended) &&
3868 // ((SCO device is NOT connected ||
3869 // (forced usage NOT for communication && NOT for record is SCO))) &&
3870 // (phone state is NOT ringing && NOT in call)
3871 //
3872 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003873 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003874 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3875 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3876 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3877 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003878
3879 mpClientInterface->restoreOutput(a2dpOutput);
3880 mA2dpSuspended = false;
3881 }
3882 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003883 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003884 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3885 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3886 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3887 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003888
3889 mpClientInterface->suspendOutput(a2dpOutput);
3890 mA2dpSuspended = true;
3891 }
3892 }
3893}
3894
Eric Laurent1c333e22014-05-20 10:48:17 -07003895audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003896{
3897 audio_devices_t device = AUDIO_DEVICE_NONE;
3898
Eric Laurent1f2f2232014-06-02 12:01:23 -07003899 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003900
3901 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3902 if (index >= 0) {
3903 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3904 if (patchDesc->mUid != mUidCached) {
3905 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3906 outputDesc->device(), outputDesc->mPatchHandle);
3907 return outputDesc->device();
3908 }
3909 }
3910
Eric Laurente552edb2014-03-10 17:42:56 -07003911 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003912 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003913 // use device for strategy enforced audible
3914 // 2: we are in call or the strategy phone is active on the output:
3915 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003916 // 3: the strategy for enforced audible is active but not enforced on the output:
3917 // use the device for strategy enforced audible
3918 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003919 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003920 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003921 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08003922 // 6: the strategy accessibility is active on the output:
3923 // use device for strategy accessibility
3924 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003925 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08003926 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003927 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08003928 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003929 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05003930 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3931 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003932 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3933 } else if (isInCall() ||
3934 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3935 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003936 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3937 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003938 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3939 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3940 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3941 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003942 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
3943 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003944 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3945 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3946 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3947 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003948 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
3949 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003950 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
3951 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003952 }
3953
Eric Laurent1c333e22014-05-20 10:48:17 -07003954 ALOGV("getNewOutputDevice() selected device %x", device);
3955 return device;
3956}
3957
3958audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3959{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003960 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003961
3962 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3963 if (index >= 0) {
3964 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3965 if (patchDesc->mUid != mUidCached) {
3966 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3967 inputDesc->mDevice, inputDesc->mPatchHandle);
3968 return inputDesc->mDevice;
3969 }
3970 }
3971
Eric Laurent1c333e22014-05-20 10:48:17 -07003972 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3973
3974 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003975 return device;
3976}
3977
Eric Laurente0720872014-03-11 09:30:41 -07003978uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003979 return (uint32_t)getStrategy(stream);
3980}
3981
Eric Laurente0720872014-03-11 09:30:41 -07003982audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003983 // By checking the range of stream before calling getStrategy, we avoid
3984 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3985 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08003986 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003987 return AUDIO_DEVICE_NONE;
3988 }
3989 audio_devices_t devices;
3990 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3991 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3992 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3993 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003994 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003995 if (outputDesc->isStrategyActive(strategy)) {
3996 devices = outputDesc->device();
3997 break;
3998 }
Eric Laurente552edb2014-03-10 17:42:56 -07003999 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004000
4001 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4002 and doesn't really need to.*/
4003 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4004 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4005 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4006 }
4007
Eric Laurente552edb2014-03-10 17:42:56 -07004008 return devices;
4009}
4010
Eric Laurente0720872014-03-11 09:30:41 -07004011AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004012 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004013
4014 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4015
Eric Laurente552edb2014-03-10 17:42:56 -07004016 // stream to strategy mapping
4017 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004018 case AUDIO_STREAM_VOICE_CALL:
4019 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004020 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004021 case AUDIO_STREAM_RING:
4022 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004023 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004024 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004025 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004026 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004027 return STRATEGY_DTMF;
4028 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004029 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004030 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004031 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4032 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004033 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004034 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004035 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004036 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004037 case AUDIO_STREAM_TTS:
4038 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004039 case AUDIO_STREAM_ACCESSIBILITY:
4040 return STRATEGY_ACCESSIBILITY;
4041 case AUDIO_STREAM_REROUTING:
4042 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004043 }
4044}
4045
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004046uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4047 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004048 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4049 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4050 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004051 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4052 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4053 }
4054
4055 // usage to strategy mapping
4056 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004057 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4058 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4059 return (uint32_t) STRATEGY_SONIFICATION;
4060 }
4061 if (isInCall()) {
4062 return (uint32_t) STRATEGY_PHONE;
4063 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004064 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004065
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004066 case AUDIO_USAGE_MEDIA:
4067 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004068 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4069 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4070 return (uint32_t) STRATEGY_MEDIA;
4071
4072 case AUDIO_USAGE_VOICE_COMMUNICATION:
4073 return (uint32_t) STRATEGY_PHONE;
4074
4075 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4076 return (uint32_t) STRATEGY_DTMF;
4077
4078 case AUDIO_USAGE_ALARM:
4079 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4080 return (uint32_t) STRATEGY_SONIFICATION;
4081
4082 case AUDIO_USAGE_NOTIFICATION:
4083 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4084 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4085 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4086 case AUDIO_USAGE_NOTIFICATION_EVENT:
4087 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4088
4089 case AUDIO_USAGE_UNKNOWN:
4090 default:
4091 return (uint32_t) STRATEGY_MEDIA;
4092 }
4093}
4094
Eric Laurente0720872014-03-11 09:30:41 -07004095void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004096 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004097 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004098 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4099 updateDevicesAndOutputs();
4100 break;
4101 default:
4102 break;
4103 }
4104}
4105
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004106bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4107 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4108 if (s == (size_t) streamToIgnore) {
4109 continue;
4110 }
4111 for (size_t i = 0; i < mOutputs.size(); i++) {
4112 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4113 if (outputDesc->mRefCount[s] != 0) {
4114 return true;
4115 }
4116 }
4117 }
4118 return false;
4119}
4120
4121uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4122 switch(event) {
4123 case STARTING_OUTPUT:
4124 mBeaconMuteRefCount++;
4125 break;
4126 case STOPPING_OUTPUT:
4127 if (mBeaconMuteRefCount > 0) {
4128 mBeaconMuteRefCount--;
4129 }
4130 break;
4131 case STARTING_BEACON:
4132 mBeaconPlayingRefCount++;
4133 break;
4134 case STOPPING_BEACON:
4135 if (mBeaconPlayingRefCount > 0) {
4136 mBeaconPlayingRefCount--;
4137 }
4138 break;
4139 }
4140
4141 if (mBeaconMuteRefCount > 0) {
4142 // any playback causes beacon to be muted
4143 return setBeaconMute(true);
4144 } else {
4145 // no other playback: unmute when beacon starts playing, mute when it stops
4146 return setBeaconMute(mBeaconPlayingRefCount == 0);
4147 }
4148}
4149
4150uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4151 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4152 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4153 // keep track of muted state to avoid repeating mute/unmute operations
4154 if (mBeaconMuted != mute) {
4155 // mute/unmute AUDIO_STREAM_TTS on all outputs
4156 ALOGV("\t muting %d", mute);
4157 uint32_t maxLatency = 0;
4158 for (size_t i = 0; i < mOutputs.size(); i++) {
4159 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4160 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4161 desc->mIoHandle,
4162 0 /*delay*/, AUDIO_DEVICE_NONE);
4163 const uint32_t latency = desc->latency() * 2;
4164 if (latency > maxLatency) {
4165 maxLatency = latency;
4166 }
4167 }
4168 mBeaconMuted = mute;
4169 return maxLatency;
4170 }
4171 return 0;
4172}
4173
Eric Laurente0720872014-03-11 09:30:41 -07004174audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004175 bool fromCache)
4176{
4177 uint32_t device = AUDIO_DEVICE_NONE;
4178
4179 if (fromCache) {
4180 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4181 strategy, mDeviceForStrategy[strategy]);
4182 return mDeviceForStrategy[strategy];
4183 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004184 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004185 switch (strategy) {
4186
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004187 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4188 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4189 if (!device) {
4190 ALOGE("getDeviceForStrategy() no device found for "\
4191 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4192 }
4193 break;
4194
Eric Laurente552edb2014-03-10 17:42:56 -07004195 case STRATEGY_SONIFICATION_RESPECTFUL:
4196 if (isInCall()) {
4197 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004198 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004199 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4200 // while media is playing on a remote device, use the the sonification behavior.
4201 // Note that we test this usecase before testing if media is playing because
4202 // the isStreamActive() method only informs about the activity of a stream, not
4203 // if it's for local playback. Note also that we use the same delay between both tests
4204 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004205 //user "safe" speaker if available instead of normal speaker to avoid triggering
4206 //other acoustic safety mechanisms for notification
4207 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4208 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004209 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004210 // while media is playing (or has recently played), use the same device
4211 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4212 } else {
4213 // when media is not playing anymore, fall back on the sonification behavior
4214 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004215 //user "safe" speaker if available instead of normal speaker to avoid triggering
4216 //other acoustic safety mechanisms for notification
4217 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4218 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004219 }
4220
4221 break;
4222
4223 case STRATEGY_DTMF:
4224 if (!isInCall()) {
4225 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4226 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4227 break;
4228 }
4229 // when in call, DTMF and PHONE strategies follow the same rules
4230 // FALL THROUGH
4231
4232 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004233 // Force use of only devices on primary output if:
4234 // - in call AND
4235 // - cannot route from voice call RX OR
4236 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4237 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4238 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4239 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4240 if (((mAvailableInputDevices.types() &
4241 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4242 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004243 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004244 AUDIO_DEVICE_API_VERSION_3_0))) {
4245 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4246 }
4247 }
Eric Laurente552edb2014-03-10 17:42:56 -07004248 // for phone strategy, we first consider the forced use and then the available devices by order
4249 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004250 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4251 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004252 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004253 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004254 if (device) break;
4255 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004256 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004257 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004258 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004259 if (device) break;
4260 // if SCO device is requested but no SCO device is available, fall back to default case
4261 // FALL THROUGH
4262
4263 default: // FORCE_NONE
4264 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004265 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004266 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004267 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004268 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004269 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004270 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004271 if (device) break;
4272 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004273 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004274 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004275 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004276 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004277 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4278 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004279 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004280 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004281 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004282 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004283 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004284 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004285 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004286 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004287 if (device) break;
4288 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004289 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004290 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004291 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004292 if (device == AUDIO_DEVICE_NONE) {
4293 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4294 }
4295 break;
4296
Eric Laurent3b73df72014-03-11 09:06:29 -07004297 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004298 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4299 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004300 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004301 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004302 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004303 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004304 if (device) break;
4305 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004306 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004307 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004308 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004309 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004310 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004311 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004312 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004313 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004314 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004315 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004316 if (device) break;
4317 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004318 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4319 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004320 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004321 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004322 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004323 if (device == AUDIO_DEVICE_NONE) {
4324 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4325 }
4326 break;
4327 }
4328 break;
4329
4330 case STRATEGY_SONIFICATION:
4331
4332 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4333 // handleIncallSonification().
4334 if (isInCall()) {
4335 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4336 break;
4337 }
4338 // FALL THROUGH
4339
4340 case STRATEGY_ENFORCED_AUDIBLE:
4341 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4342 // except:
4343 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4344 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4345
4346 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004347 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004348 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004349 if (device == AUDIO_DEVICE_NONE) {
4350 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4351 }
4352 }
4353 // The second device used for sonification is the same as the device used by media strategy
4354 // FALL THROUGH
4355
Eric Laurent223fd5c2014-11-11 13:43:36 -08004356 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4357 case STRATEGY_ACCESSIBILITY:
4358 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004359 case STRATEGY_MEDIA: {
4360 uint32_t device2 = AUDIO_DEVICE_NONE;
4361 if (strategy != STRATEGY_SONIFICATION) {
4362 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004363 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004364 }
4365 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004366 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004367 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004368 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004369 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004370 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004371 }
4372 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004373 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004374 }
4375 }
Hochi Huang327cb702014-09-21 09:47:31 +08004376 if ((device2 == AUDIO_DEVICE_NONE) &&
4377 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4378 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4379 }
Eric Laurente552edb2014-03-10 17:42:56 -07004380 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004381 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004382 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004383 if ((device2 == AUDIO_DEVICE_NONE)) {
4384 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4385 }
Eric Laurente552edb2014-03-10 17:42:56 -07004386 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004387 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004388 }
4389 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004390 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004391 }
4392 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004393 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004394 }
4395 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004396 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004397 }
4398 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4399 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004400 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004401 }
4402 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004403 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004404 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004405 }
4406 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004407 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004408 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004409 int device3 = AUDIO_DEVICE_NONE;
4410 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004411 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004412 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4413 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004414 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004415 }
Eric Laurente552edb2014-03-10 17:42:56 -07004416
Jungshik Jang839e4f32014-06-26 17:23:40 +09004417 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004418 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4419 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4420 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004421
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004422 // If hdmi system audio mode is on, remove speaker out of output list.
4423 if ((strategy == STRATEGY_MEDIA) &&
4424 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4425 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4426 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4427 }
4428
Eric Laurente552edb2014-03-10 17:42:56 -07004429 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004430 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004431 if (device == AUDIO_DEVICE_NONE) {
4432 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4433 }
4434 } break;
4435
4436 default:
4437 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4438 break;
4439 }
4440
4441 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4442 return device;
4443}
4444
Eric Laurente0720872014-03-11 09:30:41 -07004445void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004446{
4447 for (int i = 0; i < NUM_STRATEGIES; i++) {
4448 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4449 }
4450 mPreviousOutputs = mOutputs;
4451}
4452
Eric Laurent1f2f2232014-06-02 12:01:23 -07004453uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004454 audio_devices_t prevDevice,
4455 uint32_t delayMs)
4456{
4457 // mute/unmute strategies using an incompatible device combination
4458 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4459 // if unmuting, unmute only after the specified delay
4460 if (outputDesc->isDuplicated()) {
4461 return 0;
4462 }
4463
4464 uint32_t muteWaitMs = 0;
4465 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004466 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004467
4468 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4469 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004470 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004471 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4472 bool doMute = false;
4473
4474 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4475 doMute = true;
4476 outputDesc->mStrategyMutedByDevice[i] = true;
4477 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4478 doMute = true;
4479 outputDesc->mStrategyMutedByDevice[i] = false;
4480 }
Eric Laurent99401132014-05-07 19:48:15 -07004481 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004482 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004483 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004484 // skip output if it does not share any device with current output
4485 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4486 == AUDIO_DEVICE_NONE) {
4487 continue;
4488 }
4489 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4490 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4491 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4492 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4493 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004494 if (mute) {
4495 // FIXME: should not need to double latency if volume could be applied
4496 // immediately by the audioflinger mixer. We must account for the delay
4497 // between now and the next time the audioflinger thread for this output
4498 // will process a buffer (which corresponds to one buffer size,
4499 // usually 1/2 or 1/4 of the latency).
4500 if (muteWaitMs < desc->latency() * 2) {
4501 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004502 }
4503 }
4504 }
4505 }
4506 }
4507 }
4508
Eric Laurent99401132014-05-07 19:48:15 -07004509 // temporary mute output if device selection changes to avoid volume bursts due to
4510 // different per device volumes
4511 if (outputDesc->isActive() && (device != prevDevice)) {
4512 if (muteWaitMs < outputDesc->latency() * 2) {
4513 muteWaitMs = outputDesc->latency() * 2;
4514 }
4515 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4516 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004517 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004518 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004519 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004520 muteWaitMs *2, device);
4521 }
4522 }
4523 }
4524
Eric Laurente552edb2014-03-10 17:42:56 -07004525 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4526 if (muteWaitMs > delayMs) {
4527 muteWaitMs -= delayMs;
4528 usleep(muteWaitMs * 1000);
4529 return muteWaitMs;
4530 }
4531 return 0;
4532}
4533
Eric Laurente0720872014-03-11 09:30:41 -07004534uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004535 audio_devices_t device,
4536 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004537 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004538 audio_patch_handle_t *patchHandle,
4539 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004540{
4541 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004542 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004543 AudioParameter param;
4544 uint32_t muteWaitMs;
4545
4546 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004547 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4548 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004549 return muteWaitMs;
4550 }
4551 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4552 // output profile
4553 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004554 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004555 return 0;
4556 }
4557
4558 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004559 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004560
4561 audio_devices_t prevDevice = outputDesc->mDevice;
4562
4563 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4564
4565 if (device != AUDIO_DEVICE_NONE) {
4566 outputDesc->mDevice = device;
4567 }
4568 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4569
4570 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004571 // the requested device is AUDIO_DEVICE_NONE
4572 // OR the requested device is the same as current device
4573 // AND force is not specified
4574 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004575 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004576 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4577 outputDesc->mPatchHandle != 0) {
4578 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4579 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004580 return muteWaitMs;
4581 }
4582
4583 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004584
Eric Laurente552edb2014-03-10 17:42:56 -07004585 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004586 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004587 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004588 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004589 DeviceVector deviceList = (address == NULL) ?
4590 mAvailableOutputDevices.getDevicesFromType(device)
4591 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004592 if (!deviceList.isEmpty()) {
4593 struct audio_patch patch;
4594 outputDesc->toAudioPortConfig(&patch.sources[0]);
4595 patch.num_sources = 1;
4596 patch.num_sinks = 0;
4597 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4598 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004599 patch.num_sinks++;
4600 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004601 ssize_t index;
4602 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4603 index = mAudioPatches.indexOfKey(*patchHandle);
4604 } else {
4605 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4606 }
4607 sp< AudioPatch> patchDesc;
4608 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4609 if (index >= 0) {
4610 patchDesc = mAudioPatches.valueAt(index);
4611 afPatchHandle = patchDesc->mAfPatchHandle;
4612 }
4613
Eric Laurent1c333e22014-05-20 10:48:17 -07004614 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004615 &afPatchHandle,
4616 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004617 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4618 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004619 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004620 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004621 if (index < 0) {
4622 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4623 &patch, mUidCached);
4624 addAudioPatch(patchDesc->mHandle, patchDesc);
4625 } else {
4626 patchDesc->mPatch = patch;
4627 }
4628 patchDesc->mAfPatchHandle = afPatchHandle;
4629 patchDesc->mUid = mUidCached;
4630 if (patchHandle) {
4631 *patchHandle = patchDesc->mHandle;
4632 }
4633 outputDesc->mPatchHandle = patchDesc->mHandle;
4634 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004635 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004636 }
4637 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004638
4639 // inform all input as well
4640 for (size_t i = 0; i < mInputs.size(); i++) {
4641 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4642 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4643 AudioParameter inputCmd = AudioParameter();
4644 ALOGV("%s: inform input %d of device:%d", __func__,
4645 inputDescriptor->mIoHandle, device);
4646 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4647 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4648 inputCmd.toString(),
4649 delayMs);
4650 }
4651 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004652 }
Eric Laurente552edb2014-03-10 17:42:56 -07004653
4654 // update stream volumes according to new device
4655 applyStreamVolumes(output, device, delayMs);
4656
4657 return muteWaitMs;
4658}
4659
Eric Laurent1c333e22014-05-20 10:48:17 -07004660status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004661 int delayMs,
4662 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004663{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004664 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004665 ssize_t index;
4666 if (patchHandle) {
4667 index = mAudioPatches.indexOfKey(*patchHandle);
4668 } else {
4669 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4670 }
4671 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004672 return INVALID_OPERATION;
4673 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004674 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4675 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004676 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4677 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004678 removeAudioPatch(patchDesc->mHandle);
4679 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004680 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004681 return status;
4682}
4683
4684status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4685 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004686 bool force,
4687 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004688{
4689 status_t status = NO_ERROR;
4690
Eric Laurent1f2f2232014-06-02 12:01:23 -07004691 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004692 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4693 inputDesc->mDevice = device;
4694
4695 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4696 if (!deviceList.isEmpty()) {
4697 struct audio_patch patch;
4698 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004699 // AUDIO_SOURCE_HOTWORD is for internal use only:
4700 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004701 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4702 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004703 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4704 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004705 patch.num_sinks = 1;
4706 //only one input device for now
4707 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004708 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004709 ssize_t index;
4710 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4711 index = mAudioPatches.indexOfKey(*patchHandle);
4712 } else {
4713 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4714 }
4715 sp< AudioPatch> patchDesc;
4716 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4717 if (index >= 0) {
4718 patchDesc = mAudioPatches.valueAt(index);
4719 afPatchHandle = patchDesc->mAfPatchHandle;
4720 }
4721
Eric Laurent1c333e22014-05-20 10:48:17 -07004722 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004723 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004724 0);
4725 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004727 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004728 if (index < 0) {
4729 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4730 &patch, mUidCached);
4731 addAudioPatch(patchDesc->mHandle, patchDesc);
4732 } else {
4733 patchDesc->mPatch = patch;
4734 }
4735 patchDesc->mAfPatchHandle = afPatchHandle;
4736 patchDesc->mUid = mUidCached;
4737 if (patchHandle) {
4738 *patchHandle = patchDesc->mHandle;
4739 }
4740 inputDesc->mPatchHandle = patchDesc->mHandle;
4741 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004742 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004743 }
4744 }
4745 }
4746 return status;
4747}
4748
Eric Laurent6a94d692014-05-20 11:18:06 -07004749status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4750 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004751{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004752 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004753 ssize_t index;
4754 if (patchHandle) {
4755 index = mAudioPatches.indexOfKey(*patchHandle);
4756 } else {
4757 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4758 }
4759 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004760 return INVALID_OPERATION;
4761 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004762 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4763 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004764 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4765 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004766 removeAudioPatch(patchDesc->mHandle);
4767 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004768 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004769 return status;
4770}
4771
4772sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004773 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004774 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004775 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004776 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004777{
4778 // Choose an input profile based on the requested capture parameters: select the first available
4779 // profile supporting all requested parameters.
4780
4781 for (size_t i = 0; i < mHwModules.size(); i++)
4782 {
4783 if (mHwModules[i]->mHandle == 0) {
4784 continue;
4785 }
4786 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4787 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004788 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004789 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004790 if (profile->isCompatibleProfile(device, samplingRate,
4791 &samplingRate /*updatedSamplingRate*/,
4792 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004793 return profile;
4794 }
4795 }
4796 }
4797 return NULL;
4798}
4799
Eric Laurente0720872014-03-11 09:30:41 -07004800audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004801{
4802 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004803 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4804 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004805 switch (inputSource) {
4806 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004807 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004808 device = AUDIO_DEVICE_IN_VOICE_CALL;
4809 break;
4810 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004811 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004812
4813 case AUDIO_SOURCE_DEFAULT:
4814 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004815 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4816 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004817 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4818 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4819 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4820 device = AUDIO_DEVICE_IN_USB_DEVICE;
4821 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4822 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004823 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004824 break;
4825
4826 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4827 // Allow only use of devices on primary input if in call and HAL does not support routing
4828 // to voice call path.
4829 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4830 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4831 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4832 }
4833
4834 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4835 case AUDIO_POLICY_FORCE_BT_SCO:
4836 // if SCO device is requested but no SCO device is available, fall back to default case
4837 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4838 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4839 break;
4840 }
4841 // FALL THROUGH
4842
4843 default: // FORCE_NONE
4844 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4845 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4846 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4847 device = AUDIO_DEVICE_IN_USB_DEVICE;
4848 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4849 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4850 }
4851 break;
4852
4853 case AUDIO_POLICY_FORCE_SPEAKER:
4854 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4855 device = AUDIO_DEVICE_IN_BACK_MIC;
4856 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4857 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4858 }
4859 break;
4860 }
4861 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004862
Eric Laurente552edb2014-03-10 17:42:56 -07004863 case AUDIO_SOURCE_VOICE_RECOGNITION:
4864 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004865 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004866 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004867 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004868 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004869 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004870 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4871 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004872 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004873 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4874 }
4875 break;
4876 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004877 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004878 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004879 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004880 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4881 }
4882 break;
4883 case AUDIO_SOURCE_VOICE_DOWNLINK:
4884 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004885 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004886 device = AUDIO_DEVICE_IN_VOICE_CALL;
4887 }
4888 break;
4889 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004890 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004891 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4892 }
4893 break;
Hochi Huang327cb702014-09-21 09:47:31 +08004894 case AUDIO_SOURCE_FM_TUNER:
4895 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
4896 device = AUDIO_DEVICE_IN_FM_TUNER;
4897 }
4898 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004899 default:
4900 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4901 break;
4902 }
4903 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4904 return device;
4905}
4906
Eric Laurente0720872014-03-11 09:30:41 -07004907bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004908{
4909 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4910 device &= ~AUDIO_DEVICE_BIT_IN;
4911 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4912 return true;
4913 }
4914 return false;
4915}
4916
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004917bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4918 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4919}
4920
Eric Laurente0720872014-03-11 09:30:41 -07004921audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004922{
4923 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004924 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004925 if ((input_descriptor->mRefCount > 0)
4926 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4927 return mInputs.keyAt(i);
4928 }
4929 }
4930 return 0;
4931}
4932
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004933uint32_t AudioPolicyManager::activeInputsCount() const
4934{
4935 uint32_t count = 0;
4936 for (size_t i = 0; i < mInputs.size(); i++) {
4937 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4938 if (desc->mRefCount > 0) {
4939 return count++;
4940 }
4941 }
4942 return count;
4943}
4944
Eric Laurente552edb2014-03-10 17:42:56 -07004945
Eric Laurente0720872014-03-11 09:30:41 -07004946audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004947{
4948 if (device == AUDIO_DEVICE_NONE) {
4949 // this happens when forcing a route update and no track is active on an output.
4950 // In this case the returned category is not important.
4951 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004952 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004953 // Multiple device selection is either:
4954 // - speaker + one other device: give priority to speaker in this case.
4955 // - one A2DP device + another device: happens with duplicated output. In this case
4956 // retain the device on the A2DP output as the other must not correspond to an active
4957 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004958 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004959 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4960 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004961 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4962 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4963 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4964 device = AUDIO_DEVICE_OUT_AUX_LINE;
4965 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4966 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004967 } else {
4968 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4969 }
4970 }
4971
Jon Eklund11c9fb12014-06-23 14:47:03 -05004972 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4973 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4974 device = AUDIO_DEVICE_OUT_SPEAKER;
4975
Eric Laurent3b73df72014-03-11 09:06:29 -07004976 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004977 "getDeviceForVolume() invalid device combination: %08x",
4978 device);
4979
4980 return device;
4981}
4982
Eric Laurente0720872014-03-11 09:30:41 -07004983AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004984{
4985 switch(getDeviceForVolume(device)) {
4986 case AUDIO_DEVICE_OUT_EARPIECE:
4987 return DEVICE_CATEGORY_EARPIECE;
4988 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4989 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4990 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4991 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4992 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4993 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4994 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004995 case AUDIO_DEVICE_OUT_LINE:
4996 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4997 /*USB? Remote submix?*/
4998 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004999 case AUDIO_DEVICE_OUT_SPEAKER:
5000 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5001 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005002 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5003 case AUDIO_DEVICE_OUT_USB_DEVICE:
5004 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5005 default:
5006 return DEVICE_CATEGORY_SPEAKER;
5007 }
5008}
5009
Eric Laurent223fd5c2014-11-11 13:43:36 -08005010/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005011float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005012 int indexInUi)
5013{
5014 device_category deviceCategory = getDeviceCategory(device);
5015 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5016
5017 // the volume index in the UI is relative to the min and max volume indices for this stream type
5018 int nbSteps = 1 + curve[VOLMAX].mIndex -
5019 curve[VOLMIN].mIndex;
5020 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5021 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5022
5023 // find what part of the curve this index volume belongs to, or if it's out of bounds
5024 int segment = 0;
5025 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5026 return 0.0f;
5027 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5028 segment = 0;
5029 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5030 segment = 1;
5031 } else if (volIdx <= curve[VOLMAX].mIndex) {
5032 segment = 2;
5033 } else { // out of bounds
5034 return 1.0f;
5035 }
5036
5037 // linear interpolation in the attenuation table in dB
5038 float decibels = curve[segment].mDBAttenuation +
5039 ((float)(volIdx - curve[segment].mIndex)) *
5040 ( (curve[segment+1].mDBAttenuation -
5041 curve[segment].mDBAttenuation) /
5042 ((float)(curve[segment+1].mIndex -
5043 curve[segment].mIndex)) );
5044
5045 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5046
5047 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5048 curve[segment].mIndex, volIdx,
5049 curve[segment+1].mIndex,
5050 curve[segment].mDBAttenuation,
5051 decibels,
5052 curve[segment+1].mDBAttenuation,
5053 amplification);
5054
5055 return amplification;
5056}
5057
Eric Laurente0720872014-03-11 09:30:41 -07005058const AudioPolicyManager::VolumeCurvePoint
5059 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005060 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5061};
5062
Eric Laurente0720872014-03-11 09:30:41 -07005063const AudioPolicyManager::VolumeCurvePoint
5064 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005065 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5066};
5067
Eric Laurente0720872014-03-11 09:30:41 -07005068const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005069 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5070 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5071};
5072
5073const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005074 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005075 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5076};
5077
Eric Laurente0720872014-03-11 09:30:41 -07005078const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005079 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005080 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005081};
5082
5083const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005084 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005085 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5086};
5087
Eric Laurente0720872014-03-11 09:30:41 -07005088const AudioPolicyManager::VolumeCurvePoint
5089 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005090 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5091};
5092
5093// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5094// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5095// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5096// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5097
Eric Laurente0720872014-03-11 09:30:41 -07005098const AudioPolicyManager::VolumeCurvePoint
5099 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005100 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5101};
5102
Eric Laurente0720872014-03-11 09:30:41 -07005103const AudioPolicyManager::VolumeCurvePoint
5104 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005105 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5106};
5107
Eric Laurente0720872014-03-11 09:30:41 -07005108const AudioPolicyManager::VolumeCurvePoint
5109 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005110 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5111};
5112
Eric Laurente0720872014-03-11 09:30:41 -07005113const AudioPolicyManager::VolumeCurvePoint
5114 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005115 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5116};
5117
Eric Laurente0720872014-03-11 09:30:41 -07005118const AudioPolicyManager::VolumeCurvePoint
5119 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005120 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5121};
5122
Eric Laurente0720872014-03-11 09:30:41 -07005123const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005124 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5125 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5126};
5127
5128const AudioPolicyManager::VolumeCurvePoint
5129 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5130 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5131};
5132
5133const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005134 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5135 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5136};
5137
5138const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005139 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5140 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005141 { // AUDIO_STREAM_VOICE_CALL
5142 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5143 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005144 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5145 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005146 },
5147 { // AUDIO_STREAM_SYSTEM
5148 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5149 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005150 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5151 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005152 },
5153 { // AUDIO_STREAM_RING
5154 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5155 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005156 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5157 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005158 },
5159 { // AUDIO_STREAM_MUSIC
5160 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5161 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005162 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5163 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005164 },
5165 { // AUDIO_STREAM_ALARM
5166 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5167 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005168 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5169 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005170 },
5171 { // AUDIO_STREAM_NOTIFICATION
5172 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5173 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005174 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5175 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005176 },
5177 { // AUDIO_STREAM_BLUETOOTH_SCO
5178 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5179 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005180 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5181 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005182 },
5183 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5184 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5185 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005186 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5187 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005188 },
5189 { // AUDIO_STREAM_DTMF
5190 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5191 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005192 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5193 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005194 },
5195 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005196 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5197 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5198 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5199 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5200 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005201 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005202 { // AUDIO_STREAM_ACCESSIBILITY
5203 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5204 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5205 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5206 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5207 },
5208 { // AUDIO_STREAM_REROUTING
5209 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5210 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5211 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5212 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5213 },
5214 { // AUDIO_STREAM_PATCH
5215 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5216 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5217 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5218 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5219 },
Eric Laurente552edb2014-03-10 17:42:56 -07005220};
5221
Eric Laurente0720872014-03-11 09:30:41 -07005222void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005223{
5224 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5225 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5226 mStreams[i].mVolumeCurve[j] =
5227 sVolumeProfiles[i][j];
5228 }
5229 }
5230
5231 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5232 if (mSpeakerDrcEnabled) {
5233 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5234 sDefaultSystemVolumeCurveDrc;
5235 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5236 sSpeakerSonificationVolumeCurveDrc;
5237 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5238 sSpeakerSonificationVolumeCurveDrc;
5239 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5240 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005241 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5242 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005243 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5244 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005245 }
5246}
5247
Eric Laurente0720872014-03-11 09:30:41 -07005248float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005249 int index,
5250 audio_io_handle_t output,
5251 audio_devices_t device)
5252{
5253 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005254 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005255 StreamDescriptor &streamDesc = mStreams[stream];
5256
5257 if (device == AUDIO_DEVICE_NONE) {
5258 device = outputDesc->device();
5259 }
5260
Eric Laurente552edb2014-03-10 17:42:56 -07005261 volume = volIndexToAmpl(device, streamDesc, index);
5262
5263 // if a headset is connected, apply the following rules to ring tones and notifications
5264 // to avoid sound level bursts in user's ears:
5265 // - always attenuate ring tones and notifications volume by 6dB
5266 // - if music is playing, always limit the volume to current music volume,
5267 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005268 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005269 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5270 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5271 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5272 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5273 ((stream_strategy == STRATEGY_SONIFICATION)
5274 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005275 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005276 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005277 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005278 streamDesc.mCanBeMuted) {
5279 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5280 // when the phone is ringing we must consider that music could have been paused just before
5281 // by the music application and behave as if music was active if the last music track was
5282 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005283 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005284 mLimitRingtoneVolume) {
5285 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005286 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5287 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005288 output,
5289 musicDevice);
5290 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5291 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5292 if (volume > minVol) {
5293 volume = minVol;
5294 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5295 }
5296 }
5297 }
5298
5299 return volume;
5300}
5301
Eric Laurente0720872014-03-11 09:30:41 -07005302status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005303 int index,
5304 audio_io_handle_t output,
5305 audio_devices_t device,
5306 int delayMs,
5307 bool force)
5308{
5309
5310 // do not change actual stream volume if the stream is muted
5311 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5312 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5313 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5314 return NO_ERROR;
5315 }
5316
5317 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005318 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5319 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5320 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5321 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005322 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005323 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005324 return INVALID_OPERATION;
5325 }
5326
5327 float volume = computeVolume(stream, index, output, device);
5328 // We actually change the volume if:
5329 // - the float value returned by computeVolume() changed
5330 // - the force flag is set
5331 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5332 force) {
5333 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5334 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5335 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5336 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005337 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5338 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005339 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005340 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005341 }
5342
Eric Laurent3b73df72014-03-11 09:06:29 -07005343 if (stream == AUDIO_STREAM_VOICE_CALL ||
5344 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005345 float voiceVolume;
5346 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005347 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005348 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5349 } else {
5350 voiceVolume = 1.0;
5351 }
5352
5353 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5354 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5355 mLastVoiceVolume = voiceVolume;
5356 }
5357 }
5358
5359 return NO_ERROR;
5360}
5361
Eric Laurente0720872014-03-11 09:30:41 -07005362void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005363 audio_devices_t device,
5364 int delayMs,
5365 bool force)
5366{
5367 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5368
Eric Laurent3b73df72014-03-11 09:06:29 -07005369 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005370 if (stream == AUDIO_STREAM_PATCH) {
5371 continue;
5372 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005373 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005374 mStreams[stream].getVolumeIndex(device),
5375 output,
5376 device,
5377 delayMs,
5378 force);
5379 }
5380}
5381
Eric Laurente0720872014-03-11 09:30:41 -07005382void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005383 bool on,
5384 audio_io_handle_t output,
5385 int delayMs,
5386 audio_devices_t device)
5387{
5388 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005389 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005390 if (stream == AUDIO_STREAM_PATCH) {
5391 continue;
5392 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005393 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5394 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005395 }
5396 }
5397}
5398
Eric Laurente0720872014-03-11 09:30:41 -07005399void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005400 bool on,
5401 audio_io_handle_t output,
5402 int delayMs,
5403 audio_devices_t device)
5404{
5405 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005406 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005407 if (device == AUDIO_DEVICE_NONE) {
5408 device = outputDesc->device();
5409 }
5410
5411 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5412 stream, on, output, outputDesc->mMuteCount[stream], device);
5413
5414 if (on) {
5415 if (outputDesc->mMuteCount[stream] == 0) {
5416 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005417 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5418 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005419 checkAndSetVolume(stream, 0, output, device, delayMs);
5420 }
5421 }
5422 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5423 outputDesc->mMuteCount[stream]++;
5424 } else {
5425 if (outputDesc->mMuteCount[stream] == 0) {
5426 ALOGV("setStreamMute() unmuting non muted stream!");
5427 return;
5428 }
5429 if (--outputDesc->mMuteCount[stream] == 0) {
5430 checkAndSetVolume(stream,
5431 streamDesc.getVolumeIndex(device),
5432 output,
5433 device,
5434 delayMs);
5435 }
5436 }
5437}
5438
Eric Laurente0720872014-03-11 09:30:41 -07005439void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005440 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005441{
5442 // if the stream pertains to sonification strategy and we are in call we must
5443 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5444 // in the device used for phone strategy and play the tone if the selected device does not
5445 // interfere with the device used for phone strategy
5446 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5447 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005448 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005449 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5450 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005451 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005452 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5453 stream, starting, outputDesc->mDevice, stateChange);
5454 if (outputDesc->mRefCount[stream]) {
5455 int muteCount = 1;
5456 if (stateChange) {
5457 muteCount = outputDesc->mRefCount[stream];
5458 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005459 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005460 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5461 for (int i = 0; i < muteCount; i++) {
5462 setStreamMute(stream, starting, mPrimaryOutput);
5463 }
5464 } else {
5465 ALOGV("handleIncallSonification() high visibility");
5466 if (outputDesc->device() &
5467 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5468 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5469 for (int i = 0; i < muteCount; i++) {
5470 setStreamMute(stream, starting, mPrimaryOutput);
5471 }
5472 }
5473 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005474 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5475 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005476 } else {
5477 mpClientInterface->stopTone();
5478 }
5479 }
5480 }
5481 }
5482}
5483
Eric Laurente0720872014-03-11 09:30:41 -07005484bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005485{
5486 return isStateInCall(mPhoneState);
5487}
5488
Eric Laurente0720872014-03-11 09:30:41 -07005489bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005490 return ((state == AUDIO_MODE_IN_CALL) ||
5491 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005492}
5493
Eric Laurente0720872014-03-11 09:30:41 -07005494uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005495{
5496 return MAX_EFFECTS_CPU_LOAD;
5497}
5498
Eric Laurente0720872014-03-11 09:30:41 -07005499uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005500{
5501 return MAX_EFFECTS_MEMORY;
5502}
5503
Eric Laurent6a94d692014-05-20 11:18:06 -07005504
Eric Laurente552edb2014-03-10 17:42:56 -07005505// --- AudioOutputDescriptor class implementation
5506
Eric Laurente0720872014-03-11 09:30:41 -07005507AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005508 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005509 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005510 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005511 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5512{
5513 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005514 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005515 mRefCount[i] = 0;
5516 mCurVolume[i] = -1.0;
5517 mMuteCount[i] = 0;
5518 mStopTime[i] = 0;
5519 }
5520 for (int i = 0; i < NUM_STRATEGIES; i++) {
5521 mStrategyMutedByDevice[i] = false;
5522 }
5523 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005524 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005525 mSamplingRate = profile->pickSamplingRate();
5526 mFormat = profile->pickFormat();
5527 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005528 if (profile->mGains.size() > 0) {
5529 profile->mGains[0]->getDefaultConfig(&mGain);
5530 }
Eric Laurente552edb2014-03-10 17:42:56 -07005531 }
5532}
5533
Eric Laurente0720872014-03-11 09:30:41 -07005534audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005535{
5536 if (isDuplicated()) {
5537 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5538 } else {
5539 return mDevice;
5540 }
5541}
5542
Eric Laurente0720872014-03-11 09:30:41 -07005543uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005544{
5545 if (isDuplicated()) {
5546 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5547 } else {
5548 return mLatency;
5549 }
5550}
5551
Eric Laurente0720872014-03-11 09:30:41 -07005552bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005553 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005554{
5555 if (isDuplicated()) {
5556 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5557 } else if (outputDesc->isDuplicated()){
5558 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5559 } else {
5560 return (mProfile->mModule == outputDesc->mProfile->mModule);
5561 }
5562}
5563
Eric Laurente0720872014-03-11 09:30:41 -07005564void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005565 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005566{
5567 // forward usage count change to attached outputs
5568 if (isDuplicated()) {
5569 mOutput1->changeRefCount(stream, delta);
5570 mOutput2->changeRefCount(stream, delta);
5571 }
5572 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005573 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5574 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005575 mRefCount[stream] = 0;
5576 return;
5577 }
5578 mRefCount[stream] += delta;
5579 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5580}
5581
Eric Laurente0720872014-03-11 09:30:41 -07005582audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005583{
5584 if (isDuplicated()) {
5585 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5586 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005587 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005588 }
5589}
5590
Eric Laurente0720872014-03-11 09:30:41 -07005591bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005592{
5593 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5594}
5595
Eric Laurente0720872014-03-11 09:30:41 -07005596bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005597 uint32_t inPastMs,
5598 nsecs_t sysTime) const
5599{
5600 if ((sysTime == 0) && (inPastMs != 0)) {
5601 sysTime = systemTime();
5602 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005603 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005604 if (i == AUDIO_STREAM_PATCH) {
5605 continue;
5606 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005607 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005608 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005609 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005610 return true;
5611 }
5612 }
5613 return false;
5614}
5615
Eric Laurente0720872014-03-11 09:30:41 -07005616bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005617 uint32_t inPastMs,
5618 nsecs_t sysTime) const
5619{
5620 if (mRefCount[stream] != 0) {
5621 return true;
5622 }
5623 if (inPastMs == 0) {
5624 return false;
5625 }
5626 if (sysTime == 0) {
5627 sysTime = systemTime();
5628 }
5629 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5630 return true;
5631 }
5632 return false;
5633}
5634
Eric Laurent1c333e22014-05-20 10:48:17 -07005635void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005636 struct audio_port_config *dstConfig,
5637 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005638{
Eric Laurent84c70242014-06-23 08:46:27 -07005639 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5640
Eric Laurent1f2f2232014-06-02 12:01:23 -07005641 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5642 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5643 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005644 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005645 }
5646 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5647
Eric Laurent6a94d692014-05-20 11:18:06 -07005648 dstConfig->id = mId;
5649 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5650 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005651 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5652 dstConfig->ext.mix.handle = mIoHandle;
5653 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005654}
5655
5656void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5657 struct audio_port *port) const
5658{
Eric Laurent84c70242014-06-23 08:46:27 -07005659 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005660 mProfile->toAudioPort(port);
5661 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005662 toAudioPortConfig(&port->active_config);
5663 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005664 port->ext.mix.handle = mIoHandle;
5665 port->ext.mix.latency_class =
5666 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5667}
Eric Laurente552edb2014-03-10 17:42:56 -07005668
Eric Laurente0720872014-03-11 09:30:41 -07005669status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005670{
5671 const size_t SIZE = 256;
5672 char buffer[SIZE];
5673 String8 result;
5674
Eric Laurent4d416952014-08-10 14:07:09 -07005675 snprintf(buffer, SIZE, " ID: %d\n", mId);
5676 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005677 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5678 result.append(buffer);
5679 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5680 result.append(buffer);
5681 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5682 result.append(buffer);
5683 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5684 result.append(buffer);
5685 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5686 result.append(buffer);
5687 snprintf(buffer, SIZE, " Devices %08x\n", device());
5688 result.append(buffer);
5689 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5690 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005691 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5692 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5693 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005694 result.append(buffer);
5695 }
5696 write(fd, result.string(), result.size());
5697
5698 return NO_ERROR;
5699}
5700
5701// --- AudioInputDescriptor class implementation
5702
Eric Laurent1c333e22014-05-20 10:48:17 -07005703AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005704 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005705 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005706 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005707{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005708 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005709 mSamplingRate = profile->pickSamplingRate();
5710 mFormat = profile->pickFormat();
5711 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005712 if (profile->mGains.size() > 0) {
5713 profile->mGains[0]->getDefaultConfig(&mGain);
5714 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005715 }
Eric Laurente552edb2014-03-10 17:42:56 -07005716}
5717
Eric Laurent1c333e22014-05-20 10:48:17 -07005718void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005719 struct audio_port_config *dstConfig,
5720 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005721{
Eric Laurent84c70242014-06-23 08:46:27 -07005722 ALOG_ASSERT(mProfile != 0,
5723 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005724 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5725 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5726 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005727 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005728 }
5729
5730 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5731
Eric Laurent6a94d692014-05-20 11:18:06 -07005732 dstConfig->id = mId;
5733 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5734 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005735 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5736 dstConfig->ext.mix.handle = mIoHandle;
5737 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005738}
5739
5740void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5741 struct audio_port *port) const
5742{
Eric Laurent84c70242014-06-23 08:46:27 -07005743 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5744
Eric Laurent1c333e22014-05-20 10:48:17 -07005745 mProfile->toAudioPort(port);
5746 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005747 toAudioPortConfig(&port->active_config);
5748 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005749 port->ext.mix.handle = mIoHandle;
5750 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5751}
5752
Eric Laurente0720872014-03-11 09:30:41 -07005753status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005754{
5755 const size_t SIZE = 256;
5756 char buffer[SIZE];
5757 String8 result;
5758
Eric Laurent4d416952014-08-10 14:07:09 -07005759 snprintf(buffer, SIZE, " ID: %d\n", mId);
5760 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005761 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5762 result.append(buffer);
5763 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5764 result.append(buffer);
5765 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5766 result.append(buffer);
5767 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5768 result.append(buffer);
5769 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5770 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005771 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5772 result.append(buffer);
5773
Eric Laurente552edb2014-03-10 17:42:56 -07005774 write(fd, result.string(), result.size());
5775
5776 return NO_ERROR;
5777}
5778
5779// --- StreamDescriptor class implementation
5780
Eric Laurente0720872014-03-11 09:30:41 -07005781AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005782 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5783{
5784 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5785}
5786
Eric Laurente0720872014-03-11 09:30:41 -07005787int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005788{
Eric Laurente0720872014-03-11 09:30:41 -07005789 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005790 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5791 if (mIndexCur.indexOfKey(device) < 0) {
5792 device = AUDIO_DEVICE_OUT_DEFAULT;
5793 }
5794 return mIndexCur.valueFor(device);
5795}
5796
Eric Laurente0720872014-03-11 09:30:41 -07005797void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005798{
5799 const size_t SIZE = 256;
5800 char buffer[SIZE];
5801 String8 result;
5802
5803 snprintf(buffer, SIZE, "%s %02d %02d ",
5804 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5805 result.append(buffer);
5806 for (size_t i = 0; i < mIndexCur.size(); i++) {
5807 snprintf(buffer, SIZE, "%04x : %02d, ",
5808 mIndexCur.keyAt(i),
5809 mIndexCur.valueAt(i));
5810 result.append(buffer);
5811 }
5812 result.append("\n");
5813
5814 write(fd, result.string(), result.size());
5815}
5816
5817// --- EffectDescriptor class implementation
5818
Eric Laurente0720872014-03-11 09:30:41 -07005819status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005820{
5821 const size_t SIZE = 256;
5822 char buffer[SIZE];
5823 String8 result;
5824
5825 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5826 result.append(buffer);
5827 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5828 result.append(buffer);
5829 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5830 result.append(buffer);
5831 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5832 result.append(buffer);
5833 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5834 result.append(buffer);
5835 write(fd, result.string(), result.size());
5836
5837 return NO_ERROR;
5838}
5839
Eric Laurent1c333e22014-05-20 10:48:17 -07005840// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005841
Eric Laurente0720872014-03-11 09:30:41 -07005842AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005843 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5844 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005845{
5846}
5847
Eric Laurente0720872014-03-11 09:30:41 -07005848AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005849{
5850 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005851 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005852 }
5853 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005854 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005855 }
5856 free((void *)mName);
5857}
5858
Eric Laurent1afeecb2014-05-14 08:52:28 -07005859status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5860{
5861 cnode *node = root->first_child;
5862
5863 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5864
5865 while (node) {
5866 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5867 profile->loadSamplingRates((char *)node->value);
5868 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5869 profile->loadFormats((char *)node->value);
5870 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5871 profile->loadInChannels((char *)node->value);
5872 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5873 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5874 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005875 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5876 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005877 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5878 profile->loadGains(node);
5879 }
5880 node = node->next;
5881 }
5882 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5883 "loadInput() invalid supported devices");
5884 ALOGW_IF(profile->mChannelMasks.size() == 0,
5885 "loadInput() invalid supported channel masks");
5886 ALOGW_IF(profile->mSamplingRates.size() == 0,
5887 "loadInput() invalid supported sampling rates");
5888 ALOGW_IF(profile->mFormats.size() == 0,
5889 "loadInput() invalid supported formats");
5890 if (!profile->mSupportedDevices.isEmpty() &&
5891 (profile->mChannelMasks.size() != 0) &&
5892 (profile->mSamplingRates.size() != 0) &&
5893 (profile->mFormats.size() != 0)) {
5894
5895 ALOGV("loadInput() adding input Supported Devices %04x",
5896 profile->mSupportedDevices.types());
5897
5898 mInputProfiles.add(profile);
5899 return NO_ERROR;
5900 } else {
5901 return BAD_VALUE;
5902 }
5903}
5904
5905status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5906{
5907 cnode *node = root->first_child;
5908
5909 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5910
5911 while (node) {
5912 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5913 profile->loadSamplingRates((char *)node->value);
5914 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5915 profile->loadFormats((char *)node->value);
5916 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5917 profile->loadOutChannels((char *)node->value);
5918 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5919 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5920 mDeclaredDevices);
5921 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005922 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005923 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5924 profile->loadGains(node);
5925 }
5926 node = node->next;
5927 }
5928 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5929 "loadOutput() invalid supported devices");
5930 ALOGW_IF(profile->mChannelMasks.size() == 0,
5931 "loadOutput() invalid supported channel masks");
5932 ALOGW_IF(profile->mSamplingRates.size() == 0,
5933 "loadOutput() invalid supported sampling rates");
5934 ALOGW_IF(profile->mFormats.size() == 0,
5935 "loadOutput() invalid supported formats");
5936 if (!profile->mSupportedDevices.isEmpty() &&
5937 (profile->mChannelMasks.size() != 0) &&
5938 (profile->mSamplingRates.size() != 0) &&
5939 (profile->mFormats.size() != 0)) {
5940
5941 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5942 profile->mSupportedDevices.types(), profile->mFlags);
5943
5944 mOutputProfiles.add(profile);
5945 return NO_ERROR;
5946 } else {
5947 return BAD_VALUE;
5948 }
5949}
5950
5951status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5952{
5953 cnode *node = root->first_child;
5954
5955 audio_devices_t type = AUDIO_DEVICE_NONE;
5956 while (node) {
5957 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5958 type = parseDeviceNames((char *)node->value);
5959 break;
5960 }
5961 node = node->next;
5962 }
5963 if (type == AUDIO_DEVICE_NONE ||
5964 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5965 ALOGW("loadDevice() bad type %08x", type);
5966 return BAD_VALUE;
5967 }
5968 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5969 deviceDesc->mModule = this;
5970
5971 node = root->first_child;
5972 while (node) {
5973 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5974 deviceDesc->mAddress = String8((char *)node->value);
5975 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5976 if (audio_is_input_device(type)) {
5977 deviceDesc->loadInChannels((char *)node->value);
5978 } else {
5979 deviceDesc->loadOutChannels((char *)node->value);
5980 }
5981 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5982 deviceDesc->loadGains(node);
5983 }
5984 node = node->next;
5985 }
5986
5987 ALOGV("loadDevice() adding device name %s type %08x address %s",
5988 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5989
5990 mDeclaredDevices.add(deviceDesc);
5991
5992 return NO_ERROR;
5993}
5994
Eric Laurente0720872014-03-11 09:30:41 -07005995void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005996{
5997 const size_t SIZE = 256;
5998 char buffer[SIZE];
5999 String8 result;
6000
6001 snprintf(buffer, SIZE, " - name: %s\n", mName);
6002 result.append(buffer);
6003 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6004 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006005 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6006 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006007 write(fd, result.string(), result.size());
6008 if (mOutputProfiles.size()) {
6009 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6010 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006011 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006012 write(fd, buffer, strlen(buffer));
6013 mOutputProfiles[i]->dump(fd);
6014 }
6015 }
6016 if (mInputProfiles.size()) {
6017 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6018 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006019 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006020 write(fd, buffer, strlen(buffer));
6021 mInputProfiles[i]->dump(fd);
6022 }
6023 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006024 if (mDeclaredDevices.size()) {
6025 write(fd, " - devices:\n", strlen(" - devices:\n"));
6026 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6027 mDeclaredDevices[i]->dump(fd, 4, i);
6028 }
6029 }
Eric Laurente552edb2014-03-10 17:42:56 -07006030}
6031
Eric Laurent1c333e22014-05-20 10:48:17 -07006032// --- AudioPort class implementation
6033
Eric Laurenta121f902014-06-03 13:32:54 -07006034
6035AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6036 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006037 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006038{
6039 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6040 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6041}
6042
Eric Laurent1c333e22014-05-20 10:48:17 -07006043void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6044{
6045 port->role = mRole;
6046 port->type = mType;
6047 unsigned int i;
6048 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006049 if (mSamplingRates[i] != 0) {
6050 port->sample_rates[i] = mSamplingRates[i];
6051 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006052 }
6053 port->num_sample_rates = i;
6054 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006055 if (mChannelMasks[i] != 0) {
6056 port->channel_masks[i] = mChannelMasks[i];
6057 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006058 }
6059 port->num_channel_masks = i;
6060 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006061 if (mFormats[i] != 0) {
6062 port->formats[i] = mFormats[i];
6063 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006064 }
6065 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006066
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006067 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006068
6069 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6070 port->gains[i] = mGains[i]->mGain;
6071 }
6072 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006073}
6074
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006075void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6076 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6077 const uint32_t rate = port->mSamplingRates.itemAt(k);
6078 if (rate != 0) { // skip "dynamic" rates
6079 bool hasRate = false;
6080 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6081 if (rate == mSamplingRates.itemAt(l)) {
6082 hasRate = true;
6083 break;
6084 }
6085 }
6086 if (!hasRate) { // never import a sampling rate twice
6087 mSamplingRates.add(rate);
6088 }
6089 }
6090 }
6091 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6092 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6093 if (mask != 0) { // skip "dynamic" masks
6094 bool hasMask = false;
6095 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6096 if (mask == mChannelMasks.itemAt(l)) {
6097 hasMask = true;
6098 break;
6099 }
6100 }
6101 if (!hasMask) { // never import a channel mask twice
6102 mChannelMasks.add(mask);
6103 }
6104 }
6105 }
6106 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6107 const audio_format_t format = port->mFormats.itemAt(k);
6108 if (format != 0) { // skip "dynamic" formats
6109 bool hasFormat = false;
6110 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6111 if (format == mFormats.itemAt(l)) {
6112 hasFormat = true;
6113 break;
6114 }
6115 }
6116 if (!hasFormat) { // never import a channel mask twice
6117 mFormats.add(format);
6118 }
6119 }
6120 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006121 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6122 sp<AudioGain> gain = port->mGains.itemAt(k);
6123 if (gain != 0) {
6124 bool hasGain = false;
6125 for (size_t l = 0 ; l < mGains.size() ; l++) {
6126 if (gain == mGains.itemAt(l)) {
6127 hasGain = true;
6128 break;
6129 }
6130 }
6131 if (!hasGain) { // never import a gain twice
6132 mGains.add(gain);
6133 }
6134 }
6135 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006136}
6137
6138void AudioPolicyManager::AudioPort::clearCapabilities() {
6139 mChannelMasks.clear();
6140 mFormats.clear();
6141 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006142 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006143}
Eric Laurent1c333e22014-05-20 10:48:17 -07006144
6145void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6146{
6147 char *str = strtok(name, "|");
6148
6149 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6150 // rates should be read from the output stream after it is opened for the first time
6151 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6152 mSamplingRates.add(0);
6153 return;
6154 }
6155
6156 while (str != NULL) {
6157 uint32_t rate = atoi(str);
6158 if (rate != 0) {
6159 ALOGV("loadSamplingRates() adding rate %d", rate);
6160 mSamplingRates.add(rate);
6161 }
6162 str = strtok(NULL, "|");
6163 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006164}
6165
6166void AudioPolicyManager::AudioPort::loadFormats(char *name)
6167{
6168 char *str = strtok(name, "|");
6169
6170 // by convention, "0' in the first entry in mFormats indicates the supported formats
6171 // should be read from the output stream after it is opened for the first time
6172 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6173 mFormats.add(AUDIO_FORMAT_DEFAULT);
6174 return;
6175 }
6176
6177 while (str != NULL) {
6178 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6179 ARRAY_SIZE(sFormatNameToEnumTable),
6180 str);
6181 if (format != AUDIO_FORMAT_DEFAULT) {
6182 mFormats.add(format);
6183 }
6184 str = strtok(NULL, "|");
6185 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006186}
6187
6188void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6189{
6190 const char *str = strtok(name, "|");
6191
6192 ALOGV("loadInChannels() %s", name);
6193
6194 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6195 mChannelMasks.add(0);
6196 return;
6197 }
6198
6199 while (str != NULL) {
6200 audio_channel_mask_t channelMask =
6201 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6202 ARRAY_SIZE(sInChannelsNameToEnumTable),
6203 str);
6204 if (channelMask != 0) {
6205 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6206 mChannelMasks.add(channelMask);
6207 }
6208 str = strtok(NULL, "|");
6209 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006210}
6211
6212void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6213{
6214 const char *str = strtok(name, "|");
6215
6216 ALOGV("loadOutChannels() %s", name);
6217
6218 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6219 // masks should be read from the output stream after it is opened for the first time
6220 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6221 mChannelMasks.add(0);
6222 return;
6223 }
6224
6225 while (str != NULL) {
6226 audio_channel_mask_t channelMask =
6227 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6228 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6229 str);
6230 if (channelMask != 0) {
6231 mChannelMasks.add(channelMask);
6232 }
6233 str = strtok(NULL, "|");
6234 }
6235 return;
6236}
6237
Eric Laurent1afeecb2014-05-14 08:52:28 -07006238audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6239{
6240 const char *str = strtok(name, "|");
6241
6242 ALOGV("loadGainMode() %s", name);
6243 audio_gain_mode_t mode = 0;
6244 while (str != NULL) {
6245 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6246 ARRAY_SIZE(sGainModeNameToEnumTable),
6247 str);
6248 str = strtok(NULL, "|");
6249 }
6250 return mode;
6251}
6252
Eric Laurenta121f902014-06-03 13:32:54 -07006253void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006254{
6255 cnode *node = root->first_child;
6256
Eric Laurenta121f902014-06-03 13:32:54 -07006257 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006258
6259 while (node) {
6260 if (strcmp(node->name, GAIN_MODE) == 0) {
6261 gain->mGain.mode = loadGainMode((char *)node->value);
6262 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006263 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006264 gain->mGain.channel_mask =
6265 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6266 ARRAY_SIZE(sInChannelsNameToEnumTable),
6267 (char *)node->value);
6268 } else {
6269 gain->mGain.channel_mask =
6270 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6271 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6272 (char *)node->value);
6273 }
6274 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6275 gain->mGain.min_value = atoi((char *)node->value);
6276 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6277 gain->mGain.max_value = atoi((char *)node->value);
6278 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6279 gain->mGain.default_value = atoi((char *)node->value);
6280 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6281 gain->mGain.step_value = atoi((char *)node->value);
6282 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6283 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6284 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6285 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6286 }
6287 node = node->next;
6288 }
6289
6290 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6291 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6292
6293 if (gain->mGain.mode == 0) {
6294 return;
6295 }
6296 mGains.add(gain);
6297}
6298
6299void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6300{
6301 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006302 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006303 while (node) {
6304 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006305 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006306 node = node->next;
6307 }
6308}
6309
Glenn Kastencbd48022014-07-24 13:46:44 -07006310status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006311{
6312 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6313 if (mSamplingRates[i] == samplingRate) {
6314 return NO_ERROR;
6315 }
6316 }
6317 return BAD_VALUE;
6318}
6319
Glenn Kastencbd48022014-07-24 13:46:44 -07006320status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6321 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006322{
Glenn Kastencbd48022014-07-24 13:46:44 -07006323 // Search for the closest supported sampling rate that is above (preferred)
6324 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6325 // The sampling rates do not need to be sorted in ascending order.
6326 ssize_t maxBelow = -1;
6327 ssize_t minAbove = -1;
6328 uint32_t candidate;
6329 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6330 candidate = mSamplingRates[i];
6331 if (candidate == samplingRate) {
6332 if (updatedSamplingRate != NULL) {
6333 *updatedSamplingRate = candidate;
6334 }
6335 return NO_ERROR;
6336 }
6337 // candidate < desired
6338 if (candidate < samplingRate) {
6339 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6340 maxBelow = i;
6341 }
6342 // candidate > desired
6343 } else {
6344 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6345 minAbove = i;
6346 }
6347 }
6348 }
6349 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6350 // TODO Move these assumptions out.
6351 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6352 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6353 // due to approximation by an int32_t of the
6354 // phase increments
6355 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6356 if (minAbove >= 0) {
6357 candidate = mSamplingRates[minAbove];
6358 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6359 if (updatedSamplingRate != NULL) {
6360 *updatedSamplingRate = candidate;
6361 }
6362 return NO_ERROR;
6363 }
6364 }
6365 // But if we have to up-sample from a lower sampling rate, that's OK.
6366 if (maxBelow >= 0) {
6367 candidate = mSamplingRates[maxBelow];
6368 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6369 if (updatedSamplingRate != NULL) {
6370 *updatedSamplingRate = candidate;
6371 }
6372 return NO_ERROR;
6373 }
6374 }
6375 // leave updatedSamplingRate unmodified
6376 return BAD_VALUE;
6377}
6378
6379status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6380{
6381 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006382 if (mChannelMasks[i] == channelMask) {
6383 return NO_ERROR;
6384 }
6385 }
6386 return BAD_VALUE;
6387}
6388
Glenn Kastencbd48022014-07-24 13:46:44 -07006389status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6390 const
6391{
6392 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6393 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6394 // FIXME Does not handle multi-channel automatic conversions yet
6395 audio_channel_mask_t supported = mChannelMasks[i];
6396 if (supported == channelMask) {
6397 return NO_ERROR;
6398 }
6399 if (isRecordThread) {
6400 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6401 // FIXME Abstract this out to a table.
6402 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6403 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6404 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6405 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6406 return NO_ERROR;
6407 }
6408 }
6409 }
6410 return BAD_VALUE;
6411}
6412
Eric Laurenta121f902014-06-03 13:32:54 -07006413status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6414{
6415 for (size_t i = 0; i < mFormats.size(); i ++) {
6416 if (mFormats[i] == format) {
6417 return NO_ERROR;
6418 }
6419 }
6420 return BAD_VALUE;
6421}
6422
Eric Laurent1e693b52014-07-09 15:03:28 -07006423
6424uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6425{
6426 // special case for uninitialized dynamic profile
6427 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6428 return 0;
6429 }
6430
Eric Laurent828bcff2014-09-07 12:26:06 -07006431 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6432 // channel count / sampling rate combination chosen will be supported by the connected
6433 // sink
6434 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6435 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6436 uint32_t samplingRate = UINT_MAX;
6437 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6438 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6439 samplingRate = mSamplingRates[i];
6440 }
6441 }
6442 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6443 }
6444
Eric Laurent1e693b52014-07-09 15:03:28 -07006445 uint32_t samplingRate = 0;
6446 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6447
6448 // For mixed output and inputs, use max mixer sampling rates. Do not
6449 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006450 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006451 maxRate = UINT_MAX;
6452 }
6453 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6454 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6455 samplingRate = mSamplingRates[i];
6456 }
6457 }
6458 return samplingRate;
6459}
6460
6461audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6462{
6463 // special case for uninitialized dynamic profile
6464 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6465 return AUDIO_CHANNEL_NONE;
6466 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006467 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006468
6469 // For direct outputs, pick minimum channel count: this helps ensuring that the
6470 // channel count / sampling rate combination chosen will be supported by the connected
6471 // sink
6472 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6473 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6474 uint32_t channelCount = UINT_MAX;
6475 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6476 uint32_t cnlCount;
6477 if (mUseInChannelMask) {
6478 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6479 } else {
6480 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6481 }
6482 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6483 channelMask = mChannelMasks[i];
6484 channelCount = cnlCount;
6485 }
6486 }
6487 return channelMask;
6488 }
6489
Eric Laurent1e693b52014-07-09 15:03:28 -07006490 uint32_t channelCount = 0;
6491 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6492
6493 // For mixed output and inputs, use max mixer channel count. Do not
6494 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006495 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006496 maxCount = UINT_MAX;
6497 }
6498 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6499 uint32_t cnlCount;
6500 if (mUseInChannelMask) {
6501 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6502 } else {
6503 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6504 }
6505 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6506 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006507 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006508 }
6509 }
6510 return channelMask;
6511}
6512
Andy Hung9a605382014-07-28 16:16:31 -07006513/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006514const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6515 AUDIO_FORMAT_DEFAULT,
6516 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006517 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006518 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006519 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006520 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006521};
6522
6523int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6524 audio_format_t format2)
6525{
6526 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6527 // compressed format and better than any PCM format. This is by design of pickFormat()
6528 if (!audio_is_linear_pcm(format1)) {
6529 if (!audio_is_linear_pcm(format2)) {
6530 return 0;
6531 }
6532 return 1;
6533 }
6534 if (!audio_is_linear_pcm(format2)) {
6535 return -1;
6536 }
6537
6538 int index1 = -1, index2 = -1;
6539 for (size_t i = 0;
6540 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6541 i ++) {
6542 if (sPcmFormatCompareTable[i] == format1) {
6543 index1 = i;
6544 }
6545 if (sPcmFormatCompareTable[i] == format2) {
6546 index2 = i;
6547 }
6548 }
6549 // format1 not found => index1 < 0 => format2 > format1
6550 // format2 not found => index2 < 0 => format2 < format1
6551 return index1 - index2;
6552}
6553
6554audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6555{
6556 // special case for uninitialized dynamic profile
6557 if (mFormats.size() == 1 && mFormats[0] == 0) {
6558 return AUDIO_FORMAT_DEFAULT;
6559 }
6560
6561 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006562 audio_format_t bestFormat =
6563 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6564 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006565 // For mixed output and inputs, use best mixer output format. Do not
6566 // limit format otherwise
6567 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6568 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006569 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006570 bestFormat = AUDIO_FORMAT_INVALID;
6571 }
6572
6573 for (size_t i = 0; i < mFormats.size(); i ++) {
6574 if ((compareFormats(mFormats[i], format) > 0) &&
6575 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6576 format = mFormats[i];
6577 }
6578 }
6579 return format;
6580}
6581
Eric Laurenta121f902014-06-03 13:32:54 -07006582status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6583 int index) const
6584{
6585 if (index < 0 || (size_t)index >= mGains.size()) {
6586 return BAD_VALUE;
6587 }
6588 return mGains[index]->checkConfig(gainConfig);
6589}
6590
Eric Laurent1afeecb2014-05-14 08:52:28 -07006591void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6592{
6593 const size_t SIZE = 256;
6594 char buffer[SIZE];
6595 String8 result;
6596
6597 if (mName.size() != 0) {
6598 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6599 result.append(buffer);
6600 }
6601
6602 if (mSamplingRates.size() != 0) {
6603 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6604 result.append(buffer);
6605 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006606 if (i == 0 && mSamplingRates[i] == 0) {
6607 snprintf(buffer, SIZE, "Dynamic");
6608 } else {
6609 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6610 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006611 result.append(buffer);
6612 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6613 }
6614 result.append("\n");
6615 }
6616
6617 if (mChannelMasks.size() != 0) {
6618 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6619 result.append(buffer);
6620 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006621 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6622
6623 if (i == 0 && mChannelMasks[i] == 0) {
6624 snprintf(buffer, SIZE, "Dynamic");
6625 } else {
6626 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6627 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006628 result.append(buffer);
6629 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6630 }
6631 result.append("\n");
6632 }
6633
6634 if (mFormats.size() != 0) {
6635 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6636 result.append(buffer);
6637 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006638 const char *formatStr = enumToString(sFormatNameToEnumTable,
6639 ARRAY_SIZE(sFormatNameToEnumTable),
6640 mFormats[i]);
6641 if (i == 0 && strcmp(formatStr, "") == 0) {
6642 snprintf(buffer, SIZE, "Dynamic");
6643 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006644 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006645 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006646 result.append(buffer);
6647 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6648 }
6649 result.append("\n");
6650 }
6651 write(fd, result.string(), result.size());
6652 if (mGains.size() != 0) {
6653 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6654 write(fd, buffer, strlen(buffer) + 1);
6655 result.append(buffer);
6656 for (size_t i = 0; i < mGains.size(); i++) {
6657 mGains[i]->dump(fd, spaces + 2, i);
6658 }
6659 }
6660}
6661
6662// --- AudioGain class implementation
6663
Eric Laurenta121f902014-06-03 13:32:54 -07006664AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006665{
Eric Laurenta121f902014-06-03 13:32:54 -07006666 mIndex = index;
6667 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006668 memset(&mGain, 0, sizeof(struct audio_gain));
6669}
6670
Eric Laurenta121f902014-06-03 13:32:54 -07006671void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6672{
6673 config->index = mIndex;
6674 config->mode = mGain.mode;
6675 config->channel_mask = mGain.channel_mask;
6676 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6677 config->values[0] = mGain.default_value;
6678 } else {
6679 uint32_t numValues;
6680 if (mUseInChannelMask) {
6681 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6682 } else {
6683 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6684 }
6685 for (size_t i = 0; i < numValues; i++) {
6686 config->values[i] = mGain.default_value;
6687 }
6688 }
6689 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6690 config->ramp_duration_ms = mGain.min_ramp_ms;
6691 }
6692}
6693
6694status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6695{
6696 if ((config->mode & ~mGain.mode) != 0) {
6697 return BAD_VALUE;
6698 }
6699 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6700 if ((config->values[0] < mGain.min_value) ||
6701 (config->values[0] > mGain.max_value)) {
6702 return BAD_VALUE;
6703 }
6704 } else {
6705 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6706 return BAD_VALUE;
6707 }
6708 uint32_t numValues;
6709 if (mUseInChannelMask) {
6710 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6711 } else {
6712 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6713 }
6714 for (size_t i = 0; i < numValues; i++) {
6715 if ((config->values[i] < mGain.min_value) ||
6716 (config->values[i] > mGain.max_value)) {
6717 return BAD_VALUE;
6718 }
6719 }
6720 }
6721 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6722 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6723 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6724 return BAD_VALUE;
6725 }
6726 }
6727 return NO_ERROR;
6728}
6729
Eric Laurent1afeecb2014-05-14 08:52:28 -07006730void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6731{
6732 const size_t SIZE = 256;
6733 char buffer[SIZE];
6734 String8 result;
6735
6736 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6737 result.append(buffer);
6738 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6739 result.append(buffer);
6740 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6741 result.append(buffer);
6742 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6743 result.append(buffer);
6744 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6745 result.append(buffer);
6746 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6747 result.append(buffer);
6748 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6749 result.append(buffer);
6750 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6751 result.append(buffer);
6752 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6753 result.append(buffer);
6754
6755 write(fd, result.string(), result.size());
6756}
6757
Eric Laurent1f2f2232014-06-02 12:01:23 -07006758// --- AudioPortConfig class implementation
6759
6760AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6761{
6762 mSamplingRate = 0;
6763 mChannelMask = AUDIO_CHANNEL_NONE;
6764 mFormat = AUDIO_FORMAT_INVALID;
6765 mGain.index = -1;
6766}
6767
Eric Laurenta121f902014-06-03 13:32:54 -07006768status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6769 const struct audio_port_config *config,
6770 struct audio_port_config *backupConfig)
6771{
6772 struct audio_port_config localBackupConfig;
6773 status_t status = NO_ERROR;
6774
6775 localBackupConfig.config_mask = config->config_mask;
6776 toAudioPortConfig(&localBackupConfig);
6777
Marco Nelissen961ec212014-08-25 15:58:39 -07006778 sp<AudioPort> audioport = getAudioPort();
6779 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006780 status = NO_INIT;
6781 goto exit;
6782 }
6783 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006784 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006785 if (status != NO_ERROR) {
6786 goto exit;
6787 }
6788 mSamplingRate = config->sample_rate;
6789 }
6790 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006791 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006792 if (status != NO_ERROR) {
6793 goto exit;
6794 }
6795 mChannelMask = config->channel_mask;
6796 }
6797 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006798 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006799 if (status != NO_ERROR) {
6800 goto exit;
6801 }
6802 mFormat = config->format;
6803 }
6804 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006805 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006806 if (status != NO_ERROR) {
6807 goto exit;
6808 }
6809 mGain = config->gain;
6810 }
6811
6812exit:
6813 if (status != NO_ERROR) {
6814 applyAudioPortConfig(&localBackupConfig);
6815 }
6816 if (backupConfig != NULL) {
6817 *backupConfig = localBackupConfig;
6818 }
6819 return status;
6820}
6821
Eric Laurent1f2f2232014-06-02 12:01:23 -07006822void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6823 struct audio_port_config *dstConfig,
6824 const struct audio_port_config *srcConfig) const
6825{
6826 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6827 dstConfig->sample_rate = mSamplingRate;
6828 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6829 dstConfig->sample_rate = srcConfig->sample_rate;
6830 }
6831 } else {
6832 dstConfig->sample_rate = 0;
6833 }
6834 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6835 dstConfig->channel_mask = mChannelMask;
6836 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6837 dstConfig->channel_mask = srcConfig->channel_mask;
6838 }
6839 } else {
6840 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6841 }
6842 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6843 dstConfig->format = mFormat;
6844 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6845 dstConfig->format = srcConfig->format;
6846 }
6847 } else {
6848 dstConfig->format = AUDIO_FORMAT_INVALID;
6849 }
6850 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6851 dstConfig->gain = mGain;
6852 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6853 dstConfig->gain = srcConfig->gain;
6854 }
6855 } else {
6856 dstConfig->gain.index = -1;
6857 }
6858 if (dstConfig->gain.index != -1) {
6859 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6860 } else {
6861 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6862 }
6863}
6864
Eric Laurent1c333e22014-05-20 10:48:17 -07006865// --- IOProfile class implementation
6866
Eric Laurent1afeecb2014-05-14 08:52:28 -07006867AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006868 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006869 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006870{
6871}
6872
Eric Laurente0720872014-03-11 09:30:41 -07006873AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006874{
6875}
6876
6877// checks if the IO profile is compatible with specified parameters.
6878// Sampling rate, format and channel mask must be specified in order to
6879// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006880bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006881 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006882 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006883 audio_format_t format,
6884 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006885 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006886{
Glenn Kastencbd48022014-07-24 13:46:44 -07006887 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6888 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6889 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006890
Glenn Kastencbd48022014-07-24 13:46:44 -07006891 if ((mSupportedDevices.types() & device) != device) {
6892 return false;
6893 }
6894
6895 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006896 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006897 }
6898 uint32_t myUpdatedSamplingRate = samplingRate;
6899 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006900 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006901 }
6902 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6903 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006904 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006905 }
6906
6907 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6908 return false;
6909 }
6910
6911 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6912 checkExactChannelMask(channelMask) != NO_ERROR)) {
6913 return false;
6914 }
6915 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6916 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6917 return false;
6918 }
6919
6920 if (isPlaybackThread && (mFlags & flags) != flags) {
6921 return false;
6922 }
6923 // The only input flag that is allowed to be different is the fast flag.
6924 // An existing fast stream is compatible with a normal track request.
6925 // An existing normal stream is compatible with a fast track request,
6926 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006927 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006928 ~AUDIO_INPUT_FLAG_FAST)) {
6929 return false;
6930 }
6931
6932 if (updatedSamplingRate != NULL) {
6933 *updatedSamplingRate = myUpdatedSamplingRate;
6934 }
6935 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006936}
6937
Eric Laurente0720872014-03-11 09:30:41 -07006938void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006939{
6940 const size_t SIZE = 256;
6941 char buffer[SIZE];
6942 String8 result;
6943
Eric Laurent1afeecb2014-05-14 08:52:28 -07006944 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006945
Eric Laurente552edb2014-03-10 17:42:56 -07006946 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6947 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006948 snprintf(buffer, SIZE, " - devices:\n");
6949 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006950 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006951 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6952 mSupportedDevices[i]->dump(fd, 6, i);
6953 }
Eric Laurente552edb2014-03-10 17:42:56 -07006954}
6955
Eric Laurentd4692962014-05-05 18:13:44 -07006956void AudioPolicyManager::IOProfile::log()
6957{
6958 const size_t SIZE = 256;
6959 char buffer[SIZE];
6960 String8 result;
6961
6962 ALOGV(" - sampling rates: ");
6963 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6964 ALOGV(" %d", mSamplingRates[i]);
6965 }
6966
6967 ALOGV(" - channel masks: ");
6968 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6969 ALOGV(" 0x%04x", mChannelMasks[i]);
6970 }
6971
6972 ALOGV(" - formats: ");
6973 for (size_t i = 0; i < mFormats.size(); i++) {
6974 ALOGV(" 0x%08x", mFormats[i]);
6975 }
6976
6977 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6978 ALOGV(" - flags: 0x%04x\n", mFlags);
6979}
6980
6981
Eric Laurent3a4311c2014-03-17 12:00:47 -07006982// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006983
Eric Laurent1f2f2232014-06-02 12:01:23 -07006984
6985AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6986 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6987 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6988 AUDIO_PORT_ROLE_SOURCE,
6989 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006990 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006991{
Eric Laurenta121f902014-06-03 13:32:54 -07006992 if (mGains.size() > 0) {
6993 mGains[0]->getDefaultConfig(&mGain);
6994 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006995}
6996
Eric Laurent3a4311c2014-03-17 12:00:47 -07006997bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006998{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006999 // Devices are considered equal if they:
7000 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7001 // - have the same address or one device does not specify the address
7002 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007003 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007004 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007005 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007006 mChannelMask == other->mChannelMask);
7007}
7008
7009void AudioPolicyManager::DeviceVector::refreshTypes()
7010{
Eric Laurent1c333e22014-05-20 10:48:17 -07007011 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007012 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007013 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007014 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007015 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007016}
7017
7018ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7019{
7020 for(size_t i = 0; i < size(); i++) {
7021 if (item->equals(itemAt(i))) {
7022 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007023 }
7024 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007025 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007026}
7027
Eric Laurent3a4311c2014-03-17 12:00:47 -07007028ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007029{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007030 ssize_t ret = indexOf(item);
7031
7032 if (ret < 0) {
7033 ret = SortedVector::add(item);
7034 if (ret >= 0) {
7035 refreshTypes();
7036 }
7037 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007038 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007039 ret = -1;
7040 }
7041 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007042}
7043
Eric Laurent3a4311c2014-03-17 12:00:47 -07007044ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7045{
7046 size_t i;
7047 ssize_t ret = indexOf(item);
7048
7049 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007050 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007051 } else {
7052 ret = SortedVector::removeAt(ret);
7053 if (ret >= 0) {
7054 refreshTypes();
7055 }
7056 }
7057 return ret;
7058}
7059
7060void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7061{
7062 DeviceVector deviceList;
7063
7064 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7065 types &= ~role_bit;
7066
7067 while (types) {
7068 uint32_t i = 31 - __builtin_clz(types);
7069 uint32_t type = 1 << i;
7070 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007071 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007072 }
7073}
7074
Eric Laurent1afeecb2014-05-14 08:52:28 -07007075void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7076 const DeviceVector& declaredDevices)
7077{
7078 char *devName = strtok(name, "|");
7079 while (devName != NULL) {
7080 if (strlen(devName) != 0) {
7081 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7082 ARRAY_SIZE(sDeviceNameToEnumTable),
7083 devName);
7084 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007085 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
7086 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
7087 dev->mAddress = String8("0");
7088 }
7089 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007090 } else {
7091 sp<DeviceDescriptor> deviceDesc =
7092 declaredDevices.getDeviceFromName(String8(devName));
7093 if (deviceDesc != 0) {
7094 add(deviceDesc);
7095 }
7096 }
7097 }
7098 devName = strtok(NULL, "|");
7099 }
7100}
7101
Eric Laurent1c333e22014-05-20 10:48:17 -07007102sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7103 audio_devices_t type, String8 address) const
7104{
7105 sp<DeviceDescriptor> device;
7106 for (size_t i = 0; i < size(); i++) {
7107 if (itemAt(i)->mDeviceType == type) {
7108 device = itemAt(i);
7109 if (itemAt(i)->mAddress = address) {
7110 break;
7111 }
7112 }
7113 }
7114 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
7115 type, address.string(), device.get());
7116 return device;
7117}
7118
Eric Laurent6a94d692014-05-20 11:18:06 -07007119sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7120 audio_port_handle_t id) const
7121{
7122 sp<DeviceDescriptor> device;
7123 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007124 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007125 if (itemAt(i)->mId == id) {
7126 device = itemAt(i);
7127 break;
7128 }
7129 }
7130 return device;
7131}
7132
Eric Laurent1c333e22014-05-20 10:48:17 -07007133AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7134 audio_devices_t type) const
7135{
7136 DeviceVector devices;
7137 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7138 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7139 devices.add(itemAt(i));
7140 type &= ~itemAt(i)->mDeviceType;
7141 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7142 itemAt(i)->mDeviceType, itemAt(i).get());
7143 }
7144 }
7145 return devices;
7146}
7147
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007148AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7149 audio_devices_t type, String8 address) const
7150{
7151 DeviceVector devices;
7152 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
7153 for (size_t i = 0; i < size(); i++) {
7154 //ALOGV(" at i=%d: device=%x, addr=%s",
7155 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
7156 if (itemAt(i)->mDeviceType == type) {
7157 if (itemAt(i)->mAddress == address) {
7158 //ALOGV(" found matching address %s", address.string());
7159 devices.add(itemAt(i));
7160 }
7161 }
7162 }
7163 return devices;
7164}
7165
Eric Laurent1afeecb2014-05-14 08:52:28 -07007166sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7167 const String8& name) const
7168{
7169 sp<DeviceDescriptor> device;
7170 for (size_t i = 0; i < size(); i++) {
7171 if (itemAt(i)->mName == name) {
7172 device = itemAt(i);
7173 break;
7174 }
7175 }
7176 return device;
7177}
7178
Eric Laurent6a94d692014-05-20 11:18:06 -07007179void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7180 struct audio_port_config *dstConfig,
7181 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007182{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007183 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7184 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007185 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007186 }
7187
7188 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7189
Eric Laurent6a94d692014-05-20 11:18:06 -07007190 dstConfig->id = mId;
7191 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007192 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007193 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007194 dstConfig->ext.device.type = mDeviceType;
7195 dstConfig->ext.device.hw_module = mModule->mHandle;
7196 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007197}
7198
7199void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7200{
Eric Laurent83b88082014-06-20 18:31:16 -07007201 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007202 AudioPort::toAudioPort(port);
7203 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007204 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007205 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007206 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007207 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7208}
7209
Eric Laurent1afeecb2014-05-14 08:52:28 -07007210status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007211{
7212 const size_t SIZE = 256;
7213 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007214 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007215
Eric Laurent1afeecb2014-05-14 08:52:28 -07007216 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7217 result.append(buffer);
7218 if (mId != 0) {
7219 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7220 result.append(buffer);
7221 }
7222 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7223 enumToString(sDeviceNameToEnumTable,
7224 ARRAY_SIZE(sDeviceNameToEnumTable),
7225 mDeviceType));
7226 result.append(buffer);
7227 if (mAddress.size() != 0) {
7228 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7229 result.append(buffer);
7230 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007231 write(fd, result.string(), result.size());
7232 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007233
7234 return NO_ERROR;
7235}
7236
Eric Laurent4d416952014-08-10 14:07:09 -07007237status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7238{
7239 const size_t SIZE = 256;
7240 char buffer[SIZE];
7241 String8 result;
7242
7243
7244 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7245 result.append(buffer);
7246 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7247 result.append(buffer);
7248 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7249 result.append(buffer);
7250 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7251 result.append(buffer);
7252 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7253 result.append(buffer);
7254 for (size_t i = 0; i < mPatch.num_sources; i++) {
7255 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7256 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7257 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7258 ARRAY_SIZE(sDeviceNameToEnumTable),
7259 mPatch.sources[i].ext.device.type));
7260 } else {
7261 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7262 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7263 }
7264 result.append(buffer);
7265 }
7266 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7267 result.append(buffer);
7268 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7269 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7270 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7271 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7272 ARRAY_SIZE(sDeviceNameToEnumTable),
7273 mPatch.sinks[i].ext.device.type));
7274 } else {
7275 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7276 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7277 }
7278 result.append(buffer);
7279 }
7280
7281 write(fd, result.string(), result.size());
7282 return NO_ERROR;
7283}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007284
7285// --- audio_policy.conf file parsing
7286
Eric Laurent5dbe4712014-09-19 19:04:57 -07007287uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007288{
7289 uint32_t flag = 0;
7290
7291 // it is OK to cast name to non const here as we are not going to use it after
7292 // strtok() modifies it
7293 char *flagName = strtok(name, "|");
7294 while (flagName != NULL) {
7295 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007296 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7297 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007298 flagName);
7299 }
7300 flagName = strtok(NULL, "|");
7301 }
7302 //force direct flag if offload flag is set: offloading implies a direct output stream
7303 // and all common behaviors are driven by checking only the direct flag
7304 // this should normally be set appropriately in the policy configuration file
7305 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7306 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7307 }
7308
Eric Laurent5dbe4712014-09-19 19:04:57 -07007309 return flag;
7310}
7311
7312uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7313{
7314 uint32_t flag = 0;
7315
7316 // it is OK to cast name to non const here as we are not going to use it after
7317 // strtok() modifies it
7318 char *flagName = strtok(name, "|");
7319 while (flagName != NULL) {
7320 if (strlen(flagName) != 0) {
7321 flag |= stringToEnum(sInputFlagNameToEnumTable,
7322 ARRAY_SIZE(sInputFlagNameToEnumTable),
7323 flagName);
7324 }
7325 flagName = strtok(NULL, "|");
7326 }
7327 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007328}
7329
Eric Laurente0720872014-03-11 09:30:41 -07007330audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007331{
7332 uint32_t device = 0;
7333
7334 char *devName = strtok(name, "|");
7335 while (devName != NULL) {
7336 if (strlen(devName) != 0) {
7337 device |= stringToEnum(sDeviceNameToEnumTable,
7338 ARRAY_SIZE(sDeviceNameToEnumTable),
7339 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007340 }
Eric Laurente552edb2014-03-10 17:42:56 -07007341 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007342 }
Eric Laurente552edb2014-03-10 17:42:56 -07007343 return device;
7344}
7345
Eric Laurente0720872014-03-11 09:30:41 -07007346void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007347{
Eric Laurente552edb2014-03-10 17:42:56 -07007348 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007349 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007350 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007351
Eric Laurent1afeecb2014-05-14 08:52:28 -07007352 node = config_find(root, DEVICES_TAG);
7353 if (node != NULL) {
7354 node = node->first_child;
7355 while (node) {
7356 ALOGV("loadHwModule() loading device %s", node->name);
7357 status_t tmpStatus = module->loadDevice(node);
7358 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7359 status = tmpStatus;
7360 }
7361 node = node->next;
7362 }
7363 }
7364 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007365 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007366 node = node->first_child;
7367 while (node) {
7368 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007369 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007370 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7371 status = tmpStatus;
7372 }
7373 node = node->next;
7374 }
7375 }
7376 node = config_find(root, INPUTS_TAG);
7377 if (node != NULL) {
7378 node = node->first_child;
7379 while (node) {
7380 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007381 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007382 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7383 status = tmpStatus;
7384 }
7385 node = node->next;
7386 }
7387 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007388 loadGlobalConfig(root, module);
7389
Eric Laurente552edb2014-03-10 17:42:56 -07007390 if (status == NO_ERROR) {
7391 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007392 }
7393}
7394
Eric Laurente0720872014-03-11 09:30:41 -07007395void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007396{
7397 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7398 if (node == NULL) {
7399 return;
7400 }
7401
7402 node = node->first_child;
7403 while (node) {
7404 ALOGV("loadHwModules() loading module %s", node->name);
7405 loadHwModule(node);
7406 node = node->next;
7407 }
7408}
7409
Eric Laurent1f2f2232014-06-02 12:01:23 -07007410void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007411{
7412 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007413
Eric Laurente552edb2014-03-10 17:42:56 -07007414 if (node == NULL) {
7415 return;
7416 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007417 DeviceVector declaredDevices;
7418 if (module != NULL) {
7419 declaredDevices = module->mDeclaredDevices;
7420 }
7421
Eric Laurente552edb2014-03-10 17:42:56 -07007422 node = node->first_child;
7423 while (node) {
7424 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007425 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7426 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007427 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7428 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007429 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007430 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007431 ARRAY_SIZE(sDeviceNameToEnumTable),
7432 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007433 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007434 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007435 } else {
7436 ALOGW("loadGlobalConfig() default device not specified");
7437 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007438 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007439 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007440 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7441 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007442 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007443 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7444 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7445 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007446 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7447 uint32_t major, minor;
7448 sscanf((char *)node->value, "%u.%u", &major, &minor);
7449 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7450 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7451 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007452 }
7453 node = node->next;
7454 }
7455}
7456
Eric Laurente0720872014-03-11 09:30:41 -07007457status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007458{
7459 cnode *root;
7460 char *data;
7461
7462 data = (char *)load_file(path, NULL);
7463 if (data == NULL) {
7464 return -ENODEV;
7465 }
7466 root = config_node("", "");
7467 config_load(root, data);
7468
Eric Laurente552edb2014-03-10 17:42:56 -07007469 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007470 // legacy audio_policy.conf files have one global_configuration section
7471 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007472 config_free(root);
7473 free(root);
7474 free(data);
7475
7476 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7477
7478 return NO_ERROR;
7479}
7480
Eric Laurente0720872014-03-11 09:30:41 -07007481void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007482{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007483 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007484 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007485 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7486 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007487 mAvailableOutputDevices.add(mDefaultOutputDevice);
7488 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007489
7490 module = new HwModule("primary");
7491
Eric Laurent1afeecb2014-05-14 08:52:28 -07007492 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007493 profile->mSamplingRates.add(44100);
7494 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7495 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007496 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007497 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7498 module->mOutputProfiles.add(profile);
7499
Eric Laurent1afeecb2014-05-14 08:52:28 -07007500 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007501 profile->mSamplingRates.add(8000);
7502 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7503 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007504 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007505 module->mInputProfiles.add(profile);
7506
7507 mHwModules.add(module);
7508}
7509
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007510audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7511{
7512 // flags to stream type mapping
7513 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7514 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7515 }
7516 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7517 return AUDIO_STREAM_BLUETOOTH_SCO;
7518 }
7519
7520 // usage to stream type mapping
7521 switch (attr->usage) {
7522 case AUDIO_USAGE_MEDIA:
7523 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007524 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7525 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007526 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007527 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7528 return AUDIO_STREAM_ALARM;
7529 }
7530 if (isStreamActive(AUDIO_STREAM_RING)) {
7531 return AUDIO_STREAM_RING;
7532 }
7533 if (isInCall()) {
7534 return AUDIO_STREAM_VOICE_CALL;
7535 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08007536 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007537 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7538 return AUDIO_STREAM_SYSTEM;
7539 case AUDIO_USAGE_VOICE_COMMUNICATION:
7540 return AUDIO_STREAM_VOICE_CALL;
7541
7542 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7543 return AUDIO_STREAM_DTMF;
7544
7545 case AUDIO_USAGE_ALARM:
7546 return AUDIO_STREAM_ALARM;
7547 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7548 return AUDIO_STREAM_RING;
7549
7550 case AUDIO_USAGE_NOTIFICATION:
7551 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7552 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7553 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7554 case AUDIO_USAGE_NOTIFICATION_EVENT:
7555 return AUDIO_STREAM_NOTIFICATION;
7556
7557 case AUDIO_USAGE_UNKNOWN:
7558 default:
7559 return AUDIO_STREAM_MUSIC;
7560 }
7561}
Eric Laurente83b55d2014-11-14 10:06:21 -08007562
7563bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
7564 // has flags that map to a strategy?
7565 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7566 return true;
7567 }
7568
7569 // has known usage?
7570 switch (paa->usage) {
7571 case AUDIO_USAGE_UNKNOWN:
7572 case AUDIO_USAGE_MEDIA:
7573 case AUDIO_USAGE_VOICE_COMMUNICATION:
7574 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7575 case AUDIO_USAGE_ALARM:
7576 case AUDIO_USAGE_NOTIFICATION:
7577 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7578 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7579 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7580 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7581 case AUDIO_USAGE_NOTIFICATION_EVENT:
7582 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7583 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7584 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7585 case AUDIO_USAGE_GAME:
7586 break;
7587 default:
7588 return false;
7589 }
7590 return true;
7591}
7592
Eric Laurente552edb2014-03-10 17:42:56 -07007593}; // namespace android