blob: 3cd5fb2b903e99602f75d3edb30d89c3e6756d32 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
Hochi Huang327cb702014-09-21 09:47:31 +080029#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
Eric Laurente552edb2014-03-10 17:42:56 -070030// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070047#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070048#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070049#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurent3b73df72014-03-11 09:06:29 -070051namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070052
53// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070054// Definitions for audio_policy.conf file parsing
55// ----------------------------------------------------------------------------
56
57struct StringToEnum {
58 const char *name;
59 uint32_t value;
60};
61
62#define STRING_TO_ENUM(string) { #string, string }
63#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64
65const StringToEnum sDeviceNameToEnumTable[] = {
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070069 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070081 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070087 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
91 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070092 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050093 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070094 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
98 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700108 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
110 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
111 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700112 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900113 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700114};
115
Eric Laurent5dbe4712014-09-19 19:04:57 -0700116const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700123 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700124};
125
Eric Laurent5dbe4712014-09-19 19:04:57 -0700126const StringToEnum sInputFlagNameToEnumTable[] = {
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
128 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
129};
130
Eric Laurent3a4311c2014-03-17 12:00:47 -0700131const StringToEnum sFormatNameToEnumTable[] = {
132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
137 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
138 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
149 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
152 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
153 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
154 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
155 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156};
157
158const StringToEnum sOutChannelsNameToEnumTable[] = {
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
163 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
164};
165
166const StringToEnum sInChannelsNameToEnumTable[] = {
167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
169 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
170};
171
Eric Laurent1afeecb2014-05-14 08:52:28 -0700172const StringToEnum sGainModeNameToEnumTable[] = {
173 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
174 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
175 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
176};
177
Eric Laurent3a4311c2014-03-17 12:00:47 -0700178
179uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
180 size_t size,
181 const char *name)
182{
183 for (size_t i = 0; i < size; i++) {
184 if (strcmp(table[i].name, name) == 0) {
185 ALOGV("stringToEnum() found %s", table[i].name);
186 return table[i].value;
187 }
188 }
189 return 0;
190}
191
192const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
193 size_t size,
194 uint32_t value)
195{
196 for (size_t i = 0; i < size; i++) {
197 if (table[i].value == value) {
198 return table[i].name;
199 }
200 }
201 return "";
202}
203
204bool AudioPolicyManager::stringToBool(const char *value)
205{
206 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
207}
208
209
210// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700211// AudioPolicyInterface implementation
212// ----------------------------------------------------------------------------
213
Eric Laurente0720872014-03-11 09:30:41 -0700214status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700216 const char *device_address)
217{
Eric Laurent22226012014-08-01 17:00:54 -0700218 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700219 // handle legacy remote submix case where the address was not always specified
220 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
221 address = String8("0");
222 }
Eric Laurente552edb2014-03-10 17:42:56 -0700223
Eric Laurent22226012014-08-01 17:00:54 -0700224 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
225 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700226
227 // connect/disconnect only 1 device at a time
228 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
229
Eric Laurente552edb2014-03-10 17:42:56 -0700230 // handle output devices
231 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700232 SortedVector <audio_io_handle_t> outputs;
233
Eric Laurent1afeecb2014-05-14 08:52:28 -0700234 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
235 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
237
Eric Laurente552edb2014-03-10 17:42:56 -0700238 // save a copy of the opened output descriptors before any output is opened or closed
239 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
240 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700241 switch (state)
242 {
243 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700244 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700245 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700246 ALOGW("setDeviceConnectionState() device already connected: %x", device);
247 return INVALID_OPERATION;
248 }
249 ALOGV("setDeviceConnectionState() connecting device %x", device);
250
Eric Laurente552edb2014-03-10 17:42:56 -0700251 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 index = mAvailableOutputDevices.add(devDesc);
253 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700254 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700255 if (module == 0) {
256 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
257 device);
258 mAvailableOutputDevices.remove(devDesc);
259 return INVALID_OPERATION;
260 }
261 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700262 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700263 } else {
264 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700265 }
266
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700267 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700268 mAvailableOutputDevices.remove(devDesc);
269 return INVALID_OPERATION;
270 }
271 // outputs should never be empty here
272 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
273 "checkOutputsForDevice() returned no outputs but status OK");
274 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
275 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700276 break;
277 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700278 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700279 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700280 ALOGW("setDeviceConnectionState() device not connected: %x", device);
281 return INVALID_OPERATION;
282 }
283
Paul McLean5c477aa2014-08-20 16:47:57 -0700284 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
285
286 // Set Disconnect to HALs
287 AudioParameter param = AudioParameter(address);
288 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
289 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
290
Eric Laurente552edb2014-03-10 17:42:56 -0700291 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700292 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700293
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700294 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700295 } break;
296
297 default:
298 ALOGE("setDeviceConnectionState() invalid state: %x", state);
299 return BAD_VALUE;
300 }
301
Eric Laurent3a4311c2014-03-17 12:00:47 -0700302 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
303 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700304 checkA2dpSuspend();
305 checkOutputForAllStrategies();
306 // outputs must be closed after checkOutputForAllStrategies() is executed
307 if (!outputs.isEmpty()) {
308 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700309 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700310 // close unused outputs after device disconnection or direct outputs that have been
311 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700312 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700313 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
314 (desc->mDirectOpenCount == 0))) {
315 closeOutput(outputs[i]);
316 }
317 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700318 // check again after closing A2DP output to reset mA2dpSuspended if needed
319 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700320 }
321
322 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700323 if (mPhoneState == AUDIO_MODE_IN_CALL) {
324 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
325 updateCallRouting(newDevice);
326 }
Eric Laurente552edb2014-03-10 17:42:56 -0700327 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 audio_io_handle_t output = mOutputs.keyAt(i);
329 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
330 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
331 true /*fromCache*/);
332 // do not force device change on duplicated output because if device is 0, it will
333 // also force a device 0 for the two outputs it is duplicated to which may override
334 // a valid device selection on those outputs.
335 bool force = !mOutputs.valueAt(i)->isDuplicated()
336 && (!deviceDistinguishesOnAddress(device)
337 // always force when disconnecting (a non-duplicated device)
338 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
339 setOutputDevice(output, newDevice, force, 0);
340 }
Eric Laurente552edb2014-03-10 17:42:56 -0700341 }
342
Eric Laurent72aa32f2014-05-30 18:51:48 -0700343 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700344 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700345 } // end if is output device
346
Eric Laurente552edb2014-03-10 17:42:56 -0700347 // handle input devices
348 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700349 SortedVector <audio_io_handle_t> inputs;
350
Eric Laurent1afeecb2014-05-14 08:52:28 -0700351 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
352 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700354 switch (state)
355 {
356 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700357 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700358 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700359 ALOGW("setDeviceConnectionState() device already connected: %d", device);
360 return INVALID_OPERATION;
361 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700362 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700363 if (module == NULL) {
364 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
365 device);
366 return INVALID_OPERATION;
367 }
Eric Laurentd4692962014-05-05 18:13:44 -0700368 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
369 return INVALID_OPERATION;
370 }
371
Eric Laurent3a4311c2014-03-17 12:00:47 -0700372 index = mAvailableInputDevices.add(devDesc);
373 if (index >= 0) {
374 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700375 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700376 } else {
377 return NO_MEMORY;
378 }
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700380
381 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700382 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700383 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700384 ALOGW("setDeviceConnectionState() device not connected: %d", device);
385 return INVALID_OPERATION;
386 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700387
388 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
389
390 // Set Disconnect to HALs
391 AudioParameter param = AudioParameter(address);
392 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
393 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
394
Eric Laurentd4692962014-05-05 18:13:44 -0700395 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700396 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700397
Eric Laurentd4692962014-05-05 18:13:44 -0700398 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700399
400 default:
401 ALOGE("setDeviceConnectionState() invalid state: %x", state);
402 return BAD_VALUE;
403 }
404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700406
Eric Laurentc2730ba2014-07-20 15:47:07 -0700407 if (mPhoneState == AUDIO_MODE_IN_CALL) {
408 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
409 updateCallRouting(newDevice);
410 }
411
Eric Laurentb52c1522014-05-20 11:27:36 -0700412 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700413 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700414 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700415
416 ALOGW("setDeviceConnectionState() invalid device: %x", device);
417 return BAD_VALUE;
418}
419
Eric Laurente0720872014-03-11 09:30:41 -0700420audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700421 const char *device_address)
422{
Eric Laurent3b73df72014-03-11 09:06:29 -0700423 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700424 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700425 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700426 // handle legacy remote submix case where the address was not always specified
427 if (deviceDistinguishesOnAddress(device) && (devDesc->mAddress.length() == 0)) {
428 devDesc->mAddress = String8("0");
429 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700430 ssize_t index;
431 DeviceVector *deviceVector;
432
Eric Laurente552edb2014-03-10 17:42:56 -0700433 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700435 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700436 deviceVector = &mAvailableInputDevices;
437 } else {
438 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
439 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700440 }
441
Eric Laurent3a4311c2014-03-17 12:00:47 -0700442 index = deviceVector->indexOf(devDesc);
443 if (index >= 0) {
444 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
445 } else {
446 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
447 }
Eric Laurente552edb2014-03-10 17:42:56 -0700448}
449
Eric Laurentc2730ba2014-07-20 15:47:07 -0700450void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
451{
452 bool createTxPatch = false;
453 struct audio_patch patch;
454 patch.num_sources = 1;
455 patch.num_sinks = 1;
456 status_t status;
457 audio_patch_handle_t afPatchHandle;
458 DeviceVector deviceList;
459
460 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
461 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
462
463 // release existing RX patch if any
464 if (mCallRxPatch != 0) {
465 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
466 mCallRxPatch.clear();
467 }
468 // release TX patch if any
469 if (mCallTxPatch != 0) {
470 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
471 mCallTxPatch.clear();
472 }
473
474 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
475 // via setOutputDevice() on primary output.
476 // Otherwise, create two audio patches for TX and RX path.
477 if (availablePrimaryOutputDevices() & rxDevice) {
478 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
479 // If the TX device is also on the primary HW module, setOutputDevice() will take care
480 // of it due to legacy implementation. If not, create a patch.
481 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
482 == AUDIO_DEVICE_NONE) {
483 createTxPatch = true;
484 }
485 } else {
486 // create RX path audio patch
487 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
488 ALOG_ASSERT(!deviceList.isEmpty(),
489 "updateCallRouting() selected device not in output device list");
490 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
491 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
492 ALOG_ASSERT(!deviceList.isEmpty(),
493 "updateCallRouting() no telephony RX device");
494 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
495
496 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
497 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
498
499 // request to reuse existing output stream if one is already opened to reach the RX device
500 SortedVector<audio_io_handle_t> outputs =
501 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700502 audio_io_handle_t output = selectOutput(outputs,
503 AUDIO_OUTPUT_FLAG_NONE,
504 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700505 if (output != AUDIO_IO_HANDLE_NONE) {
506 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
507 ALOG_ASSERT(!outputDesc->isDuplicated(),
508 "updateCallRouting() RX device output is duplicated");
509 outputDesc->toAudioPortConfig(&patch.sources[1]);
510 patch.num_sources = 2;
511 }
512
513 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
514 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
515 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
516 status);
517 if (status == NO_ERROR) {
518 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
519 &patch, mUidCached);
520 mCallRxPatch->mAfPatchHandle = afPatchHandle;
521 mCallRxPatch->mUid = mUidCached;
522 }
523 createTxPatch = true;
524 }
525 if (createTxPatch) {
526
527 struct audio_patch patch;
528 patch.num_sources = 1;
529 patch.num_sinks = 1;
530 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
531 ALOG_ASSERT(!deviceList.isEmpty(),
532 "updateCallRouting() selected device not in input device list");
533 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
534 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
535 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
536 ALOG_ASSERT(!deviceList.isEmpty(),
537 "updateCallRouting() no telephony TX device");
538 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
539 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
540
541 SortedVector<audio_io_handle_t> outputs =
542 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700543 audio_io_handle_t output = selectOutput(outputs,
544 AUDIO_OUTPUT_FLAG_NONE,
545 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700546 // request to reuse existing output stream if one is already opened to reach the TX
547 // path output device
548 if (output != AUDIO_IO_HANDLE_NONE) {
549 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
550 ALOG_ASSERT(!outputDesc->isDuplicated(),
551 "updateCallRouting() RX device output is duplicated");
552 outputDesc->toAudioPortConfig(&patch.sources[1]);
553 patch.num_sources = 2;
554 }
555
556 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
557 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
558 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
559 status);
560 if (status == NO_ERROR) {
561 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
562 &patch, mUidCached);
563 mCallTxPatch->mAfPatchHandle = afPatchHandle;
564 mCallTxPatch->mUid = mUidCached;
565 }
566 }
567}
568
Eric Laurente0720872014-03-11 09:30:41 -0700569void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700570{
571 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700572 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700573 ALOGW("setPhoneState() invalid state %d", state);
574 return;
575 }
576
577 if (state == mPhoneState ) {
578 ALOGW("setPhoneState() setting same state %d", state);
579 return;
580 }
581
582 // if leaving call state, handle special case of active streams
583 // pertaining to sonification strategy see handleIncallSonification()
584 if (isInCall()) {
585 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700586 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800587 if (stream == AUDIO_STREAM_PATCH) {
588 continue;
589 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700590 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700591 }
592 }
593
594 // store previous phone state for management of sonification strategy below
595 int oldState = mPhoneState;
596 mPhoneState = state;
597 bool force = false;
598
599 // are we entering or starting a call
600 if (!isStateInCall(oldState) && isStateInCall(state)) {
601 ALOGV(" Entering call in setPhoneState()");
602 // force routing command to audio hardware when starting a call
603 // even if no device change is needed
604 force = true;
605 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
606 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
607 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
608 }
609 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
610 ALOGV(" Exiting call in setPhoneState()");
611 // force routing command to audio hardware when exiting a call
612 // even if no device change is needed
613 force = true;
614 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
615 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
616 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
617 }
618 } else if (isStateInCall(state) && (state != oldState)) {
619 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
620 // force routing command to audio hardware when switching between telephony and VoIP
621 // even if no device change is needed
622 force = true;
623 }
624
625 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700626 checkA2dpSuspend();
627 checkOutputForAllStrategies();
628 updateDevicesAndOutputs();
629
Eric Laurent1f2f2232014-06-02 12:01:23 -0700630 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700631
Eric Laurente552edb2014-03-10 17:42:56 -0700632 int delayMs = 0;
633 if (isStateInCall(state)) {
634 nsecs_t sysTime = systemTime();
635 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700636 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700637 // mute media and sonification strategies and delay device switch by the largest
638 // latency of any output where either strategy is active.
639 // This avoid sending the ring tone or music tail into the earpiece or headset.
640 if ((desc->isStrategyActive(STRATEGY_MEDIA,
641 SONIFICATION_HEADSET_MUSIC_DELAY,
642 sysTime) ||
643 desc->isStrategyActive(STRATEGY_SONIFICATION,
644 SONIFICATION_HEADSET_MUSIC_DELAY,
645 sysTime)) &&
646 (delayMs < (int)desc->mLatency*2)) {
647 delayMs = desc->mLatency*2;
648 }
649 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
650 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
651 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
652 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
653 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
654 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
655 }
656 }
657
Eric Laurentc2730ba2014-07-20 15:47:07 -0700658 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
659 // the device returned is not necessarily reachable via this output
660 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
661 // force routing command to audio hardware when ending call
662 // even if no device change is needed
663 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
664 rxDevice = hwOutputDesc->device();
665 }
Eric Laurente552edb2014-03-10 17:42:56 -0700666
Eric Laurentc2730ba2014-07-20 15:47:07 -0700667 if (state == AUDIO_MODE_IN_CALL) {
668 updateCallRouting(rxDevice, delayMs);
669 } else if (oldState == AUDIO_MODE_IN_CALL) {
670 if (mCallRxPatch != 0) {
671 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
672 mCallRxPatch.clear();
673 }
674 if (mCallTxPatch != 0) {
675 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
676 mCallTxPatch.clear();
677 }
678 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
679 } else {
680 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
681 }
Eric Laurente552edb2014-03-10 17:42:56 -0700682 // if entering in call state, handle special case of active streams
683 // pertaining to sonification strategy see handleIncallSonification()
684 if (isStateInCall(state)) {
685 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700686 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800687 if (stream == AUDIO_STREAM_PATCH) {
688 continue;
689 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700690 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700691 }
692 }
693
694 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700695 if (state == AUDIO_MODE_RINGTONE &&
696 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700697 mLimitRingtoneVolume = true;
698 } else {
699 mLimitRingtoneVolume = false;
700 }
701}
702
Eric Laurente0720872014-03-11 09:30:41 -0700703void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700704 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700705{
706 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
707
708 bool forceVolumeReeval = false;
709 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700710 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
711 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
712 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700713 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
714 return;
715 }
716 forceVolumeReeval = true;
717 mForceUse[usage] = config;
718 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700719 case AUDIO_POLICY_FORCE_FOR_MEDIA:
720 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
721 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
722 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
723 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800724 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700725 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
726 return;
727 }
728 mForceUse[usage] = config;
729 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700730 case AUDIO_POLICY_FORCE_FOR_RECORD:
731 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
732 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700733 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
734 return;
735 }
736 mForceUse[usage] = config;
737 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700738 case AUDIO_POLICY_FORCE_FOR_DOCK:
739 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
740 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
741 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
742 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
743 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700744 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
745 }
746 forceVolumeReeval = true;
747 mForceUse[usage] = config;
748 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700749 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
750 if (config != AUDIO_POLICY_FORCE_NONE &&
751 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700752 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
753 }
754 forceVolumeReeval = true;
755 mForceUse[usage] = config;
756 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900757 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
758 if (config != AUDIO_POLICY_FORCE_NONE &&
759 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
760 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
761 }
762 mForceUse[usage] = config;
763 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700764 default:
765 ALOGW("setForceUse() invalid usage %d", usage);
766 break;
767 }
768
769 // check for device and output changes triggered by new force usage
770 checkA2dpSuspend();
771 checkOutputForAllStrategies();
772 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700773 if (mPhoneState == AUDIO_MODE_IN_CALL) {
774 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
775 updateCallRouting(newDevice);
776 }
Eric Laurente552edb2014-03-10 17:42:56 -0700777 for (size_t i = 0; i < mOutputs.size(); i++) {
778 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700779 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700780 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
781 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
782 }
Eric Laurente552edb2014-03-10 17:42:56 -0700783 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
784 applyStreamVolumes(output, newDevice, 0, true);
785 }
786 }
787
788 audio_io_handle_t activeInput = getActiveInput();
789 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700790 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700791 }
792
793}
794
Eric Laurente0720872014-03-11 09:30:41 -0700795audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700796{
797 return mForceUse[usage];
798}
799
Eric Laurente0720872014-03-11 09:30:41 -0700800void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700801{
802 ALOGV("setSystemProperty() property %s, value %s", property, value);
803}
804
805// Find a direct output profile compatible with the parameters passed, even if the input flags do
806// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700807sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700808 audio_devices_t device,
809 uint32_t samplingRate,
810 audio_format_t format,
811 audio_channel_mask_t channelMask,
812 audio_output_flags_t flags)
813{
814 for (size_t i = 0; i < mHwModules.size(); i++) {
815 if (mHwModules[i]->mHandle == 0) {
816 continue;
817 }
818 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700819 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent275e8e92014-11-30 15:14:47 -0800820 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -0700821 NULL /*updatedSamplingRate*/, format, channelMask,
822 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
823 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700824 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
825 return profile;
826 }
Eric Laurente552edb2014-03-10 17:42:56 -0700827 }
828 }
829 return 0;
830}
831
Eric Laurente0720872014-03-11 09:30:41 -0700832audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700833 uint32_t samplingRate,
834 audio_format_t format,
835 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700836 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700837 const audio_offload_info_t *offloadInfo)
838{
Eric Laurent3b73df72014-03-11 09:06:29 -0700839 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
841 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
842 device, stream, samplingRate, format, channelMask, flags);
843
Eric Laurente83b55d2014-11-14 10:06:21 -0800844 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
845 stream, samplingRate,format, channelMask,
846 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700847}
848
Eric Laurente83b55d2014-11-14 10:06:21 -0800849status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
850 audio_io_handle_t *output,
851 audio_session_t session,
852 audio_stream_type_t *stream,
853 uint32_t samplingRate,
854 audio_format_t format,
855 audio_channel_mask_t channelMask,
856 audio_output_flags_t flags,
857 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700858{
Eric Laurente83b55d2014-11-14 10:06:21 -0800859 audio_attributes_t attributes;
860 if (attr != NULL) {
861 if (!isValidAttributes(attr)) {
862 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
863 attr->usage, attr->content_type, attr->flags,
864 attr->tags);
865 return BAD_VALUE;
866 }
867 attributes = *attr;
868 } else {
869 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
870 ALOGE("getOutputForAttr(): invalid stream type");
871 return BAD_VALUE;
872 }
873 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700874 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800875
Eric Laurent275e8e92014-11-30 15:14:47 -0800876 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
877 sp<AudioOutputDescriptor> desc;
878 if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) {
879 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
880 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
881 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) ||
882 (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
883 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) {
884 desc = mPolicyMixes[i]->mOutput;
885 break;
886 }
887 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
888 strncmp(attributes.tags + strlen("addr="),
889 mPolicyMixes[i]->mMix.mRegistrationId.string(),
890 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
891 desc = mPolicyMixes[i]->mOutput;
892 break;
893 }
894 }
895 } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) {
896 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE &&
897 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
898 strncmp(attributes.tags + strlen("addr="),
899 mPolicyMixes[i]->mMix.mRegistrationId.string(),
900 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
901 desc = mPolicyMixes[i]->mOutput;
Eric Laurent275e8e92014-11-30 15:14:47 -0800902 }
903 }
904 if (desc != 0) {
905 if (!audio_is_linear_pcm(format)) {
906 return BAD_VALUE;
907 }
Eric Laurentc722f302014-12-10 11:21:49 -0800908 desc->mPolicyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -0800909 *stream = streamTypefromAttributesInt(&attributes);
910 *output = desc->mIoHandle;
911 ALOGV("getOutputForAttr() returns output %d", *output);
912 return NO_ERROR;
913 }
914 }
915 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
916 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
917 return BAD_VALUE;
918 }
919
Eric Laurent93c3d412014-08-01 14:48:35 -0700920 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800921 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700922
Eric Laurente83b55d2014-11-14 10:06:21 -0800923 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700924 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700925
Eric Laurente83b55d2014-11-14 10:06:21 -0800926 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700927 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
928 }
929
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700930 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700931 device, samplingRate, format, channelMask, flags);
932
Eric Laurente83b55d2014-11-14 10:06:21 -0800933 *stream = streamTypefromAttributesInt(&attributes);
934 *output = getOutputForDevice(device, session, *stream,
935 samplingRate, format, channelMask,
936 flags, offloadInfo);
937 if (*output == AUDIO_IO_HANDLE_NONE) {
938 return INVALID_OPERATION;
939 }
940 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700941}
942
943audio_io_handle_t AudioPolicyManager::getOutputForDevice(
944 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800945 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700946 audio_stream_type_t stream,
947 uint32_t samplingRate,
948 audio_format_t format,
949 audio_channel_mask_t channelMask,
950 audio_output_flags_t flags,
951 const audio_offload_info_t *offloadInfo)
952{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700953 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700954 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700955 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700956
Eric Laurente552edb2014-03-10 17:42:56 -0700957#ifdef AUDIO_POLICY_TEST
958 if (mCurOutput != 0) {
959 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
960 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
961
962 if (mTestOutputs[mCurOutput] == 0) {
963 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700964 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700965 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700966 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700967 outputDesc->mFlags =
968 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700969 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700970 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
971 config.sample_rate = mTestSamplingRate;
972 config.channel_mask = mTestChannels;
973 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700974 if (offloadInfo != NULL) {
975 config.offload_info = *offloadInfo;
976 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700977 status = mpClientInterface->openOutput(0,
978 &mTestOutputs[mCurOutput],
979 &config,
980 &outputDesc->mDevice,
981 String8(""),
982 &outputDesc->mLatency,
983 outputDesc->mFlags);
984 if (status == NO_ERROR) {
985 outputDesc->mSamplingRate = config.sample_rate;
986 outputDesc->mFormat = config.format;
987 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700988 AudioParameter outputCmd = AudioParameter();
989 outputCmd.addInt(String8("set_id"),mCurOutput);
990 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
991 addOutput(mTestOutputs[mCurOutput], outputDesc);
992 }
993 }
994 return mTestOutputs[mCurOutput];
995 }
996#endif //AUDIO_POLICY_TEST
997
998 // open a direct output if required by specified parameters
999 //force direct flag if offload flag is set: offloading implies a direct output stream
1000 // and all common behaviors are driven by checking only the direct flag
1001 // this should normally be set appropriately in the policy configuration file
1002 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001003 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001004 }
Eric Laurent93c3d412014-08-01 14:48:35 -07001005 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1006 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1007 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001008 // only allow deep buffering for music stream type
1009 if (stream != AUDIO_STREAM_MUSIC) {
1010 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1011 }
Eric Laurente552edb2014-03-10 17:42:56 -07001012
Eric Laurentb732cf52014-09-24 19:08:21 -07001013 sp<IOProfile> profile;
1014
1015 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001016 // and not explicitly requested
1017 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1018 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -07001019 audio_channel_count_from_out_mask(channelMask) <= 2) {
1020 goto non_direct_output;
1021 }
1022
Eric Laurente552edb2014-03-10 17:42:56 -07001023 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1024 // creating an offloaded track and tearing it down immediately after start when audioflinger
1025 // detects there is an active non offloadable effect.
1026 // FIXME: We should check the audio session here but we do not have it in this context.
1027 // This may prevent offloading in rare situations where effects are left active by apps
1028 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001029
Eric Laurente552edb2014-03-10 17:42:56 -07001030 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1031 !isNonOffloadableEffectEnabled()) {
1032 profile = getProfileForDirectOutput(device,
1033 samplingRate,
1034 format,
1035 channelMask,
1036 (audio_output_flags_t)flags);
1037 }
1038
Eric Laurent1c333e22014-05-20 10:48:17 -07001039 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001040 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -07001041
1042 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001043 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001044 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1045 outputDesc = desc;
1046 // reuse direct output if currently open and configured with same parameters
1047 if ((samplingRate == outputDesc->mSamplingRate) &&
1048 (format == outputDesc->mFormat) &&
1049 (channelMask == outputDesc->mChannelMask)) {
1050 outputDesc->mDirectOpenCount++;
1051 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1052 return mOutputs.keyAt(i);
1053 }
1054 }
1055 }
1056 // close direct output if currently open and configured with different parameters
1057 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001058 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001059 }
1060 outputDesc = new AudioOutputDescriptor(profile);
1061 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001062 outputDesc->mLatency = 0;
1063 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001064 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1065 config.sample_rate = samplingRate;
1066 config.channel_mask = channelMask;
1067 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001068 if (offloadInfo != NULL) {
1069 config.offload_info = *offloadInfo;
1070 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001071 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1072 &output,
1073 &config,
1074 &outputDesc->mDevice,
1075 String8(""),
1076 &outputDesc->mLatency,
1077 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001078
1079 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001080 if (status != NO_ERROR ||
1081 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1082 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1083 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001084 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1085 "format %d %d, channelMask %04x %04x", output, samplingRate,
1086 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1087 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001088 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001089 mpClientInterface->closeOutput(output);
1090 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001091 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001092 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001093 outputDesc->mSamplingRate = config.sample_rate;
1094 outputDesc->mChannelMask = config.channel_mask;
1095 outputDesc->mFormat = config.format;
1096 outputDesc->mRefCount[stream] = 0;
1097 outputDesc->mStopTime[stream] = 0;
1098 outputDesc->mDirectOpenCount = 1;
1099
Eric Laurente552edb2014-03-10 17:42:56 -07001100 audio_io_handle_t srcOutput = getOutputForEffect();
1101 addOutput(output, outputDesc);
1102 audio_io_handle_t dstOutput = getOutputForEffect();
1103 if (dstOutput == output) {
1104 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1105 }
1106 mPreviousOutputs = mOutputs;
1107 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001108 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001109 return output;
1110 }
1111
Eric Laurentb732cf52014-09-24 19:08:21 -07001112non_direct_output:
1113
Eric Laurente552edb2014-03-10 17:42:56 -07001114 // ignoring channel mask due to downmix capability in mixer
1115
1116 // open a non direct output
1117
1118 // for non direct outputs, only PCM is supported
1119 if (audio_is_linear_pcm(format)) {
1120 // get which output is suitable for the specified stream. The actual
1121 // routing change will happen when startOutput() will be called
1122 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1123
Eric Laurent8838a382014-09-08 16:44:28 -07001124 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1125 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1126 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001127 }
1128 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1129 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1130
1131 ALOGV("getOutput() returns output %d", output);
1132
1133 return output;
1134}
1135
Eric Laurente0720872014-03-11 09:30:41 -07001136audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001137 audio_output_flags_t flags,
1138 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001139{
1140 // select one output among several that provide a path to a particular device or set of
1141 // devices (the list was previously build by getOutputsForDevice()).
1142 // The priority is as follows:
1143 // 1: the output with the highest number of requested policy flags
1144 // 2: the primary output
1145 // 3: the first output in the list
1146
1147 if (outputs.size() == 0) {
1148 return 0;
1149 }
1150 if (outputs.size() == 1) {
1151 return outputs[0];
1152 }
1153
1154 int maxCommonFlags = 0;
1155 audio_io_handle_t outputFlags = 0;
1156 audio_io_handle_t outputPrimary = 0;
1157
1158 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001159 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001160 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001161 // if a valid format is specified, skip output if not compatible
1162 if (format != AUDIO_FORMAT_INVALID) {
1163 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1164 if (format != outputDesc->mFormat) {
1165 continue;
1166 }
1167 } else if (!audio_is_linear_pcm(format)) {
1168 continue;
1169 }
1170 }
1171
Eric Laurent3b73df72014-03-11 09:06:29 -07001172 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001173 if (commonFlags > maxCommonFlags) {
1174 outputFlags = outputs[i];
1175 maxCommonFlags = commonFlags;
1176 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1177 }
1178 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1179 outputPrimary = outputs[i];
1180 }
1181 }
1182 }
1183
1184 if (outputFlags != 0) {
1185 return outputFlags;
1186 }
1187 if (outputPrimary != 0) {
1188 return outputPrimary;
1189 }
1190
1191 return outputs[0];
1192}
1193
Eric Laurente0720872014-03-11 09:30:41 -07001194status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001195 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001196 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001197{
1198 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1199 ssize_t index = mOutputs.indexOfKey(output);
1200 if (index < 0) {
1201 ALOGW("startOutput() unknown output %d", output);
1202 return BAD_VALUE;
1203 }
1204
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001205 // cannot start playback of STREAM_TTS if any other output is being used
1206 uint32_t beaconMuteLatency = 0;
1207 if (stream == AUDIO_STREAM_TTS) {
1208 ALOGV("\t found BEACON stream");
1209 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1210 return INVALID_OPERATION;
1211 } else {
1212 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1213 }
1214 } else {
1215 // some playback other than beacon starts
1216 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1217 }
1218
Eric Laurent1f2f2232014-06-02 12:01:23 -07001219 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001220
1221 // increment usage count for this stream on the requested output:
1222 // NOTE that the usage count is the same for duplicated output and hardware output which is
1223 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1224 outputDesc->changeRefCount(stream, 1);
1225
1226 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001227 // starting an output being rerouted?
1228 audio_devices_t newDevice;
Eric Laurentc722f302014-12-10 11:21:49 -08001229 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001230 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1231 } else {
1232 newDevice = getNewOutputDevice(output, false /*fromCache*/);
1233 }
Eric Laurente552edb2014-03-10 17:42:56 -07001234 routing_strategy strategy = getStrategy(stream);
1235 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001236 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1237 (beaconMuteLatency > 0);
1238 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001239 bool force = false;
1240 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001241 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001242 if (desc != outputDesc) {
1243 // force a device change if any other output is managed by the same hw
1244 // module and has a current device selection that differs from selected device.
1245 // In this case, the audio HAL must receive the new device selection so that it can
1246 // change the device currently selected by the other active output.
1247 if (outputDesc->sharesHwModuleWith(desc) &&
1248 desc->device() != newDevice) {
1249 force = true;
1250 }
1251 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001252 // a notification so that audio focus effect can propagate, or that a mute/unmute
1253 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001254 uint32_t latency = desc->latency();
1255 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1256 waitMs = latency;
1257 }
1258 }
1259 }
1260 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1261
1262 // handle special case for sonification while in call
1263 if (isInCall()) {
1264 handleIncallSonification(stream, true, false);
1265 }
1266
1267 // apply volume rules for current stream and device if necessary
1268 checkAndSetVolume(stream,
1269 mStreams[stream].getVolumeIndex(newDevice),
1270 output,
1271 newDevice);
1272
1273 // update the outputs if starting an output with a stream that can affect notification
1274 // routing
1275 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001276
1277 // Automatically enable the remote submix input when output is started on a re routing mix
1278 // of type MIX_TYPE_RECORDERS
1279 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1280 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1281 setDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1282 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1283 outputDesc->mPolicyMix->mRegistrationId);
1284 }
1285
Eric Laurente552edb2014-03-10 17:42:56 -07001286 if (waitMs > muteWaitMs) {
1287 usleep((waitMs - muteWaitMs) * 2 * 1000);
1288 }
1289 }
1290 return NO_ERROR;
1291}
1292
1293
Eric Laurente0720872014-03-11 09:30:41 -07001294status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001295 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001296 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001297{
1298 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1299 ssize_t index = mOutputs.indexOfKey(output);
1300 if (index < 0) {
1301 ALOGW("stopOutput() unknown output %d", output);
1302 return BAD_VALUE;
1303 }
1304
Eric Laurent1f2f2232014-06-02 12:01:23 -07001305 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001306
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001307 // always handle stream stop, check which stream type is stopping
1308 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1309
Eric Laurente552edb2014-03-10 17:42:56 -07001310 // handle special case for sonification while in call
1311 if (isInCall()) {
1312 handleIncallSonification(stream, false, false);
1313 }
1314
1315 if (outputDesc->mRefCount[stream] > 0) {
1316 // decrement usage count of this stream on the output
1317 outputDesc->changeRefCount(stream, -1);
1318 // store time at which the stream was stopped - see isStreamActive()
1319 if (outputDesc->mRefCount[stream] == 0) {
Eric Laurentc722f302014-12-10 11:21:49 -08001320 // Automatically disable the remote submix input when output is stopped on a
1321 // re routing mix of type MIX_TYPE_RECORDERS
1322 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1323 outputDesc->mPolicyMix != NULL &&
1324 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1325 setDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1326 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1327 outputDesc->mPolicyMix->mRegistrationId);
1328 }
1329
Eric Laurente552edb2014-03-10 17:42:56 -07001330 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001331 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001332 // delay the device switch by twice the latency because stopOutput() is executed when
1333 // the track stop() command is received and at that time the audio track buffer can
1334 // still contain data that needs to be drained. The latency only covers the audio HAL
1335 // and kernel buffers. Also the latency does not always include additional delay in the
1336 // audio path (audio DSP, CODEC ...)
1337 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1338
1339 // force restoring the device selection on other active outputs if it differs from the
1340 // one being selected for this output
1341 for (size_t i = 0; i < mOutputs.size(); i++) {
1342 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001343 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001344 if (curOutput != output &&
1345 desc->isActive() &&
1346 outputDesc->sharesHwModuleWith(desc) &&
1347 (newDevice != desc->device())) {
1348 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001349 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001350 true,
1351 outputDesc->mLatency*2);
1352 }
1353 }
1354 // update the outputs if stopping one with a stream that can affect notification routing
1355 handleNotificationRoutingForStream(stream);
1356 }
1357 return NO_ERROR;
1358 } else {
1359 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1360 return INVALID_OPERATION;
1361 }
1362}
1363
Eric Laurente83b55d2014-11-14 10:06:21 -08001364void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001365 audio_stream_type_t stream __unused,
1366 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001367{
1368 ALOGV("releaseOutput() %d", output);
1369 ssize_t index = mOutputs.indexOfKey(output);
1370 if (index < 0) {
1371 ALOGW("releaseOutput() releasing unknown output %d", output);
1372 return;
1373 }
1374
1375#ifdef AUDIO_POLICY_TEST
1376 int testIndex = testOutputIndex(output);
1377 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001378 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001379 if (outputDesc->isActive()) {
1380 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001381 mOutputs.removeItem(output);
1382 mTestOutputs[testIndex] = 0;
1383 }
1384 return;
1385 }
1386#endif //AUDIO_POLICY_TEST
1387
Eric Laurent1f2f2232014-06-02 12:01:23 -07001388 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001389 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001390 if (desc->mDirectOpenCount <= 0) {
1391 ALOGW("releaseOutput() invalid open count %d for output %d",
1392 desc->mDirectOpenCount, output);
1393 return;
1394 }
1395 if (--desc->mDirectOpenCount == 0) {
1396 closeOutput(output);
1397 // If effects where present on the output, audioflinger moved them to the primary
1398 // output by default: move them back to the appropriate output.
1399 audio_io_handle_t dstOutput = getOutputForEffect();
1400 if (dstOutput != mPrimaryOutput) {
1401 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1402 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001403 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001404 }
1405 }
1406}
1407
1408
Eric Laurentcaf7f482014-11-25 17:50:47 -08001409status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1410 audio_io_handle_t *input,
1411 audio_session_t session,
1412 uint32_t samplingRate,
1413 audio_format_t format,
1414 audio_channel_mask_t channelMask,
1415 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001416{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001417 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1418 "session %d, flags %#x",
1419 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001420
Eric Laurentcaf7f482014-11-25 17:50:47 -08001421 *input = AUDIO_IO_HANDLE_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001422 audio_devices_t device;
1423 // handle legacy remote submix case where the address was not always specified
1424 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001425 bool isSoundTrigger = false;
Eric Laurentcaf7f482014-11-25 17:50:47 -08001426 audio_source_t halInputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001427 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001428
1429 if (attr->source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1430 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1431 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1432 address = String8(attr->tags + strlen("addr="));
1433 ssize_t index = mPolicyMixes.indexOfKey(address);
1434 if (index < 0) {
1435 ALOGW("getInputForAttr() no policy for address %s", address.string());
1436 return BAD_VALUE;
1437 }
Eric Laurentc722f302014-12-10 11:21:49 -08001438 if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) {
1439 ALOGW("getInputForAttr() bad policy mix type for address %s", address.string());
1440 return BAD_VALUE;
1441 }
1442 policyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08001443 } else {
Eric Laurentc722f302014-12-10 11:21:49 -08001444 device = getDeviceForInputSource(attr->source, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001445 if (device == AUDIO_DEVICE_NONE) {
1446 ALOGW("getInputForAttr() could not find device for source %d", attr->source);
1447 return BAD_VALUE;
1448 }
Eric Laurentc722f302014-12-10 11:21:49 -08001449 if (policyMix != NULL) {
1450 address = policyMix->mRegistrationId;
1451 } else if (audio_is_remote_submix_device(device)) {
1452 address = String8("0");
1453 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001454 // adapt channel selection to input source
1455 switch (attr->source) {
1456 case AUDIO_SOURCE_VOICE_UPLINK:
1457 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1458 break;
1459 case AUDIO_SOURCE_VOICE_DOWNLINK:
1460 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1461 break;
1462 case AUDIO_SOURCE_VOICE_CALL:
1463 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1464 break;
1465 default:
1466 break;
1467 }
1468 if (attr->source == AUDIO_SOURCE_HOTWORD) {
1469 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1470 if (index >= 0) {
1471 *input = mSoundTriggerSessions.valueFor(session);
1472 isSoundTrigger = true;
1473 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1474 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1475 } else {
1476 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1477 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001478 }
1479 }
1480
Eric Laurent275e8e92014-11-30 15:14:47 -08001481 sp<IOProfile> profile = getInputProfile(device, address,
1482 samplingRate, format, channelMask,
1483 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001484 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001485 //retry without flags
1486 audio_input_flags_t log_flags = flags;
1487 flags = AUDIO_INPUT_FLAG_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001488 profile = getInputProfile(device, address,
1489 samplingRate, format, channelMask,
1490 flags);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001491 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001492 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1493 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001494 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001495 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001496 }
Eric Laurente552edb2014-03-10 17:42:56 -07001497 }
1498
1499 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001500 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1501 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001502 }
1503
1504 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1505 config.sample_rate = samplingRate;
1506 config.channel_mask = channelMask;
1507 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001508
Eric Laurentcf2c0212014-07-25 16:20:43 -07001509 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001510 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001511 &config,
1512 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001513 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001514 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001515 flags);
1516
1517 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001518 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001519 (samplingRate != config.sample_rate) ||
1520 (format != config.format) ||
1521 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001522 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001523 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001524 if (*input != AUDIO_IO_HANDLE_NONE) {
1525 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001526 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001527 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001528 }
1529
Eric Laurent1f2f2232014-06-02 12:01:23 -07001530 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001531 inputDesc->mInputSource = attr->source;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001532 inputDesc->mRefCount = 0;
1533 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001534 inputDesc->mSamplingRate = samplingRate;
1535 inputDesc->mFormat = format;
1536 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001537 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001538 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001539 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001540 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001541
Eric Laurentcaf7f482014-11-25 17:50:47 -08001542 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001543 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001544 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001545}
1546
Eric Laurent4dc68062014-07-28 17:26:49 -07001547status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1548 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001549{
1550 ALOGV("startInput() input %d", input);
1551 ssize_t index = mInputs.indexOfKey(input);
1552 if (index < 0) {
1553 ALOGW("startInput() unknown input %d", input);
1554 return BAD_VALUE;
1555 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001556 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001557
Eric Laurentc722f302014-12-10 11:21:49 -08001558 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001559 if (index < 0) {
1560 ALOGW("startInput() unknown session %d on input %d", session, input);
1561 return BAD_VALUE;
1562 }
1563
Glenn Kasten74a8e252014-07-24 14:09:55 -07001564 // virtual input devices are compatible with other input devices
1565 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1566
1567 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001568 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001569 if (activeInput != 0 && activeInput != input) {
1570
1571 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1572 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001573 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001574 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001575 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurentc722f302014-12-10 11:21:49 -08001576 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1577 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001578 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001579 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001580 return INVALID_OPERATION;
1581 }
1582 }
1583 }
1584
Glenn Kasten74a8e252014-07-24 14:09:55 -07001585 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001586 if (activeInputsCount() == 0) {
1587 SoundTrigger::setCaptureState(true);
1588 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001589 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001590
Eric Laurentc722f302014-12-10 11:21:49 -08001591 // automatically enable the remote submix output when input is started if not
1592 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001593 // For remote submix (a virtual device), we open only one input per capture request.
1594 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001595 String8 address = String8("");
1596 if (inputDesc->mPolicyMix == NULL) {
1597 address = String8("0");
1598 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1599 address = inputDesc->mPolicyMix->mRegistrationId;
1600 }
1601 if (address != "") {
1602 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1603 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1604 address);
1605 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001606 }
Eric Laurente552edb2014-03-10 17:42:56 -07001607 }
1608
Eric Laurente552edb2014-03-10 17:42:56 -07001609 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1610
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001611 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001612 return NO_ERROR;
1613}
1614
Eric Laurent4dc68062014-07-28 17:26:49 -07001615status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1616 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001617{
1618 ALOGV("stopInput() input %d", input);
1619 ssize_t index = mInputs.indexOfKey(input);
1620 if (index < 0) {
1621 ALOGW("stopInput() unknown input %d", input);
1622 return BAD_VALUE;
1623 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001624 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001625
Eric Laurentc722f302014-12-10 11:21:49 -08001626 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001627 if (index < 0) {
1628 ALOGW("stopInput() unknown session %d on input %d", session, input);
1629 return BAD_VALUE;
1630 }
1631
Eric Laurente552edb2014-03-10 17:42:56 -07001632 if (inputDesc->mRefCount == 0) {
1633 ALOGW("stopInput() input %d already stopped", input);
1634 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001635 }
1636
1637 inputDesc->mRefCount--;
1638 if (inputDesc->mRefCount == 0) {
1639
Eric Laurentc722f302014-12-10 11:21:49 -08001640 // automatically disable the remote submix output when input is stopped if not
1641 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001642 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001643 String8 address = String8("");
1644 if (inputDesc->mPolicyMix == NULL) {
1645 address = String8("0");
1646 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1647 address = inputDesc->mPolicyMix->mRegistrationId;
1648 }
1649 if (address != "") {
1650 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1651 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1652 address);
1653 }
Eric Laurente552edb2014-03-10 17:42:56 -07001654 }
1655
Eric Laurent1c333e22014-05-20 10:48:17 -07001656 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001657
1658 if (activeInputsCount() == 0) {
1659 SoundTrigger::setCaptureState(false);
1660 }
Eric Laurente552edb2014-03-10 17:42:56 -07001661 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001662 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001663}
1664
Eric Laurent4dc68062014-07-28 17:26:49 -07001665void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1666 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001667{
1668 ALOGV("releaseInput() %d", input);
1669 ssize_t index = mInputs.indexOfKey(input);
1670 if (index < 0) {
1671 ALOGW("releaseInput() releasing unknown input %d", input);
1672 return;
1673 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001674 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1675 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001676
Eric Laurentc722f302014-12-10 11:21:49 -08001677 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001678 if (index < 0) {
1679 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1680 return;
1681 }
Eric Laurentc722f302014-12-10 11:21:49 -08001682 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001683 if (inputDesc->mOpenRefCount == 0) {
1684 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1685 return;
1686 }
1687 inputDesc->mOpenRefCount--;
1688 if (inputDesc->mOpenRefCount > 0) {
1689 ALOGV("releaseInput() exit > 0");
1690 return;
1691 }
1692
Eric Laurent05b90f82014-08-27 15:32:29 -07001693 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001694 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001695 ALOGV("releaseInput() exit");
1696}
1697
Eric Laurentd4692962014-05-05 18:13:44 -07001698void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001699 bool patchRemoved = false;
1700
Eric Laurentd4692962014-05-05 18:13:44 -07001701 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001702 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1703 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1704 if (patch_index >= 0) {
1705 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1706 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1707 mAudioPatches.removeItemsAt(patch_index);
1708 patchRemoved = true;
1709 }
Eric Laurentd4692962014-05-05 18:13:44 -07001710 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1711 }
1712 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001713 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001714
1715 if (patchRemoved) {
1716 mpClientInterface->onAudioPatchListUpdate();
1717 }
Eric Laurentd4692962014-05-05 18:13:44 -07001718}
1719
Eric Laurente0720872014-03-11 09:30:41 -07001720void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001721 int indexMin,
1722 int indexMax)
1723{
1724 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1725 if (indexMin < 0 || indexMin >= indexMax) {
1726 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1727 return;
1728 }
1729 mStreams[stream].mIndexMin = indexMin;
1730 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001731 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1732 if (stream == AUDIO_STREAM_MUSIC) {
1733 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1734 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1735 }
Eric Laurente552edb2014-03-10 17:42:56 -07001736}
1737
Eric Laurente0720872014-03-11 09:30:41 -07001738status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001739 int index,
1740 audio_devices_t device)
1741{
1742
1743 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1744 return BAD_VALUE;
1745 }
1746 if (!audio_is_output_device(device)) {
1747 return BAD_VALUE;
1748 }
1749
1750 // Force max volume if stream cannot be muted
1751 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1752
1753 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1754 stream, device, index);
1755
1756 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1757 // clear all device specific values
1758 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1759 mStreams[stream].mIndexCur.clear();
1760 }
1761 mStreams[stream].mIndexCur.add(device, index);
1762
Eric Laurent31551f82014-10-10 18:21:56 -07001763 // update volume on all outputs whose current device is also selected by the same
1764 // strategy as the device specified by the caller
1765 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001766
1767
1768 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1769 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1770 if (stream == AUDIO_STREAM_MUSIC) {
1771 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1772 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1773 }
1774 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1775 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001776 return NO_ERROR;
1777 }
Eric Laurente552edb2014-03-10 17:42:56 -07001778 status_t status = NO_ERROR;
1779 for (size_t i = 0; i < mOutputs.size(); i++) {
1780 audio_devices_t curDevice =
1781 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001782 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001783 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1784 if (volStatus != NO_ERROR) {
1785 status = volStatus;
1786 }
1787 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001788 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1789 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1790 index, mOutputs.keyAt(i), curDevice);
1791 }
Eric Laurente552edb2014-03-10 17:42:56 -07001792 }
1793 return status;
1794}
1795
Eric Laurente0720872014-03-11 09:30:41 -07001796status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001797 int *index,
1798 audio_devices_t device)
1799{
1800 if (index == NULL) {
1801 return BAD_VALUE;
1802 }
1803 if (!audio_is_output_device(device)) {
1804 return BAD_VALUE;
1805 }
1806 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1807 // the strategy the stream belongs to.
1808 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1809 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1810 }
1811 device = getDeviceForVolume(device);
1812
1813 *index = mStreams[stream].getVolumeIndex(device);
1814 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1815 return NO_ERROR;
1816}
1817
Eric Laurente0720872014-03-11 09:30:41 -07001818audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001819 const SortedVector<audio_io_handle_t>& outputs)
1820{
1821 // select one output among several suitable for global effects.
1822 // The priority is as follows:
1823 // 1: An offloaded output. If the effect ends up not being offloadable,
1824 // AudioFlinger will invalidate the track and the offloaded output
1825 // will be closed causing the effect to be moved to a PCM output.
1826 // 2: A deep buffer output
1827 // 3: the first output in the list
1828
1829 if (outputs.size() == 0) {
1830 return 0;
1831 }
1832
1833 audio_io_handle_t outputOffloaded = 0;
1834 audio_io_handle_t outputDeepBuffer = 0;
1835
1836 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001837 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001838 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001839 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1840 outputOffloaded = outputs[i];
1841 }
1842 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1843 outputDeepBuffer = outputs[i];
1844 }
1845 }
1846
1847 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1848 outputOffloaded, outputDeepBuffer);
1849 if (outputOffloaded != 0) {
1850 return outputOffloaded;
1851 }
1852 if (outputDeepBuffer != 0) {
1853 return outputDeepBuffer;
1854 }
1855
1856 return outputs[0];
1857}
1858
Eric Laurente0720872014-03-11 09:30:41 -07001859audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001860{
1861 // apply simple rule where global effects are attached to the same output as MUSIC streams
1862
Eric Laurent3b73df72014-03-11 09:06:29 -07001863 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001864 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1865 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1866
1867 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1868 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1869 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1870
1871 return output;
1872}
1873
Eric Laurente0720872014-03-11 09:30:41 -07001874status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001875 audio_io_handle_t io,
1876 uint32_t strategy,
1877 int session,
1878 int id)
1879{
1880 ssize_t index = mOutputs.indexOfKey(io);
1881 if (index < 0) {
1882 index = mInputs.indexOfKey(io);
1883 if (index < 0) {
1884 ALOGW("registerEffect() unknown io %d", io);
1885 return INVALID_OPERATION;
1886 }
1887 }
1888
1889 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1890 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1891 desc->name, desc->memoryUsage);
1892 return INVALID_OPERATION;
1893 }
1894 mTotalEffectsMemory += desc->memoryUsage;
1895 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1896 desc->name, io, strategy, session, id);
1897 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1898
Eric Laurent1f2f2232014-06-02 12:01:23 -07001899 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1900 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1901 effectDesc->mIo = io;
1902 effectDesc->mStrategy = (routing_strategy)strategy;
1903 effectDesc->mSession = session;
1904 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001905
Eric Laurent1f2f2232014-06-02 12:01:23 -07001906 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001907
1908 return NO_ERROR;
1909}
1910
Eric Laurente0720872014-03-11 09:30:41 -07001911status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001912{
1913 ssize_t index = mEffects.indexOfKey(id);
1914 if (index < 0) {
1915 ALOGW("unregisterEffect() unknown effect ID %d", id);
1916 return INVALID_OPERATION;
1917 }
1918
Eric Laurent1f2f2232014-06-02 12:01:23 -07001919 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001920
Eric Laurent1f2f2232014-06-02 12:01:23 -07001921 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001922
Eric Laurent1f2f2232014-06-02 12:01:23 -07001923 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001924 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001925 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1926 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001927 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001928 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001929 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001930 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001931
1932 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001933
1934 return NO_ERROR;
1935}
1936
Eric Laurente0720872014-03-11 09:30:41 -07001937status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001938{
1939 ssize_t index = mEffects.indexOfKey(id);
1940 if (index < 0) {
1941 ALOGW("unregisterEffect() unknown effect ID %d", id);
1942 return INVALID_OPERATION;
1943 }
1944
1945 return setEffectEnabled(mEffects.valueAt(index), enabled);
1946}
1947
Eric Laurent1f2f2232014-06-02 12:01:23 -07001948status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001949{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001950 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001951 ALOGV("setEffectEnabled(%s) effect already %s",
1952 enabled?"true":"false", enabled?"enabled":"disabled");
1953 return INVALID_OPERATION;
1954 }
1955
1956 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001957 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001958 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001959 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001960 return INVALID_OPERATION;
1961 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001962 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001963 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1964 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001965 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001966 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001967 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1968 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001969 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001970 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001971 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1972 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001973 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001974 return NO_ERROR;
1975}
1976
Eric Laurente0720872014-03-11 09:30:41 -07001977bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001978{
1979 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001980 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1981 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1982 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001983 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001984 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001985 return true;
1986 }
1987 }
1988 return false;
1989}
1990
Eric Laurente0720872014-03-11 09:30:41 -07001991bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001992{
1993 nsecs_t sysTime = systemTime();
1994 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001995 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001996 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001997 return true;
1998 }
1999 }
2000 return false;
2001}
2002
Eric Laurente0720872014-03-11 09:30:41 -07002003bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07002004 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002005{
2006 nsecs_t sysTime = systemTime();
2007 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002008 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002009 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002010 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurentc722f302014-12-10 11:21:49 -08002011 // do not consider re routing (when the output is going to a dynamic policy)
2012 // as "remote playback"
2013 if (outputDesc->mPolicyMix == NULL) {
Jean-Michel Trivi1767df72014-12-09 18:11:49 -08002014 return true;
2015 }
Eric Laurente552edb2014-03-10 17:42:56 -07002016 }
2017 }
2018 return false;
2019}
2020
Eric Laurente0720872014-03-11 09:30:41 -07002021bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002022{
2023 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002024 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002025 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07002026 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07002027 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
2028 && (inputDescriptor->mRefCount > 0)) {
2029 return true;
2030 }
2031 }
2032 return false;
2033}
2034
Eric Laurent275e8e92014-11-30 15:14:47 -08002035// Register a list of custom mixes with their attributes and format.
2036// When a mix is registered, corresponding input and output profiles are
2037// added to the remote submix hw module. The profile contains only the
2038// parameters (sampling rate, format...) specified by the mix.
2039// The corresponding input remote submix device is also connected.
2040//
2041// When a remote submix device is connected, the address is checked to select the
2042// appropriate profile and the corresponding input or output stream is opened.
2043//
2044// When capture starts, getInputForAttr() will:
2045// - 1 look for a mix matching the address passed in attribtutes tags if any
2046// - 2 if none found, getDeviceForInputSource() will:
2047// - 2.1 look for a mix matching the attributes source
2048// - 2.2 if none found, default to device selection by policy rules
2049// At this time, the corresponding output remote submix device is also connected
2050// and active playback use cases can be transferred to this mix if needed when reconnecting
2051// after AudioTracks are invalidated
2052//
2053// When playback starts, getOutputForAttr() will:
2054// - 1 look for a mix matching the address passed in attribtutes tags if any
2055// - 2 if none found, look for a mix matching the attributes usage
2056// - 3 if none found, default to device and output selection by policy rules.
2057
2058status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2059{
2060 sp<HwModule> module;
2061 for (size_t i = 0; i < mHwModules.size(); i++) {
2062 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2063 mHwModules[i]->mHandle != 0) {
2064 module = mHwModules[i];
2065 break;
2066 }
2067 }
2068
2069 if (module == 0) {
2070 return INVALID_OPERATION;
2071 }
2072
2073 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2074
2075 for (size_t i = 0; i < mixes.size(); i++) {
2076 String8 address = mixes[i].mRegistrationId;
2077 ssize_t index = mPolicyMixes.indexOfKey(address);
2078 if (index >= 0) {
2079 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2080 continue;
2081 }
2082 audio_config_t outputConfig = mixes[i].mFormat;
2083 audio_config_t inputConfig = mixes[i].mFormat;
2084 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2085 // stereo and let audio flinger do the channel conversion if needed.
2086 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2087 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2088 module->addOutputProfile(address, &outputConfig,
2089 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2090 module->addInputProfile(address, &inputConfig,
2091 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2092 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2093 policyMix->mMix = mixes[i];
2094 mPolicyMixes.add(address, policyMix);
Eric Laurentc722f302014-12-10 11:21:49 -08002095 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2096 setDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2097 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2098 address.string());
2099 } else {
2100 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2101 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2102 address.string());
2103 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002104 }
2105 return NO_ERROR;
2106}
2107
2108status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2109{
2110 sp<HwModule> module;
2111 for (size_t i = 0; i < mHwModules.size(); i++) {
2112 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2113 mHwModules[i]->mHandle != 0) {
2114 module = mHwModules[i];
2115 break;
2116 }
2117 }
2118
2119 if (module == 0) {
2120 return INVALID_OPERATION;
2121 }
2122
2123 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2124
2125 for (size_t i = 0; i < mixes.size(); i++) {
2126 String8 address = mixes[i].mRegistrationId;
2127 ssize_t index = mPolicyMixes.indexOfKey(address);
2128 if (index < 0) {
2129 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2130 continue;
2131 }
2132
2133 mPolicyMixes.removeItemsAt(index);
2134
Eric Laurentc722f302014-12-10 11:21:49 -08002135 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2136 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2137 {
2138 setDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2139 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2140 address.string());
2141 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002142
2143 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2144 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2145 {
2146 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2147 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2148 address.string());
2149 }
2150 module->removeOutputProfile(address);
2151 module->removeInputProfile(address);
2152 }
2153 return NO_ERROR;
2154}
2155
Eric Laurente552edb2014-03-10 17:42:56 -07002156
Eric Laurente0720872014-03-11 09:30:41 -07002157status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002158{
2159 const size_t SIZE = 256;
2160 char buffer[SIZE];
2161 String8 result;
2162
2163 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2164 result.append(buffer);
2165
2166 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2167 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002168 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2169 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002170 snprintf(buffer, SIZE, " Force use for communications %d\n",
2171 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002172 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002173 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002174 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002175 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07002176 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002177 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07002178 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002179 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002180 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002181 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2182 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2183 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002184
Eric Laurent3a4311c2014-03-17 12:00:47 -07002185 snprintf(buffer, SIZE, " Available output devices:\n");
2186 result.append(buffer);
2187 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002188 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002189 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002190 }
2191 snprintf(buffer, SIZE, "\n Available input devices:\n");
2192 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002193 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002194 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002195 }
Eric Laurente552edb2014-03-10 17:42:56 -07002196
2197 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2198 write(fd, buffer, strlen(buffer));
2199 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002200 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002201 write(fd, buffer, strlen(buffer));
2202 mHwModules[i]->dump(fd);
2203 }
2204
2205 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2206 write(fd, buffer, strlen(buffer));
2207 for (size_t i = 0; i < mOutputs.size(); i++) {
2208 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2209 write(fd, buffer, strlen(buffer));
2210 mOutputs.valueAt(i)->dump(fd);
2211 }
2212
2213 snprintf(buffer, SIZE, "\nInputs dump:\n");
2214 write(fd, buffer, strlen(buffer));
2215 for (size_t i = 0; i < mInputs.size(); i++) {
2216 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2217 write(fd, buffer, strlen(buffer));
2218 mInputs.valueAt(i)->dump(fd);
2219 }
2220
2221 snprintf(buffer, SIZE, "\nStreams dump:\n");
2222 write(fd, buffer, strlen(buffer));
2223 snprintf(buffer, SIZE,
2224 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2225 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002226 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002227 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002228 write(fd, buffer, strlen(buffer));
2229 mStreams[i].dump(fd);
2230 }
2231
2232 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2233 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2234 write(fd, buffer, strlen(buffer));
2235
2236 snprintf(buffer, SIZE, "Registered effects:\n");
2237 write(fd, buffer, strlen(buffer));
2238 for (size_t i = 0; i < mEffects.size(); i++) {
2239 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2240 write(fd, buffer, strlen(buffer));
2241 mEffects.valueAt(i)->dump(fd);
2242 }
2243
Eric Laurent4d416952014-08-10 14:07:09 -07002244 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2245 write(fd, buffer, strlen(buffer));
2246 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2247 mAudioPatches[i]->dump(fd, 2, i);
2248 }
Eric Laurente552edb2014-03-10 17:42:56 -07002249
2250 return NO_ERROR;
2251}
2252
2253// This function checks for the parameters which can be offloaded.
2254// This can be enhanced depending on the capability of the DSP and policy
2255// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002256bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002257{
2258 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002259 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002260 offloadInfo.sample_rate, offloadInfo.channel_mask,
2261 offloadInfo.format,
2262 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2263 offloadInfo.has_video);
2264
2265 // Check if offload has been disabled
2266 char propValue[PROPERTY_VALUE_MAX];
2267 if (property_get("audio.offload.disable", propValue, "0")) {
2268 if (atoi(propValue) != 0) {
2269 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2270 return false;
2271 }
2272 }
2273
2274 // Check if stream type is music, then only allow offload as of now.
2275 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2276 {
2277 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2278 return false;
2279 }
2280
2281 //TODO: enable audio offloading with video when ready
2282 if (offloadInfo.has_video)
2283 {
2284 ALOGV("isOffloadSupported: has_video == true, returning false");
2285 return false;
2286 }
2287
2288 //If duration is less than minimum value defined in property, return false
2289 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2290 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2291 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2292 return false;
2293 }
2294 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2295 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2296 return false;
2297 }
2298
2299 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2300 // creating an offloaded track and tearing it down immediately after start when audioflinger
2301 // detects there is an active non offloadable effect.
2302 // FIXME: We should check the audio session here but we do not have it in this context.
2303 // This may prevent offloading in rare situations where effects are left active by apps
2304 // in the background.
2305 if (isNonOffloadableEffectEnabled()) {
2306 return false;
2307 }
2308
2309 // See if there is a profile to support this.
2310 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002311 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002312 offloadInfo.sample_rate,
2313 offloadInfo.format,
2314 offloadInfo.channel_mask,
2315 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002316 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2317 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002318}
2319
Eric Laurent6a94d692014-05-20 11:18:06 -07002320status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2321 audio_port_type_t type,
2322 unsigned int *num_ports,
2323 struct audio_port *ports,
2324 unsigned int *generation)
2325{
2326 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2327 generation == NULL) {
2328 return BAD_VALUE;
2329 }
2330 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2331 if (ports == NULL) {
2332 *num_ports = 0;
2333 }
2334
2335 size_t portsWritten = 0;
2336 size_t portsMax = *num_ports;
2337 *num_ports = 0;
2338 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2339 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2340 for (size_t i = 0;
2341 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2342 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2343 }
2344 *num_ports += mAvailableOutputDevices.size();
2345 }
2346 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2347 for (size_t i = 0;
2348 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2349 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2350 }
2351 *num_ports += mAvailableInputDevices.size();
2352 }
2353 }
2354 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2355 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2356 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2357 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2358 }
2359 *num_ports += mInputs.size();
2360 }
2361 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002362 size_t numOutputs = 0;
2363 for (size_t i = 0; i < mOutputs.size(); i++) {
2364 if (!mOutputs[i]->isDuplicated()) {
2365 numOutputs++;
2366 if (portsWritten < portsMax) {
2367 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2368 }
2369 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002370 }
Eric Laurent84c70242014-06-23 08:46:27 -07002371 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002372 }
2373 }
2374 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002375 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002376 return NO_ERROR;
2377}
2378
2379status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2380{
2381 return NO_ERROR;
2382}
2383
Eric Laurent1f2f2232014-06-02 12:01:23 -07002384sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002385 audio_port_handle_t id) const
2386{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002387 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002388 for (size_t i = 0; i < mOutputs.size(); i++) {
2389 outputDesc = mOutputs.valueAt(i);
2390 if (outputDesc->mId == id) {
2391 break;
2392 }
2393 }
2394 return outputDesc;
2395}
2396
Eric Laurent1f2f2232014-06-02 12:01:23 -07002397sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002398 audio_port_handle_t id) const
2399{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002400 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002401 for (size_t i = 0; i < mInputs.size(); i++) {
2402 inputDesc = mInputs.valueAt(i);
2403 if (inputDesc->mId == id) {
2404 break;
2405 }
2406 }
2407 return inputDesc;
2408}
2409
Eric Laurent1f2f2232014-06-02 12:01:23 -07002410sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2411 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002412{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002413 sp <HwModule> module;
2414
Eric Laurent6a94d692014-05-20 11:18:06 -07002415 for (size_t i = 0; i < mHwModules.size(); i++) {
2416 if (mHwModules[i]->mHandle == 0) {
2417 continue;
2418 }
2419 if (audio_is_output_device(device)) {
2420 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2421 {
2422 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2423 return mHwModules[i];
2424 }
2425 }
2426 } else {
2427 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2428 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2429 device & ~AUDIO_DEVICE_BIT_IN) {
2430 return mHwModules[i];
2431 }
2432 }
2433 }
2434 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002435 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002436}
2437
Eric Laurent1f2f2232014-06-02 12:01:23 -07002438sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002439{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002440 sp <HwModule> module;
2441
Eric Laurent1afeecb2014-05-14 08:52:28 -07002442 for (size_t i = 0; i < mHwModules.size(); i++)
2443 {
2444 if (strcmp(mHwModules[i]->mName, name) == 0) {
2445 return mHwModules[i];
2446 }
2447 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002448 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002449}
2450
Eric Laurentc2730ba2014-07-20 15:47:07 -07002451audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2452{
2453 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2454 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2455 return devices & mAvailableOutputDevices.types();
2456}
2457
2458audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2459{
2460 audio_module_handle_t primaryHandle =
2461 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2462 audio_devices_t devices = AUDIO_DEVICE_NONE;
2463 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2464 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2465 devices |= mAvailableInputDevices[i]->mDeviceType;
2466 }
2467 }
2468 return devices;
2469}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002470
Eric Laurent6a94d692014-05-20 11:18:06 -07002471status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2472 audio_patch_handle_t *handle,
2473 uid_t uid)
2474{
2475 ALOGV("createAudioPatch()");
2476
2477 if (handle == NULL || patch == NULL) {
2478 return BAD_VALUE;
2479 }
2480 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2481
Eric Laurent874c42872014-08-08 15:13:39 -07002482 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2483 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2484 return BAD_VALUE;
2485 }
2486 // only one source per audio patch supported for now
2487 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002488 return INVALID_OPERATION;
2489 }
Eric Laurent874c42872014-08-08 15:13:39 -07002490
2491 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002492 return INVALID_OPERATION;
2493 }
Eric Laurent874c42872014-08-08 15:13:39 -07002494 for (size_t i = 0; i < patch->num_sinks; i++) {
2495 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2496 return INVALID_OPERATION;
2497 }
2498 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002499
2500 sp<AudioPatch> patchDesc;
2501 ssize_t index = mAudioPatches.indexOfKey(*handle);
2502
Eric Laurent6a94d692014-05-20 11:18:06 -07002503 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2504 patch->sources[0].role,
2505 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002506#if LOG_NDEBUG == 0
2507 for (size_t i = 0; i < patch->num_sinks; i++) {
2508 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2509 patch->sinks[i].role,
2510 patch->sinks[i].type);
2511 }
2512#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002513
2514 if (index >= 0) {
2515 patchDesc = mAudioPatches.valueAt(index);
2516 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2517 mUidCached, patchDesc->mUid, uid);
2518 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2519 return INVALID_OPERATION;
2520 }
2521 } else {
2522 *handle = 0;
2523 }
2524
2525 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002526 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002527 if (outputDesc == NULL) {
2528 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2529 return BAD_VALUE;
2530 }
Eric Laurent84c70242014-06-23 08:46:27 -07002531 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2532 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002533 if (patchDesc != 0) {
2534 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2535 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2536 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2537 return BAD_VALUE;
2538 }
2539 }
Eric Laurent874c42872014-08-08 15:13:39 -07002540 DeviceVector devices;
2541 for (size_t i = 0; i < patch->num_sinks; i++) {
2542 // Only support mix to devices connection
2543 // TODO add support for mix to mix connection
2544 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2545 ALOGV("createAudioPatch() source mix but sink is not a device");
2546 return INVALID_OPERATION;
2547 }
2548 sp<DeviceDescriptor> devDesc =
2549 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2550 if (devDesc == 0) {
2551 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2552 return BAD_VALUE;
2553 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002554
Eric Laurent874c42872014-08-08 15:13:39 -07002555 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002556 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002557 patch->sources[0].sample_rate,
2558 NULL, // updatedSamplingRate
2559 patch->sources[0].format,
2560 patch->sources[0].channel_mask,
2561 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2562 ALOGV("createAudioPatch() profile not supported for device %08x",
2563 devDesc->mDeviceType);
2564 return INVALID_OPERATION;
2565 }
2566 devices.add(devDesc);
2567 }
2568 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002569 return INVALID_OPERATION;
2570 }
Eric Laurent874c42872014-08-08 15:13:39 -07002571
Eric Laurent6a94d692014-05-20 11:18:06 -07002572 // TODO: reconfigure output format and channels here
2573 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002574 devices.types(), outputDesc->mIoHandle);
2575 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002576 index = mAudioPatches.indexOfKey(*handle);
2577 if (index >= 0) {
2578 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2579 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2580 }
2581 patchDesc = mAudioPatches.valueAt(index);
2582 patchDesc->mUid = uid;
2583 ALOGV("createAudioPatch() success");
2584 } else {
2585 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2586 return INVALID_OPERATION;
2587 }
2588 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2589 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2590 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002591 // only one sink supported when connecting an input device to a mix
2592 if (patch->num_sinks > 1) {
2593 return INVALID_OPERATION;
2594 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002595 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002596 if (inputDesc == NULL) {
2597 return BAD_VALUE;
2598 }
2599 if (patchDesc != 0) {
2600 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2601 return BAD_VALUE;
2602 }
2603 }
2604 sp<DeviceDescriptor> devDesc =
2605 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2606 if (devDesc == 0) {
2607 return BAD_VALUE;
2608 }
2609
Eric Laurent84c70242014-06-23 08:46:27 -07002610 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002611 devDesc->mAddress,
2612 patch->sinks[0].sample_rate,
2613 NULL, /*updatedSampleRate*/
2614 patch->sinks[0].format,
2615 patch->sinks[0].channel_mask,
2616 // FIXME for the parameter type,
2617 // and the NONE
2618 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002619 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002620 return INVALID_OPERATION;
2621 }
2622 // TODO: reconfigure output format and channels here
2623 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002624 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002625 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002626 index = mAudioPatches.indexOfKey(*handle);
2627 if (index >= 0) {
2628 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2629 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2630 }
2631 patchDesc = mAudioPatches.valueAt(index);
2632 patchDesc->mUid = uid;
2633 ALOGV("createAudioPatch() success");
2634 } else {
2635 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2636 return INVALID_OPERATION;
2637 }
2638 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2639 // device to device connection
2640 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002641 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002642 return BAD_VALUE;
2643 }
2644 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002645 sp<DeviceDescriptor> srcDeviceDesc =
2646 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002647 if (srcDeviceDesc == 0) {
2648 return BAD_VALUE;
2649 }
Eric Laurent874c42872014-08-08 15:13:39 -07002650
Eric Laurent6a94d692014-05-20 11:18:06 -07002651 //update source and sink with our own data as the data passed in the patch may
2652 // be incomplete.
2653 struct audio_patch newPatch = *patch;
2654 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002655
Eric Laurent874c42872014-08-08 15:13:39 -07002656 for (size_t i = 0; i < patch->num_sinks; i++) {
2657 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2658 ALOGV("createAudioPatch() source device but one sink is not a device");
2659 return INVALID_OPERATION;
2660 }
2661
2662 sp<DeviceDescriptor> sinkDeviceDesc =
2663 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2664 if (sinkDeviceDesc == 0) {
2665 return BAD_VALUE;
2666 }
2667 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2668
2669 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2670 // only one sink supported when connected devices across HW modules
2671 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002672 return INVALID_OPERATION;
2673 }
Eric Laurent874c42872014-08-08 15:13:39 -07002674 SortedVector<audio_io_handle_t> outputs =
2675 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2676 mOutputs);
2677 // if the sink device is reachable via an opened output stream, request to go via
2678 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002679 audio_io_handle_t output = selectOutput(outputs,
2680 AUDIO_OUTPUT_FLAG_NONE,
2681 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002682 if (output != AUDIO_IO_HANDLE_NONE) {
2683 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2684 if (outputDesc->isDuplicated()) {
2685 return INVALID_OPERATION;
2686 }
2687 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2688 newPatch.num_sources = 2;
2689 }
Eric Laurent83b88082014-06-20 18:31:16 -07002690 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002691 }
2692 // TODO: check from routing capabilities in config file and other conflicting patches
2693
2694 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2695 if (index >= 0) {
2696 afPatchHandle = patchDesc->mAfPatchHandle;
2697 }
2698
2699 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2700 &afPatchHandle,
2701 0);
2702 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2703 status, afPatchHandle);
2704 if (status == NO_ERROR) {
2705 if (index < 0) {
2706 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2707 &newPatch, uid);
2708 addAudioPatch(patchDesc->mHandle, patchDesc);
2709 } else {
2710 patchDesc->mPatch = newPatch;
2711 }
2712 patchDesc->mAfPatchHandle = afPatchHandle;
2713 *handle = patchDesc->mHandle;
2714 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002715 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002716 } else {
2717 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2718 status);
2719 return INVALID_OPERATION;
2720 }
2721 } else {
2722 return BAD_VALUE;
2723 }
2724 } else {
2725 return BAD_VALUE;
2726 }
2727 return NO_ERROR;
2728}
2729
2730status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2731 uid_t uid)
2732{
2733 ALOGV("releaseAudioPatch() patch %d", handle);
2734
2735 ssize_t index = mAudioPatches.indexOfKey(handle);
2736
2737 if (index < 0) {
2738 return BAD_VALUE;
2739 }
2740 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2741 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2742 mUidCached, patchDesc->mUid, uid);
2743 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2744 return INVALID_OPERATION;
2745 }
2746
2747 struct audio_patch *patch = &patchDesc->mPatch;
2748 patchDesc->mUid = mUidCached;
2749 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002750 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002751 if (outputDesc == NULL) {
2752 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2753 return BAD_VALUE;
2754 }
2755
2756 setOutputDevice(outputDesc->mIoHandle,
2757 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2758 true,
2759 0,
2760 NULL);
2761 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2762 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002763 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002764 if (inputDesc == NULL) {
2765 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2766 return BAD_VALUE;
2767 }
2768 setInputDevice(inputDesc->mIoHandle,
2769 getNewInputDevice(inputDesc->mIoHandle),
2770 true,
2771 NULL);
2772 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2773 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2774 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2775 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2776 status, patchDesc->mAfPatchHandle);
2777 removeAudioPatch(patchDesc->mHandle);
2778 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002779 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002780 } else {
2781 return BAD_VALUE;
2782 }
2783 } else {
2784 return BAD_VALUE;
2785 }
2786 return NO_ERROR;
2787}
2788
2789status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2790 struct audio_patch *patches,
2791 unsigned int *generation)
2792{
2793 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2794 generation == NULL) {
2795 return BAD_VALUE;
2796 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002797 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002798 *num_patches, patches, mAudioPatches.size());
2799 if (patches == NULL) {
2800 *num_patches = 0;
2801 }
2802
2803 size_t patchesWritten = 0;
2804 size_t patchesMax = *num_patches;
2805 for (size_t i = 0;
2806 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2807 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2808 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002809 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002810 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2811 }
2812 *num_patches = mAudioPatches.size();
2813
2814 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002815 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002816 return NO_ERROR;
2817}
2818
Eric Laurente1715a42014-05-20 11:30:42 -07002819status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002820{
Eric Laurente1715a42014-05-20 11:30:42 -07002821 ALOGV("setAudioPortConfig()");
2822
2823 if (config == NULL) {
2824 return BAD_VALUE;
2825 }
2826 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2827 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002828 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2829 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002830 }
2831
Eric Laurenta121f902014-06-03 13:32:54 -07002832 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002833 if (config->type == AUDIO_PORT_TYPE_MIX) {
2834 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002835 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002836 if (outputDesc == NULL) {
2837 return BAD_VALUE;
2838 }
Eric Laurent84c70242014-06-23 08:46:27 -07002839 ALOG_ASSERT(!outputDesc->isDuplicated(),
2840 "setAudioPortConfig() called on duplicated output %d",
2841 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002842 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002843 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002844 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002845 if (inputDesc == NULL) {
2846 return BAD_VALUE;
2847 }
Eric Laurenta121f902014-06-03 13:32:54 -07002848 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002849 } else {
2850 return BAD_VALUE;
2851 }
2852 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2853 sp<DeviceDescriptor> deviceDesc;
2854 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2855 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2856 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2857 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2858 } else {
2859 return BAD_VALUE;
2860 }
2861 if (deviceDesc == NULL) {
2862 return BAD_VALUE;
2863 }
Eric Laurenta121f902014-06-03 13:32:54 -07002864 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002865 } else {
2866 return BAD_VALUE;
2867 }
2868
Eric Laurenta121f902014-06-03 13:32:54 -07002869 struct audio_port_config backupConfig;
2870 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2871 if (status == NO_ERROR) {
2872 struct audio_port_config newConfig;
2873 audioPortConfig->toAudioPortConfig(&newConfig, config);
2874 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002875 }
Eric Laurenta121f902014-06-03 13:32:54 -07002876 if (status != NO_ERROR) {
2877 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002878 }
Eric Laurente1715a42014-05-20 11:30:42 -07002879
2880 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002881}
2882
2883void AudioPolicyManager::clearAudioPatches(uid_t uid)
2884{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002885 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002886 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2887 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002888 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002889 }
2890 }
2891}
2892
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002893status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2894 audio_io_handle_t *ioHandle,
2895 audio_devices_t *device)
2896{
2897 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2898 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2899 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2900
2901 mSoundTriggerSessions.add(*session, *ioHandle);
2902
2903 return NO_ERROR;
2904}
2905
2906status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2907{
2908 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2909 if (index < 0) {
2910 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2911 return BAD_VALUE;
2912 }
2913
2914 mSoundTriggerSessions.removeItem(session);
2915 return NO_ERROR;
2916}
2917
Eric Laurent6a94d692014-05-20 11:18:06 -07002918status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2919 const sp<AudioPatch>& patch)
2920{
2921 ssize_t index = mAudioPatches.indexOfKey(handle);
2922
2923 if (index >= 0) {
2924 ALOGW("addAudioPatch() patch %d already in", handle);
2925 return ALREADY_EXISTS;
2926 }
2927 mAudioPatches.add(handle, patch);
2928 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2929 "sink handle %d",
2930 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2931 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2932 return NO_ERROR;
2933}
2934
2935status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2936{
2937 ssize_t index = mAudioPatches.indexOfKey(handle);
2938
2939 if (index < 0) {
2940 ALOGW("removeAudioPatch() patch %d not in", handle);
2941 return ALREADY_EXISTS;
2942 }
2943 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2944 mAudioPatches.valueAt(index)->mAfPatchHandle);
2945 mAudioPatches.removeItemsAt(index);
2946 return NO_ERROR;
2947}
2948
Eric Laurente552edb2014-03-10 17:42:56 -07002949// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002950// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002951// ----------------------------------------------------------------------------
2952
Eric Laurent3a4311c2014-03-17 12:00:47 -07002953uint32_t AudioPolicyManager::nextUniqueId()
2954{
2955 return android_atomic_inc(&mNextUniqueId);
2956}
2957
Eric Laurent6a94d692014-05-20 11:18:06 -07002958uint32_t AudioPolicyManager::nextAudioPortGeneration()
2959{
2960 return android_atomic_inc(&mAudioPortGeneration);
2961}
2962
Eric Laurente0720872014-03-11 09:30:41 -07002963AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002964 :
2965#ifdef AUDIO_POLICY_TEST
2966 Thread(false),
2967#endif //AUDIO_POLICY_TEST
2968 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002969 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002970 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2971 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002972 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002973 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002974 mAudioPortGeneration(1),
2975 mBeaconMuteRefCount(0),
2976 mBeaconPlayingRefCount(0),
2977 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002978{
Eric Laurent6a94d692014-05-20 11:18:06 -07002979 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002980 mpClientInterface = clientInterface;
2981
Eric Laurent3b73df72014-03-11 09:06:29 -07002982 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2983 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002984 }
2985
Eric Laurent1afeecb2014-05-14 08:52:28 -07002986 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002987 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2988 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2989 ALOGE("could not load audio policy configuration file, setting defaults");
2990 defaultAudioPolicyConfig();
2991 }
2992 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002993 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002994
2995 // must be done after reading the policy
2996 initializeVolumeCurves();
2997
2998 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002999 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3000 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003001 for (size_t i = 0; i < mHwModules.size(); i++) {
3002 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3003 if (mHwModules[i]->mHandle == 0) {
3004 ALOGW("could not open HW module %s", mHwModules[i]->mName);
3005 continue;
3006 }
3007 // open all output streams needed to access attached devices
3008 // except for direct output streams that are only opened when they are actually
3009 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003010 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003011 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3012 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003013 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003014
Eric Laurent3a4311c2014-03-17 12:00:47 -07003015 if (outProfile->mSupportedDevices.isEmpty()) {
3016 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3017 continue;
3018 }
3019
Eric Laurentd78f1532014-09-16 16:38:20 -07003020 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3021 continue;
3022 }
Eric Laurent83b88082014-06-20 18:31:16 -07003023 audio_devices_t profileType = outProfile->mSupportedDevices.types();
3024 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3025 profileType = mDefaultOutputDevice->mDeviceType;
3026 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07003027 // chose first device present in mSupportedDevices also part of
3028 // outputDeviceTypes
3029 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3030 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3031 if ((profileType & outputDeviceTypes) != 0) {
3032 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003033 }
Eric Laurente552edb2014-03-10 17:42:56 -07003034 }
3035 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003036 if ((profileType & outputDeviceTypes) == 0) {
3037 continue;
3038 }
3039 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3040
3041 outputDesc->mDevice = profileType;
3042 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3043 config.sample_rate = outputDesc->mSamplingRate;
3044 config.channel_mask = outputDesc->mChannelMask;
3045 config.format = outputDesc->mFormat;
3046 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3047 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3048 &output,
3049 &config,
3050 &outputDesc->mDevice,
3051 String8(""),
3052 &outputDesc->mLatency,
3053 outputDesc->mFlags);
3054
3055 if (status != NO_ERROR) {
3056 ALOGW("Cannot open output stream for device %08x on hw module %s",
3057 outputDesc->mDevice,
3058 mHwModules[i]->mName);
3059 } else {
3060 outputDesc->mSamplingRate = config.sample_rate;
3061 outputDesc->mChannelMask = config.channel_mask;
3062 outputDesc->mFormat = config.format;
3063
3064 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3065 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3066 ssize_t index =
3067 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3068 // give a valid ID to an attached device once confirmed it is reachable
3069 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3070 mAvailableOutputDevices[index]->mId = nextUniqueId();
3071 mAvailableOutputDevices[index]->mModule = mHwModules[i];
3072 }
3073 }
3074 if (mPrimaryOutput == 0 &&
3075 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3076 mPrimaryOutput = output;
3077 }
3078 addOutput(output, outputDesc);
3079 setOutputDevice(output,
3080 outputDesc->mDevice,
3081 true);
3082 }
Eric Laurente552edb2014-03-10 17:42:56 -07003083 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003084 // open input streams needed to access attached devices to validate
3085 // mAvailableInputDevices list
3086 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3087 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003088 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003089
Eric Laurent3a4311c2014-03-17 12:00:47 -07003090 if (inProfile->mSupportedDevices.isEmpty()) {
3091 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3092 continue;
3093 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003094 // chose first device present in mSupportedDevices also part of
3095 // inputDeviceTypes
3096 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3097 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3098 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3099 if (profileType & inputDeviceTypes) {
3100 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003101 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003102 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003103 if ((profileType & inputDeviceTypes) == 0) {
3104 continue;
3105 }
3106 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3107
3108 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3109 inputDesc->mDevice = profileType;
3110
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003111 // find the address
3112 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3113 // the inputs vector must be of size 1, but we don't want to crash here
3114 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3115 : String8("");
3116 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3117 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3118
Eric Laurentd78f1532014-09-16 16:38:20 -07003119 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3120 config.sample_rate = inputDesc->mSamplingRate;
3121 config.channel_mask = inputDesc->mChannelMask;
3122 config.format = inputDesc->mFormat;
3123 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3124 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3125 &input,
3126 &config,
3127 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003128 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003129 AUDIO_SOURCE_MIC,
3130 AUDIO_INPUT_FLAG_NONE);
3131
3132 if (status == NO_ERROR) {
3133 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3134 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3135 ssize_t index =
3136 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3137 // give a valid ID to an attached device once confirmed it is reachable
3138 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3139 mAvailableInputDevices[index]->mId = nextUniqueId();
3140 mAvailableInputDevices[index]->mModule = mHwModules[i];
3141 }
3142 }
3143 mpClientInterface->closeInput(input);
3144 } else {
3145 ALOGW("Cannot open input stream for device %08x on hw module %s",
3146 inputDesc->mDevice,
3147 mHwModules[i]->mName);
3148 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003149 }
3150 }
3151 // make sure all attached devices have been allocated a unique ID
3152 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3153 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003154 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003155 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3156 continue;
3157 }
3158 i++;
3159 }
3160 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3161 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003162 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003163 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3164 continue;
3165 }
3166 i++;
3167 }
3168 // make sure default device is reachable
3169 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003170 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003171 }
Eric Laurente552edb2014-03-10 17:42:56 -07003172
3173 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3174
3175 updateDevicesAndOutputs();
3176
3177#ifdef AUDIO_POLICY_TEST
3178 if (mPrimaryOutput != 0) {
3179 AudioParameter outputCmd = AudioParameter();
3180 outputCmd.addInt(String8("set_id"), 0);
3181 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3182
3183 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3184 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003185 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3186 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003187 mTestLatencyMs = 0;
3188 mCurOutput = 0;
3189 mDirectOutput = false;
3190 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3191 mTestOutputs[i] = 0;
3192 }
3193
3194 const size_t SIZE = 256;
3195 char buffer[SIZE];
3196 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3197 run(buffer, ANDROID_PRIORITY_AUDIO);
3198 }
3199#endif //AUDIO_POLICY_TEST
3200}
3201
Eric Laurente0720872014-03-11 09:30:41 -07003202AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003203{
3204#ifdef AUDIO_POLICY_TEST
3205 exit();
3206#endif //AUDIO_POLICY_TEST
3207 for (size_t i = 0; i < mOutputs.size(); i++) {
3208 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003209 }
3210 for (size_t i = 0; i < mInputs.size(); i++) {
3211 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003212 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003213 mAvailableOutputDevices.clear();
3214 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003215 mOutputs.clear();
3216 mInputs.clear();
3217 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003218}
3219
Eric Laurente0720872014-03-11 09:30:41 -07003220status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003221{
3222 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3223}
3224
3225#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003226bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003227{
3228 ALOGV("entering threadLoop()");
3229 while (!exitPending())
3230 {
3231 String8 command;
3232 int valueInt;
3233 String8 value;
3234
3235 Mutex::Autolock _l(mLock);
3236 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3237
3238 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3239 AudioParameter param = AudioParameter(command);
3240
3241 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3242 valueInt != 0) {
3243 ALOGV("Test command %s received", command.string());
3244 String8 target;
3245 if (param.get(String8("target"), target) != NO_ERROR) {
3246 target = "Manager";
3247 }
3248 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3249 param.remove(String8("test_cmd_policy_output"));
3250 mCurOutput = valueInt;
3251 }
3252 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3253 param.remove(String8("test_cmd_policy_direct"));
3254 if (value == "false") {
3255 mDirectOutput = false;
3256 } else if (value == "true") {
3257 mDirectOutput = true;
3258 }
3259 }
3260 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3261 param.remove(String8("test_cmd_policy_input"));
3262 mTestInput = valueInt;
3263 }
3264
3265 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3266 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003267 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003268 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003269 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003270 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003271 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003272 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003273 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003274 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003275 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003276 if (target == "Manager") {
3277 mTestFormat = format;
3278 } else if (mTestOutputs[mCurOutput] != 0) {
3279 AudioParameter outputParam = AudioParameter();
3280 outputParam.addInt(String8("format"), format);
3281 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3282 }
3283 }
3284 }
3285 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3286 param.remove(String8("test_cmd_policy_channels"));
3287 int channels = 0;
3288
3289 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003290 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003291 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003292 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003293 }
3294 if (channels != 0) {
3295 if (target == "Manager") {
3296 mTestChannels = channels;
3297 } else if (mTestOutputs[mCurOutput] != 0) {
3298 AudioParameter outputParam = AudioParameter();
3299 outputParam.addInt(String8("channels"), channels);
3300 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3301 }
3302 }
3303 }
3304 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3305 param.remove(String8("test_cmd_policy_sampleRate"));
3306 if (valueInt >= 0 && valueInt <= 96000) {
3307 int samplingRate = valueInt;
3308 if (target == "Manager") {
3309 mTestSamplingRate = samplingRate;
3310 } else if (mTestOutputs[mCurOutput] != 0) {
3311 AudioParameter outputParam = AudioParameter();
3312 outputParam.addInt(String8("sampling_rate"), samplingRate);
3313 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3314 }
3315 }
3316 }
3317
3318 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3319 param.remove(String8("test_cmd_policy_reopen"));
3320
Eric Laurent1f2f2232014-06-02 12:01:23 -07003321 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003322 mpClientInterface->closeOutput(mPrimaryOutput);
3323
3324 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3325
Eric Laurente552edb2014-03-10 17:42:56 -07003326 mOutputs.removeItem(mPrimaryOutput);
3327
Eric Laurent1f2f2232014-06-02 12:01:23 -07003328 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003329 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003330 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3331 config.sample_rate = outputDesc->mSamplingRate;
3332 config.channel_mask = outputDesc->mChannelMask;
3333 config.format = outputDesc->mFormat;
3334 status_t status = mpClientInterface->openOutput(moduleHandle,
3335 &mPrimaryOutput,
3336 &config,
3337 &outputDesc->mDevice,
3338 String8(""),
3339 &outputDesc->mLatency,
3340 outputDesc->mFlags);
3341 if (status != NO_ERROR) {
3342 ALOGE("Failed to reopen hardware output stream, "
3343 "samplingRate: %d, format %d, channels %d",
3344 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003345 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003346 outputDesc->mSamplingRate = config.sample_rate;
3347 outputDesc->mChannelMask = config.channel_mask;
3348 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003349 AudioParameter outputCmd = AudioParameter();
3350 outputCmd.addInt(String8("set_id"), 0);
3351 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3352 addOutput(mPrimaryOutput, outputDesc);
3353 }
3354 }
3355
3356
3357 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3358 }
3359 }
3360 return false;
3361}
3362
Eric Laurente0720872014-03-11 09:30:41 -07003363void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003364{
3365 {
3366 AutoMutex _l(mLock);
3367 requestExit();
3368 mWaitWorkCV.signal();
3369 }
3370 requestExitAndWait();
3371}
3372
Eric Laurente0720872014-03-11 09:30:41 -07003373int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003374{
3375 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3376 if (output == mTestOutputs[i]) return i;
3377 }
3378 return 0;
3379}
3380#endif //AUDIO_POLICY_TEST
3381
3382// ---
3383
Eric Laurent1f2f2232014-06-02 12:01:23 -07003384void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003385{
Eric Laurent1c333e22014-05-20 10:48:17 -07003386 outputDesc->mIoHandle = output;
3387 outputDesc->mId = nextUniqueId();
3388 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003389 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003390}
3391
Eric Laurent1f2f2232014-06-02 12:01:23 -07003392void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003393{
Eric Laurent1c333e22014-05-20 10:48:17 -07003394 inputDesc->mIoHandle = input;
3395 inputDesc->mId = nextUniqueId();
3396 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003397 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003398}
Eric Laurente552edb2014-03-10 17:42:56 -07003399
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003400void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3401 const String8 address /*in*/,
3402 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3403 // look for a match on the given address on the addresses of the outputs:
3404 // find the address by finding the patch that maps to this output
3405 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3406 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3407 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3408 if (patchIdx >= 0) {
3409 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3410 const int numSinks = patchDesc->mPatch.num_sinks;
3411 for (ssize_t j=0; j < numSinks; j++) {
3412 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3413 const char* patchAddr =
3414 patchDesc->mPatch.sinks[j].ext.device.address;
3415 if (strncmp(patchAddr,
3416 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003417 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003418 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3419 outputs.add(desc->mIoHandle);
3420 break;
3421 }
3422 }
3423 }
3424 }
3425}
3426
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003427status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003428 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003429 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003430 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003431{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003432 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003433 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003434 // erase all current sample rates, formats and channel masks
3435 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003436
Eric Laurent3b73df72014-03-11 09:06:29 -07003437 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003438 // first list already open outputs that can be routed to this device
3439 for (size_t i = 0; i < mOutputs.size(); i++) {
3440 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003441 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003442 if (!deviceDistinguishesOnAddress(device)) {
3443 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3444 outputs.add(mOutputs.keyAt(i));
3445 } else {
3446 ALOGV(" checking address match due to device 0x%x", device);
3447 findIoHandlesByAddress(desc, address, outputs);
3448 }
Eric Laurente552edb2014-03-10 17:42:56 -07003449 }
3450 }
3451 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003452 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003453 for (size_t i = 0; i < mHwModules.size(); i++)
3454 {
3455 if (mHwModules[i]->mHandle == 0) {
3456 continue;
3457 }
3458 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3459 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003460 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3461 if (profile->mSupportedDevices.types() & device) {
3462 if (!deviceDistinguishesOnAddress(device) ||
3463 address == profile->mSupportedDevices[0]->mAddress) {
3464 profiles.add(profile);
3465 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3466 }
Eric Laurente552edb2014-03-10 17:42:56 -07003467 }
3468 }
3469 }
3470
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003471 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3472
Eric Laurente552edb2014-03-10 17:42:56 -07003473 if (profiles.isEmpty() && outputs.isEmpty()) {
3474 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3475 return BAD_VALUE;
3476 }
3477
3478 // open outputs for matching profiles if needed. Direct outputs are also opened to
3479 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3480 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003481 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003482
3483 // nothing to do if one output is already opened for this profile
3484 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003485 for (j = 0; j < outputs.size(); j++) {
3486 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003487 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003488 // matching profile: save the sample rates, format and channel masks supported
3489 // by the profile in our device descriptor
3490 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003491 break;
3492 }
3493 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003494 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003495 continue;
3496 }
3497
Eric Laurent83b88082014-06-20 18:31:16 -07003498 ALOGV("opening output for device %08x with params %s profile %p",
3499 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003500 desc = new AudioOutputDescriptor(profile);
3501 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003502 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3503 config.sample_rate = desc->mSamplingRate;
3504 config.channel_mask = desc->mChannelMask;
3505 config.format = desc->mFormat;
3506 config.offload_info.sample_rate = desc->mSamplingRate;
3507 config.offload_info.channel_mask = desc->mChannelMask;
3508 config.offload_info.format = desc->mFormat;
3509 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3510 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3511 &output,
3512 &config,
3513 &desc->mDevice,
3514 address,
3515 &desc->mLatency,
3516 desc->mFlags);
3517 if (status == NO_ERROR) {
3518 desc->mSamplingRate = config.sample_rate;
3519 desc->mChannelMask = config.channel_mask;
3520 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003521
Eric Laurentd4692962014-05-05 18:13:44 -07003522 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003523 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003524 char *param = audio_device_address_to_parameter(device, address);
3525 mpClientInterface->setParameters(output, String8(param));
3526 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003527 }
3528
Eric Laurentd4692962014-05-05 18:13:44 -07003529 // Here is where we step through and resolve any "dynamic" fields
3530 String8 reply;
3531 char *value;
3532 if (profile->mSamplingRates[0] == 0) {
3533 reply = mpClientInterface->getParameters(output,
3534 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003535 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003536 reply.string());
3537 value = strpbrk((char *)reply.string(), "=");
3538 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003539 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003540 }
Eric Laurentd4692962014-05-05 18:13:44 -07003541 }
3542 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3543 reply = mpClientInterface->getParameters(output,
3544 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003545 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003546 reply.string());
3547 value = strpbrk((char *)reply.string(), "=");
3548 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003549 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003550 }
Eric Laurentd4692962014-05-05 18:13:44 -07003551 }
3552 if (profile->mChannelMasks[0] == 0) {
3553 reply = mpClientInterface->getParameters(output,
3554 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003555 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003556 reply.string());
3557 value = strpbrk((char *)reply.string(), "=");
3558 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003559 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003560 }
Eric Laurentd4692962014-05-05 18:13:44 -07003561 }
3562 if (((profile->mSamplingRates[0] == 0) &&
3563 (profile->mSamplingRates.size() < 2)) ||
3564 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3565 (profile->mFormats.size() < 2)) ||
3566 ((profile->mChannelMasks[0] == 0) &&
3567 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003568 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003569 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003570 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003571 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3572 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003573 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003574 config.sample_rate = profile->pickSamplingRate();
3575 config.channel_mask = profile->pickChannelMask();
3576 config.format = profile->pickFormat();
3577 config.offload_info.sample_rate = config.sample_rate;
3578 config.offload_info.channel_mask = config.channel_mask;
3579 config.offload_info.format = config.format;
3580 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3581 &output,
3582 &config,
3583 &desc->mDevice,
3584 address,
3585 &desc->mLatency,
3586 desc->mFlags);
3587 if (status == NO_ERROR) {
3588 desc->mSamplingRate = config.sample_rate;
3589 desc->mChannelMask = config.channel_mask;
3590 desc->mFormat = config.format;
3591 } else {
3592 output = AUDIO_IO_HANDLE_NONE;
3593 }
Eric Laurentd4692962014-05-05 18:13:44 -07003594 }
3595
Eric Laurentcf2c0212014-07-25 16:20:43 -07003596 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003597 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003598 if (deviceDistinguishesOnAddress(device) && address != "0") {
3599 ssize_t index = mPolicyMixes.indexOfKey(address);
3600 if (index >= 0) {
3601 mPolicyMixes[index]->mOutput = desc;
Eric Laurentc722f302014-12-10 11:21:49 -08003602 desc->mPolicyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08003603 } else {
3604 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3605 address.string());
3606 }
Eric Laurentc722f302014-12-10 11:21:49 -08003607 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3608 // no duplicated output for direct outputs and
3609 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003610 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003611
Eric Laurentd4692962014-05-05 18:13:44 -07003612 // set initial stream volume for device
3613 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003614
Eric Laurentd4692962014-05-05 18:13:44 -07003615 //TODO: configure audio effect output stage here
3616
3617 // open a duplicating output thread for the new output and the primary output
3618 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3619 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003620 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003621 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003622 sp<AudioOutputDescriptor> dupOutputDesc =
3623 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003624 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3625 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3626 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3627 dupOutputDesc->mFormat = desc->mFormat;
3628 dupOutputDesc->mChannelMask = desc->mChannelMask;
3629 dupOutputDesc->mLatency = desc->mLatency;
3630 addOutput(duplicatedOutput, dupOutputDesc);
3631 applyStreamVolumes(duplicatedOutput, device, 0, true);
3632 } else {
3633 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3634 mPrimaryOutput, output);
3635 mpClientInterface->closeOutput(output);
3636 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003637 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003638 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003639 }
Eric Laurente552edb2014-03-10 17:42:56 -07003640 }
3641 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003642 } else {
3643 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003644 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003645 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003646 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003647 profiles.removeAt(profile_index);
3648 profile_index--;
3649 } else {
3650 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003651 devDesc->importAudioPort(profile);
3652
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003653 if (deviceDistinguishesOnAddress(device)) {
3654 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3655 device, address.string());
3656 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3657 NULL/*patch handle*/, address.string());
3658 }
Eric Laurente552edb2014-03-10 17:42:56 -07003659 ALOGV("checkOutputsForDevice(): adding output %d", output);
3660 }
3661 }
3662
3663 if (profiles.isEmpty()) {
3664 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3665 return BAD_VALUE;
3666 }
Eric Laurentd4692962014-05-05 18:13:44 -07003667 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003668 // check if one opened output is not needed any more after disconnecting one device
3669 for (size_t i = 0; i < mOutputs.size(); i++) {
3670 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003671 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003672 // exact match on device
3673 if (deviceDistinguishesOnAddress(device) &&
3674 (desc->mProfile->mSupportedDevices.types() == device)) {
3675 findIoHandlesByAddress(desc, address, outputs);
3676 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003677 & mAvailableOutputDevices.types())) {
3678 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3679 mOutputs.keyAt(i));
3680 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003681 }
Eric Laurente552edb2014-03-10 17:42:56 -07003682 }
3683 }
Eric Laurentd4692962014-05-05 18:13:44 -07003684 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003685 for (size_t i = 0; i < mHwModules.size(); i++)
3686 {
3687 if (mHwModules[i]->mHandle == 0) {
3688 continue;
3689 }
3690 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3691 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003692 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003693 if (profile->mSupportedDevices.types() & device) {
3694 ALOGV("checkOutputsForDevice(): "
3695 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003696 if (profile->mSamplingRates[0] == 0) {
3697 profile->mSamplingRates.clear();
3698 profile->mSamplingRates.add(0);
3699 }
3700 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3701 profile->mFormats.clear();
3702 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3703 }
3704 if (profile->mChannelMasks[0] == 0) {
3705 profile->mChannelMasks.clear();
3706 profile->mChannelMasks.add(0);
3707 }
3708 }
3709 }
3710 }
3711 }
3712 return NO_ERROR;
3713}
3714
Eric Laurentd4692962014-05-05 18:13:44 -07003715status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3716 audio_policy_dev_state_t state,
3717 SortedVector<audio_io_handle_t>& inputs,
3718 const String8 address)
3719{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003720 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003721 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3722 // first list already open inputs that can be routed to this device
3723 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3724 desc = mInputs.valueAt(input_index);
3725 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3726 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3727 inputs.add(mInputs.keyAt(input_index));
3728 }
3729 }
3730
3731 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003732 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003733 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3734 {
3735 if (mHwModules[module_idx]->mHandle == 0) {
3736 continue;
3737 }
3738 for (size_t profile_index = 0;
3739 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3740 profile_index++)
3741 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003742 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3743
3744 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3745 if (!deviceDistinguishesOnAddress(device) ||
3746 address == profile->mSupportedDevices[0]->mAddress) {
3747 profiles.add(profile);
3748 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3749 profile_index, module_idx);
3750 }
Eric Laurentd4692962014-05-05 18:13:44 -07003751 }
3752 }
3753 }
3754
3755 if (profiles.isEmpty() && inputs.isEmpty()) {
3756 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3757 return BAD_VALUE;
3758 }
3759
3760 // open inputs for matching profiles if needed. Direct inputs are also opened to
3761 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3762 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3763
Eric Laurent1c333e22014-05-20 10:48:17 -07003764 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003765 // nothing to do if one input is already opened for this profile
3766 size_t input_index;
3767 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3768 desc = mInputs.valueAt(input_index);
3769 if (desc->mProfile == profile) {
3770 break;
3771 }
3772 }
3773 if (input_index != mInputs.size()) {
3774 continue;
3775 }
3776
3777 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3778 desc = new AudioInputDescriptor(profile);
3779 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003780 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3781 config.sample_rate = desc->mSamplingRate;
3782 config.channel_mask = desc->mChannelMask;
3783 config.format = desc->mFormat;
3784 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3785 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3786 &input,
3787 &config,
3788 &desc->mDevice,
3789 address,
3790 AUDIO_SOURCE_MIC,
3791 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003792
Eric Laurentcf2c0212014-07-25 16:20:43 -07003793 if (status == NO_ERROR) {
3794 desc->mSamplingRate = config.sample_rate;
3795 desc->mChannelMask = config.channel_mask;
3796 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003797
Eric Laurentd4692962014-05-05 18:13:44 -07003798 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003799 char *param = audio_device_address_to_parameter(device, address);
3800 mpClientInterface->setParameters(input, String8(param));
3801 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003802 }
3803
3804 // Here is where we step through and resolve any "dynamic" fields
3805 String8 reply;
3806 char *value;
3807 if (profile->mSamplingRates[0] == 0) {
3808 reply = mpClientInterface->getParameters(input,
3809 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3810 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3811 reply.string());
3812 value = strpbrk((char *)reply.string(), "=");
3813 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003814 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003815 }
3816 }
3817 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3818 reply = mpClientInterface->getParameters(input,
3819 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3820 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3821 value = strpbrk((char *)reply.string(), "=");
3822 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003823 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003824 }
3825 }
3826 if (profile->mChannelMasks[0] == 0) {
3827 reply = mpClientInterface->getParameters(input,
3828 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3829 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3830 reply.string());
3831 value = strpbrk((char *)reply.string(), "=");
3832 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003833 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003834 }
3835 }
3836 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3837 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3838 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3839 ALOGW("checkInputsForDevice() direct input missing param");
3840 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003841 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003842 }
3843
3844 if (input != 0) {
3845 addInput(input, desc);
3846 }
3847 } // endif input != 0
3848
Eric Laurentcf2c0212014-07-25 16:20:43 -07003849 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003850 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003851 profiles.removeAt(profile_index);
3852 profile_index--;
3853 } else {
3854 inputs.add(input);
3855 ALOGV("checkInputsForDevice(): adding input %d", input);
3856 }
3857 } // end scan profiles
3858
3859 if (profiles.isEmpty()) {
3860 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3861 return BAD_VALUE;
3862 }
3863 } else {
3864 // Disconnect
3865 // check if one opened input is not needed any more after disconnecting one device
3866 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3867 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003868 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3869 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003870 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3871 mInputs.keyAt(input_index));
3872 inputs.add(mInputs.keyAt(input_index));
3873 }
3874 }
3875 // Clear any profiles associated with the disconnected device.
3876 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3877 if (mHwModules[module_index]->mHandle == 0) {
3878 continue;
3879 }
3880 for (size_t profile_index = 0;
3881 profile_index < mHwModules[module_index]->mInputProfiles.size();
3882 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003883 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003884 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003885 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003886 profile_index, module_index);
3887 if (profile->mSamplingRates[0] == 0) {
3888 profile->mSamplingRates.clear();
3889 profile->mSamplingRates.add(0);
3890 }
3891 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3892 profile->mFormats.clear();
3893 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3894 }
3895 if (profile->mChannelMasks[0] == 0) {
3896 profile->mChannelMasks.clear();
3897 profile->mChannelMasks.add(0);
3898 }
3899 }
3900 }
3901 }
3902 } // end disconnect
3903
3904 return NO_ERROR;
3905}
3906
3907
Eric Laurente0720872014-03-11 09:30:41 -07003908void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003909{
3910 ALOGV("closeOutput(%d)", output);
3911
Eric Laurent1f2f2232014-06-02 12:01:23 -07003912 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003913 if (outputDesc == NULL) {
3914 ALOGW("closeOutput() unknown output %d", output);
3915 return;
3916 }
3917
Eric Laurent275e8e92014-11-30 15:14:47 -08003918 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3919 if (mPolicyMixes[i]->mOutput == outputDesc) {
3920 mPolicyMixes[i]->mOutput.clear();
3921 }
3922 }
3923
Eric Laurente552edb2014-03-10 17:42:56 -07003924 // look for duplicated outputs connected to the output being removed.
3925 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003926 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003927 if (dupOutputDesc->isDuplicated() &&
3928 (dupOutputDesc->mOutput1 == outputDesc ||
3929 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003930 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003931 if (dupOutputDesc->mOutput1 == outputDesc) {
3932 outputDesc2 = dupOutputDesc->mOutput2;
3933 } else {
3934 outputDesc2 = dupOutputDesc->mOutput1;
3935 }
3936 // As all active tracks on duplicated output will be deleted,
3937 // and as they were also referenced on the other output, the reference
3938 // count for their stream type must be adjusted accordingly on
3939 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003940 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003941 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003942 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003943 }
3944 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3945 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3946
3947 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003948 mOutputs.removeItem(duplicatedOutput);
3949 }
3950 }
3951
Eric Laurent05b90f82014-08-27 15:32:29 -07003952 nextAudioPortGeneration();
3953
3954 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3955 if (index >= 0) {
3956 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3957 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3958 mAudioPatches.removeItemsAt(index);
3959 mpClientInterface->onAudioPatchListUpdate();
3960 }
3961
Eric Laurente552edb2014-03-10 17:42:56 -07003962 AudioParameter param;
3963 param.add(String8("closing"), String8("true"));
3964 mpClientInterface->setParameters(output, param.toString());
3965
3966 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003967 mOutputs.removeItem(output);
3968 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003969}
3970
3971void AudioPolicyManager::closeInput(audio_io_handle_t input)
3972{
3973 ALOGV("closeInput(%d)", input);
3974
3975 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3976 if (inputDesc == NULL) {
3977 ALOGW("closeInput() unknown input %d", input);
3978 return;
3979 }
3980
Eric Laurent6a94d692014-05-20 11:18:06 -07003981 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003982
3983 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3984 if (index >= 0) {
3985 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3986 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3987 mAudioPatches.removeItemsAt(index);
3988 mpClientInterface->onAudioPatchListUpdate();
3989 }
3990
3991 mpClientInterface->closeInput(input);
3992 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003993}
3994
Eric Laurente0720872014-03-11 09:30:41 -07003995SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003996 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003997{
3998 SortedVector<audio_io_handle_t> outputs;
3999
4000 ALOGVV("getOutputsForDevice() device %04x", device);
4001 for (size_t i = 0; i < openOutputs.size(); i++) {
4002 ALOGVV("output %d isDuplicated=%d device=%04x",
4003 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4004 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4005 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4006 outputs.add(openOutputs.keyAt(i));
4007 }
4008 }
4009 return outputs;
4010}
4011
Eric Laurente0720872014-03-11 09:30:41 -07004012bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07004013 SortedVector<audio_io_handle_t>& outputs2)
4014{
4015 if (outputs1.size() != outputs2.size()) {
4016 return false;
4017 }
4018 for (size_t i = 0; i < outputs1.size(); i++) {
4019 if (outputs1[i] != outputs2[i]) {
4020 return false;
4021 }
4022 }
4023 return true;
4024}
4025
Eric Laurente0720872014-03-11 09:30:41 -07004026void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004027{
4028 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4029 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4030 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4031 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4032
4033 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4034 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4035 strategy, srcOutputs[0], dstOutputs[0]);
4036 // mute strategy while moving tracks from one output to another
4037 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004038 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004039 if (desc->isStrategyActive(strategy)) {
4040 setStrategyMute(strategy, true, srcOutputs[i]);
4041 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4042 }
4043 }
4044
4045 // Move effects associated to this strategy from previous output to new output
4046 if (strategy == STRATEGY_MEDIA) {
4047 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4048 SortedVector<audio_io_handle_t> moved;
4049 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004050 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4051 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4052 effectDesc->mIo != fxOutput) {
4053 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004054 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4055 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004056 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004057 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004058 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004059 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004060 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004061 }
4062 }
4063 }
4064 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004065 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004066 if (i == AUDIO_STREAM_PATCH) {
4067 continue;
4068 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004069 if (getStrategy((audio_stream_type_t)i) == strategy) {
4070 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004071 }
4072 }
4073 }
4074}
4075
Eric Laurente0720872014-03-11 09:30:41 -07004076void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004077{
Jon Eklund966095e2014-09-09 15:39:49 -05004078 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4079 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004080 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004081 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4082 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004083 checkOutputForStrategy(STRATEGY_SONIFICATION);
4084 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004085 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004086 checkOutputForStrategy(STRATEGY_MEDIA);
4087 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004088 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004089}
4090
Eric Laurente0720872014-03-11 09:30:41 -07004091audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004092{
Eric Laurente552edb2014-03-10 17:42:56 -07004093 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004094 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004095 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4096 return mOutputs.keyAt(i);
4097 }
4098 }
4099
4100 return 0;
4101}
4102
Eric Laurente0720872014-03-11 09:30:41 -07004103void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004104{
Eric Laurente552edb2014-03-10 17:42:56 -07004105 audio_io_handle_t a2dpOutput = getA2dpOutput();
4106 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004107 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004108 return;
4109 }
4110
Eric Laurent3a4311c2014-03-17 12:00:47 -07004111 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004112 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4113 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4114 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004115 // suspend A2DP output if:
4116 // (NOT already suspended) &&
4117 // ((SCO device is connected &&
4118 // (forced usage for communication || for record is SCO))) ||
4119 // (phone state is ringing || in call)
4120 //
4121 // restore A2DP output if:
4122 // (Already suspended) &&
4123 // ((SCO device is NOT connected ||
4124 // (forced usage NOT for communication && NOT for record is SCO))) &&
4125 // (phone state is NOT ringing && NOT in call)
4126 //
4127 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004128 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004129 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4130 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4131 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4132 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004133
4134 mpClientInterface->restoreOutput(a2dpOutput);
4135 mA2dpSuspended = false;
4136 }
4137 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004138 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004139 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4140 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4141 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4142 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004143
4144 mpClientInterface->suspendOutput(a2dpOutput);
4145 mA2dpSuspended = true;
4146 }
4147 }
4148}
4149
Eric Laurent1c333e22014-05-20 10:48:17 -07004150audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004151{
4152 audio_devices_t device = AUDIO_DEVICE_NONE;
4153
Eric Laurent1f2f2232014-06-02 12:01:23 -07004154 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004155
4156 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4157 if (index >= 0) {
4158 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4159 if (patchDesc->mUid != mUidCached) {
4160 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4161 outputDesc->device(), outputDesc->mPatchHandle);
4162 return outputDesc->device();
4163 }
4164 }
4165
Eric Laurente552edb2014-03-10 17:42:56 -07004166 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004167 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004168 // use device for strategy enforced audible
4169 // 2: we are in call or the strategy phone is active on the output:
4170 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004171 // 3: the strategy for enforced audible is active but not enforced on the output:
4172 // use the device for strategy enforced audible
4173 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004174 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004175 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004176 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004177 // 6: the strategy accessibility is active on the output:
4178 // use device for strategy accessibility
4179 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004180 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004181 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004182 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004183 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004184 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004185 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4186 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004187 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4188 } else if (isInCall() ||
4189 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4190 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004191 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4192 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004193 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4194 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4195 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4196 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004197 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4198 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004199 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4200 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4201 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4202 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004203 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4204 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004205 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4206 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004207 }
4208
Eric Laurent1c333e22014-05-20 10:48:17 -07004209 ALOGV("getNewOutputDevice() selected device %x", device);
4210 return device;
4211}
4212
4213audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4214{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004215 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004216
4217 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4218 if (index >= 0) {
4219 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4220 if (patchDesc->mUid != mUidCached) {
4221 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4222 inputDesc->mDevice, inputDesc->mPatchHandle);
4223 return inputDesc->mDevice;
4224 }
4225 }
4226
Eric Laurent1c333e22014-05-20 10:48:17 -07004227 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
4228
4229 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004230 return device;
4231}
4232
Eric Laurente0720872014-03-11 09:30:41 -07004233uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004234 return (uint32_t)getStrategy(stream);
4235}
4236
Eric Laurente0720872014-03-11 09:30:41 -07004237audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004238 // By checking the range of stream before calling getStrategy, we avoid
4239 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4240 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004241 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004242 return AUDIO_DEVICE_NONE;
4243 }
4244 audio_devices_t devices;
4245 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4246 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4247 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4248 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004249 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004250 if (outputDesc->isStrategyActive(strategy)) {
4251 devices = outputDesc->device();
4252 break;
4253 }
Eric Laurente552edb2014-03-10 17:42:56 -07004254 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004255
4256 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4257 and doesn't really need to.*/
4258 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4259 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4260 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4261 }
4262
Eric Laurente552edb2014-03-10 17:42:56 -07004263 return devices;
4264}
4265
Eric Laurente0720872014-03-11 09:30:41 -07004266AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004267 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004268
4269 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4270
Eric Laurente552edb2014-03-10 17:42:56 -07004271 // stream to strategy mapping
4272 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004273 case AUDIO_STREAM_VOICE_CALL:
4274 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004275 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004276 case AUDIO_STREAM_RING:
4277 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004278 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004279 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004280 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004281 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004282 return STRATEGY_DTMF;
4283 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004284 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004285 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004286 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4287 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004288 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004289 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004290 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004291 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004292 case AUDIO_STREAM_TTS:
4293 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004294 case AUDIO_STREAM_ACCESSIBILITY:
4295 return STRATEGY_ACCESSIBILITY;
4296 case AUDIO_STREAM_REROUTING:
4297 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004298 }
4299}
4300
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004301uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4302 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004303 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4304 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4305 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004306 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4307 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4308 }
4309
4310 // usage to strategy mapping
4311 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004312 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4313 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4314 return (uint32_t) STRATEGY_SONIFICATION;
4315 }
4316 if (isInCall()) {
4317 return (uint32_t) STRATEGY_PHONE;
4318 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004319 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004320
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004321 case AUDIO_USAGE_MEDIA:
4322 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004323 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4324 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4325 return (uint32_t) STRATEGY_MEDIA;
4326
4327 case AUDIO_USAGE_VOICE_COMMUNICATION:
4328 return (uint32_t) STRATEGY_PHONE;
4329
4330 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4331 return (uint32_t) STRATEGY_DTMF;
4332
4333 case AUDIO_USAGE_ALARM:
4334 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4335 return (uint32_t) STRATEGY_SONIFICATION;
4336
4337 case AUDIO_USAGE_NOTIFICATION:
4338 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4339 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4340 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4341 case AUDIO_USAGE_NOTIFICATION_EVENT:
4342 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4343
4344 case AUDIO_USAGE_UNKNOWN:
4345 default:
4346 return (uint32_t) STRATEGY_MEDIA;
4347 }
4348}
4349
Eric Laurente0720872014-03-11 09:30:41 -07004350void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004351 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004352 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004353 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4354 updateDevicesAndOutputs();
4355 break;
4356 default:
4357 break;
4358 }
4359}
4360
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004361bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4362 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4363 if (s == (size_t) streamToIgnore) {
4364 continue;
4365 }
4366 for (size_t i = 0; i < mOutputs.size(); i++) {
4367 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4368 if (outputDesc->mRefCount[s] != 0) {
4369 return true;
4370 }
4371 }
4372 }
4373 return false;
4374}
4375
4376uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4377 switch(event) {
4378 case STARTING_OUTPUT:
4379 mBeaconMuteRefCount++;
4380 break;
4381 case STOPPING_OUTPUT:
4382 if (mBeaconMuteRefCount > 0) {
4383 mBeaconMuteRefCount--;
4384 }
4385 break;
4386 case STARTING_BEACON:
4387 mBeaconPlayingRefCount++;
4388 break;
4389 case STOPPING_BEACON:
4390 if (mBeaconPlayingRefCount > 0) {
4391 mBeaconPlayingRefCount--;
4392 }
4393 break;
4394 }
4395
4396 if (mBeaconMuteRefCount > 0) {
4397 // any playback causes beacon to be muted
4398 return setBeaconMute(true);
4399 } else {
4400 // no other playback: unmute when beacon starts playing, mute when it stops
4401 return setBeaconMute(mBeaconPlayingRefCount == 0);
4402 }
4403}
4404
4405uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4406 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4407 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4408 // keep track of muted state to avoid repeating mute/unmute operations
4409 if (mBeaconMuted != mute) {
4410 // mute/unmute AUDIO_STREAM_TTS on all outputs
4411 ALOGV("\t muting %d", mute);
4412 uint32_t maxLatency = 0;
4413 for (size_t i = 0; i < mOutputs.size(); i++) {
4414 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4415 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4416 desc->mIoHandle,
4417 0 /*delay*/, AUDIO_DEVICE_NONE);
4418 const uint32_t latency = desc->latency() * 2;
4419 if (latency > maxLatency) {
4420 maxLatency = latency;
4421 }
4422 }
4423 mBeaconMuted = mute;
4424 return maxLatency;
4425 }
4426 return 0;
4427}
4428
Eric Laurente0720872014-03-11 09:30:41 -07004429audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004430 bool fromCache)
4431{
4432 uint32_t device = AUDIO_DEVICE_NONE;
4433
4434 if (fromCache) {
4435 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4436 strategy, mDeviceForStrategy[strategy]);
4437 return mDeviceForStrategy[strategy];
4438 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004439 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004440 switch (strategy) {
4441
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004442 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4443 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4444 if (!device) {
4445 ALOGE("getDeviceForStrategy() no device found for "\
4446 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4447 }
4448 break;
4449
Eric Laurente552edb2014-03-10 17:42:56 -07004450 case STRATEGY_SONIFICATION_RESPECTFUL:
4451 if (isInCall()) {
4452 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004453 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004454 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4455 // while media is playing on a remote device, use the the sonification behavior.
4456 // Note that we test this usecase before testing if media is playing because
4457 // the isStreamActive() method only informs about the activity of a stream, not
4458 // if it's for local playback. Note also that we use the same delay between both tests
4459 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004460 //user "safe" speaker if available instead of normal speaker to avoid triggering
4461 //other acoustic safety mechanisms for notification
4462 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4463 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004464 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004465 // while media is playing (or has recently played), use the same device
4466 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4467 } else {
4468 // when media is not playing anymore, fall back on the sonification behavior
4469 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004470 //user "safe" speaker if available instead of normal speaker to avoid triggering
4471 //other acoustic safety mechanisms for notification
4472 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4473 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004474 }
4475
4476 break;
4477
4478 case STRATEGY_DTMF:
4479 if (!isInCall()) {
4480 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4481 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4482 break;
4483 }
4484 // when in call, DTMF and PHONE strategies follow the same rules
4485 // FALL THROUGH
4486
4487 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004488 // Force use of only devices on primary output if:
4489 // - in call AND
4490 // - cannot route from voice call RX OR
4491 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4492 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4493 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4494 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4495 if (((mAvailableInputDevices.types() &
4496 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4497 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004498 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004499 AUDIO_DEVICE_API_VERSION_3_0))) {
4500 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4501 }
4502 }
Eric Laurente552edb2014-03-10 17:42:56 -07004503 // for phone strategy, we first consider the forced use and then the available devices by order
4504 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004505 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4506 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004507 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004508 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004509 if (device) break;
4510 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004511 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004512 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004513 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004514 if (device) break;
4515 // if SCO device is requested but no SCO device is available, fall back to default case
4516 // FALL THROUGH
4517
4518 default: // FORCE_NONE
4519 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004520 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004521 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004522 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004523 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004524 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004525 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004526 if (device) break;
4527 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004528 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004529 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004530 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004531 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004532 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4533 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004534 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004535 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004536 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004537 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004538 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004539 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004540 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004541 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004542 if (device) break;
4543 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004544 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004545 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004546 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004547 if (device == AUDIO_DEVICE_NONE) {
4548 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4549 }
4550 break;
4551
Eric Laurent3b73df72014-03-11 09:06:29 -07004552 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004553 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4554 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004555 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004556 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004557 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004558 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004559 if (device) break;
4560 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004561 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004562 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004563 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004564 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004565 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004566 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004567 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004568 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004569 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004570 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004571 if (device) break;
4572 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004573 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4574 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004575 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004576 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004577 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004578 if (device == AUDIO_DEVICE_NONE) {
4579 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4580 }
4581 break;
4582 }
4583 break;
4584
4585 case STRATEGY_SONIFICATION:
4586
4587 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4588 // handleIncallSonification().
4589 if (isInCall()) {
4590 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4591 break;
4592 }
4593 // FALL THROUGH
4594
4595 case STRATEGY_ENFORCED_AUDIBLE:
4596 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4597 // except:
4598 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4599 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4600
4601 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004602 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004603 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004604 if (device == AUDIO_DEVICE_NONE) {
4605 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4606 }
4607 }
4608 // The second device used for sonification is the same as the device used by media strategy
4609 // FALL THROUGH
4610
Eric Laurent223fd5c2014-11-11 13:43:36 -08004611 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4612 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004613 if (strategy == STRATEGY_ACCESSIBILITY) {
4614 // do not route accessibility prompts to a digital output currently configured with a
4615 // compressed format as they would likely not be mixed and dropped.
4616 for (size_t i = 0; i < mOutputs.size(); i++) {
4617 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4618 audio_devices_t devices = desc->device() &
4619 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4620 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4621 devices != AUDIO_DEVICE_NONE) {
4622 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4623 }
4624 }
4625 }
4626 // FALL THROUGH
4627
Eric Laurent223fd5c2014-11-11 13:43:36 -08004628 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004629 case STRATEGY_MEDIA: {
4630 uint32_t device2 = AUDIO_DEVICE_NONE;
4631 if (strategy != STRATEGY_SONIFICATION) {
4632 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004633 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4634 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4635 }
Eric Laurente552edb2014-03-10 17:42:56 -07004636 }
4637 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004638 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004639 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004640 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004641 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004642 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004643 }
4644 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004645 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004646 }
4647 }
Hochi Huang327cb702014-09-21 09:47:31 +08004648 if ((device2 == AUDIO_DEVICE_NONE) &&
4649 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4650 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4651 }
Eric Laurente552edb2014-03-10 17:42:56 -07004652 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004653 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004654 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004655 if ((device2 == AUDIO_DEVICE_NONE)) {
4656 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4657 }
Eric Laurente552edb2014-03-10 17:42:56 -07004658 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004659 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004660 }
4661 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004662 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004663 }
4664 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004665 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004666 }
4667 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004668 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004669 }
4670 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4671 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004672 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004673 }
4674 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004675 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004676 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004677 }
4678 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004679 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004680 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004681 int device3 = AUDIO_DEVICE_NONE;
4682 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004683 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004684 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4685 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004686 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004687 }
Eric Laurente552edb2014-03-10 17:42:56 -07004688
Jungshik Jang839e4f32014-06-26 17:23:40 +09004689 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004690 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4691 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4692 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004693
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004694 // If hdmi system audio mode is on, remove speaker out of output list.
4695 if ((strategy == STRATEGY_MEDIA) &&
4696 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4697 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4698 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4699 }
4700
Eric Laurente552edb2014-03-10 17:42:56 -07004701 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004702 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004703 if (device == AUDIO_DEVICE_NONE) {
4704 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4705 }
4706 } break;
4707
4708 default:
4709 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4710 break;
4711 }
4712
4713 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4714 return device;
4715}
4716
Eric Laurente0720872014-03-11 09:30:41 -07004717void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004718{
4719 for (int i = 0; i < NUM_STRATEGIES; i++) {
4720 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4721 }
4722 mPreviousOutputs = mOutputs;
4723}
4724
Eric Laurent1f2f2232014-06-02 12:01:23 -07004725uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004726 audio_devices_t prevDevice,
4727 uint32_t delayMs)
4728{
4729 // mute/unmute strategies using an incompatible device combination
4730 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4731 // if unmuting, unmute only after the specified delay
4732 if (outputDesc->isDuplicated()) {
4733 return 0;
4734 }
4735
4736 uint32_t muteWaitMs = 0;
4737 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004738 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004739
4740 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4741 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004742 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004743 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4744 bool doMute = false;
4745
4746 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4747 doMute = true;
4748 outputDesc->mStrategyMutedByDevice[i] = true;
4749 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4750 doMute = true;
4751 outputDesc->mStrategyMutedByDevice[i] = false;
4752 }
Eric Laurent99401132014-05-07 19:48:15 -07004753 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004754 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004755 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004756 // skip output if it does not share any device with current output
4757 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4758 == AUDIO_DEVICE_NONE) {
4759 continue;
4760 }
4761 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4762 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4763 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4764 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4765 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004766 if (mute) {
4767 // FIXME: should not need to double latency if volume could be applied
4768 // immediately by the audioflinger mixer. We must account for the delay
4769 // between now and the next time the audioflinger thread for this output
4770 // will process a buffer (which corresponds to one buffer size,
4771 // usually 1/2 or 1/4 of the latency).
4772 if (muteWaitMs < desc->latency() * 2) {
4773 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004774 }
4775 }
4776 }
4777 }
4778 }
4779 }
4780
Eric Laurent99401132014-05-07 19:48:15 -07004781 // temporary mute output if device selection changes to avoid volume bursts due to
4782 // different per device volumes
4783 if (outputDesc->isActive() && (device != prevDevice)) {
4784 if (muteWaitMs < outputDesc->latency() * 2) {
4785 muteWaitMs = outputDesc->latency() * 2;
4786 }
4787 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4788 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004789 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004790 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004791 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004792 muteWaitMs *2, device);
4793 }
4794 }
4795 }
4796
Eric Laurente552edb2014-03-10 17:42:56 -07004797 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4798 if (muteWaitMs > delayMs) {
4799 muteWaitMs -= delayMs;
4800 usleep(muteWaitMs * 1000);
4801 return muteWaitMs;
4802 }
4803 return 0;
4804}
4805
Eric Laurente0720872014-03-11 09:30:41 -07004806uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004807 audio_devices_t device,
4808 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004809 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004810 audio_patch_handle_t *patchHandle,
4811 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004812{
4813 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004814 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004815 AudioParameter param;
4816 uint32_t muteWaitMs;
4817
4818 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004819 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4820 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004821 return muteWaitMs;
4822 }
4823 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4824 // output profile
4825 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004826 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004827 return 0;
4828 }
4829
4830 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004831 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004832
4833 audio_devices_t prevDevice = outputDesc->mDevice;
4834
4835 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4836
4837 if (device != AUDIO_DEVICE_NONE) {
4838 outputDesc->mDevice = device;
4839 }
4840 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4841
4842 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004843 // the requested device is AUDIO_DEVICE_NONE
4844 // OR the requested device is the same as current device
4845 // AND force is not specified
4846 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004847 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004848 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4849 outputDesc->mPatchHandle != 0) {
4850 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4851 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004852 return muteWaitMs;
4853 }
4854
4855 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004856
Eric Laurente552edb2014-03-10 17:42:56 -07004857 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004858 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004859 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004860 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004861 DeviceVector deviceList = (address == NULL) ?
4862 mAvailableOutputDevices.getDevicesFromType(device)
4863 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004864 if (!deviceList.isEmpty()) {
4865 struct audio_patch patch;
4866 outputDesc->toAudioPortConfig(&patch.sources[0]);
4867 patch.num_sources = 1;
4868 patch.num_sinks = 0;
4869 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4870 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004871 patch.num_sinks++;
4872 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004873 ssize_t index;
4874 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4875 index = mAudioPatches.indexOfKey(*patchHandle);
4876 } else {
4877 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4878 }
4879 sp< AudioPatch> patchDesc;
4880 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4881 if (index >= 0) {
4882 patchDesc = mAudioPatches.valueAt(index);
4883 afPatchHandle = patchDesc->mAfPatchHandle;
4884 }
4885
Eric Laurent1c333e22014-05-20 10:48:17 -07004886 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004887 &afPatchHandle,
4888 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004889 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4890 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004891 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004892 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004893 if (index < 0) {
4894 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4895 &patch, mUidCached);
4896 addAudioPatch(patchDesc->mHandle, patchDesc);
4897 } else {
4898 patchDesc->mPatch = patch;
4899 }
4900 patchDesc->mAfPatchHandle = afPatchHandle;
4901 patchDesc->mUid = mUidCached;
4902 if (patchHandle) {
4903 *patchHandle = patchDesc->mHandle;
4904 }
4905 outputDesc->mPatchHandle = patchDesc->mHandle;
4906 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004907 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004908 }
4909 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004910
4911 // inform all input as well
4912 for (size_t i = 0; i < mInputs.size(); i++) {
4913 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4914 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4915 AudioParameter inputCmd = AudioParameter();
4916 ALOGV("%s: inform input %d of device:%d", __func__,
4917 inputDescriptor->mIoHandle, device);
4918 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4919 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4920 inputCmd.toString(),
4921 delayMs);
4922 }
4923 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004924 }
Eric Laurente552edb2014-03-10 17:42:56 -07004925
4926 // update stream volumes according to new device
4927 applyStreamVolumes(output, device, delayMs);
4928
4929 return muteWaitMs;
4930}
4931
Eric Laurent1c333e22014-05-20 10:48:17 -07004932status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 int delayMs,
4934 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004935{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004936 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004937 ssize_t index;
4938 if (patchHandle) {
4939 index = mAudioPatches.indexOfKey(*patchHandle);
4940 } else {
4941 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4942 }
4943 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004944 return INVALID_OPERATION;
4945 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004946 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4947 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004948 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4949 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 removeAudioPatch(patchDesc->mHandle);
4951 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004952 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004953 return status;
4954}
4955
4956status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4957 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 bool force,
4959 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004960{
4961 status_t status = NO_ERROR;
4962
Eric Laurent1f2f2232014-06-02 12:01:23 -07004963 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004964 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4965 inputDesc->mDevice = device;
4966
4967 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4968 if (!deviceList.isEmpty()) {
4969 struct audio_patch patch;
4970 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004971 // AUDIO_SOURCE_HOTWORD is for internal use only:
4972 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004973 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4974 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004975 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4976 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004977 patch.num_sinks = 1;
4978 //only one input device for now
4979 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004980 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004981 ssize_t index;
4982 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4983 index = mAudioPatches.indexOfKey(*patchHandle);
4984 } else {
4985 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4986 }
4987 sp< AudioPatch> patchDesc;
4988 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4989 if (index >= 0) {
4990 patchDesc = mAudioPatches.valueAt(index);
4991 afPatchHandle = patchDesc->mAfPatchHandle;
4992 }
4993
Eric Laurent1c333e22014-05-20 10:48:17 -07004994 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004995 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004996 0);
4997 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004999 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005000 if (index < 0) {
5001 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5002 &patch, mUidCached);
5003 addAudioPatch(patchDesc->mHandle, patchDesc);
5004 } else {
5005 patchDesc->mPatch = patch;
5006 }
5007 patchDesc->mAfPatchHandle = afPatchHandle;
5008 patchDesc->mUid = mUidCached;
5009 if (patchHandle) {
5010 *patchHandle = patchDesc->mHandle;
5011 }
5012 inputDesc->mPatchHandle = patchDesc->mHandle;
5013 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005014 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005015 }
5016 }
5017 }
5018 return status;
5019}
5020
Eric Laurent6a94d692014-05-20 11:18:06 -07005021status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5022 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005023{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005024 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005025 ssize_t index;
5026 if (patchHandle) {
5027 index = mAudioPatches.indexOfKey(*patchHandle);
5028 } else {
5029 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5030 }
5031 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005032 return INVALID_OPERATION;
5033 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005034 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5035 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005036 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5037 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005038 removeAudioPatch(patchDesc->mHandle);
5039 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005040 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005041 return status;
5042}
5043
5044sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08005045 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07005046 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005047 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005048 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07005049 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005050{
5051 // Choose an input profile based on the requested capture parameters: select the first available
5052 // profile supporting all requested parameters.
5053
5054 for (size_t i = 0; i < mHwModules.size(); i++)
5055 {
5056 if (mHwModules[i]->mHandle == 0) {
5057 continue;
5058 }
5059 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5060 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005061 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005062 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005063 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005064 &samplingRate /*updatedSamplingRate*/,
5065 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005066
Eric Laurente552edb2014-03-10 17:42:56 -07005067 return profile;
5068 }
5069 }
5070 }
5071 return NULL;
5072}
5073
Eric Laurent275e8e92014-11-30 15:14:47 -08005074audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource,
Eric Laurentc722f302014-12-10 11:21:49 -08005075 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005076{
5077 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005078 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5079 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005080
5081 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5082 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5083 continue;
5084 }
5085 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5086 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5087 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5088 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5089 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5090 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurentc722f302014-12-10 11:21:49 -08005091 if (policyMix != NULL) {
5092 *policyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005093 }
5094 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5095 }
5096 break;
5097 }
5098 }
5099 }
5100
Eric Laurente552edb2014-03-10 17:42:56 -07005101 switch (inputSource) {
5102 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005103 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005104 device = AUDIO_DEVICE_IN_VOICE_CALL;
5105 break;
5106 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005107 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005108
5109 case AUDIO_SOURCE_DEFAULT:
5110 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005111 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5112 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005113 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5114 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5115 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5116 device = AUDIO_DEVICE_IN_USB_DEVICE;
5117 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5118 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005119 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005120 break;
5121
5122 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5123 // Allow only use of devices on primary input if in call and HAL does not support routing
5124 // to voice call path.
5125 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5126 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5127 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5128 }
5129
5130 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5131 case AUDIO_POLICY_FORCE_BT_SCO:
5132 // if SCO device is requested but no SCO device is available, fall back to default case
5133 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5134 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5135 break;
5136 }
5137 // FALL THROUGH
5138
5139 default: // FORCE_NONE
5140 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5141 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5142 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5143 device = AUDIO_DEVICE_IN_USB_DEVICE;
5144 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5145 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5146 }
5147 break;
5148
5149 case AUDIO_POLICY_FORCE_SPEAKER:
5150 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5151 device = AUDIO_DEVICE_IN_BACK_MIC;
5152 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5153 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5154 }
5155 break;
5156 }
5157 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005158
Eric Laurente552edb2014-03-10 17:42:56 -07005159 case AUDIO_SOURCE_VOICE_RECOGNITION:
5160 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005161 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005162 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005163 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005164 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005165 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005166 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5167 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005168 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005169 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5170 }
5171 break;
5172 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005173 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005174 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005175 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005176 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5177 }
5178 break;
5179 case AUDIO_SOURCE_VOICE_DOWNLINK:
5180 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005181 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005182 device = AUDIO_DEVICE_IN_VOICE_CALL;
5183 }
5184 break;
5185 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005186 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005187 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5188 }
5189 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005190 case AUDIO_SOURCE_FM_TUNER:
5191 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5192 device = AUDIO_DEVICE_IN_FM_TUNER;
5193 }
5194 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005195 default:
5196 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5197 break;
5198 }
5199 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5200 return device;
5201}
5202
Eric Laurente0720872014-03-11 09:30:41 -07005203bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005204{
5205 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5206 device &= ~AUDIO_DEVICE_BIT_IN;
5207 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5208 return true;
5209 }
5210 return false;
5211}
5212
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005213bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005214 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005215}
5216
Eric Laurente0720872014-03-11 09:30:41 -07005217audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005218{
5219 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005220 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005221 if ((input_descriptor->mRefCount > 0)
5222 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5223 return mInputs.keyAt(i);
5224 }
5225 }
5226 return 0;
5227}
5228
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005229uint32_t AudioPolicyManager::activeInputsCount() const
5230{
5231 uint32_t count = 0;
5232 for (size_t i = 0; i < mInputs.size(); i++) {
5233 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5234 if (desc->mRefCount > 0) {
5235 return count++;
5236 }
5237 }
5238 return count;
5239}
5240
Eric Laurente552edb2014-03-10 17:42:56 -07005241
Eric Laurente0720872014-03-11 09:30:41 -07005242audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005243{
5244 if (device == AUDIO_DEVICE_NONE) {
5245 // this happens when forcing a route update and no track is active on an output.
5246 // In this case the returned category is not important.
5247 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005248 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005249 // Multiple device selection is either:
5250 // - speaker + one other device: give priority to speaker in this case.
5251 // - one A2DP device + another device: happens with duplicated output. In this case
5252 // retain the device on the A2DP output as the other must not correspond to an active
5253 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005254 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005255 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5256 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005257 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5258 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5259 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5260 device = AUDIO_DEVICE_OUT_AUX_LINE;
5261 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5262 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005263 } else {
5264 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5265 }
5266 }
5267
Jon Eklund11c9fb12014-06-23 14:47:03 -05005268 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5269 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5270 device = AUDIO_DEVICE_OUT_SPEAKER;
5271
Eric Laurent3b73df72014-03-11 09:06:29 -07005272 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005273 "getDeviceForVolume() invalid device combination: %08x",
5274 device);
5275
5276 return device;
5277}
5278
Eric Laurente0720872014-03-11 09:30:41 -07005279AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005280{
5281 switch(getDeviceForVolume(device)) {
5282 case AUDIO_DEVICE_OUT_EARPIECE:
5283 return DEVICE_CATEGORY_EARPIECE;
5284 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5285 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5286 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5287 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5288 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5289 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5290 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005291 case AUDIO_DEVICE_OUT_LINE:
5292 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5293 /*USB? Remote submix?*/
5294 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005295 case AUDIO_DEVICE_OUT_SPEAKER:
5296 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5297 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005298 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5299 case AUDIO_DEVICE_OUT_USB_DEVICE:
5300 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5301 default:
5302 return DEVICE_CATEGORY_SPEAKER;
5303 }
5304}
5305
Eric Laurent223fd5c2014-11-11 13:43:36 -08005306/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005307float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005308 int indexInUi)
5309{
5310 device_category deviceCategory = getDeviceCategory(device);
5311 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5312
5313 // the volume index in the UI is relative to the min and max volume indices for this stream type
5314 int nbSteps = 1 + curve[VOLMAX].mIndex -
5315 curve[VOLMIN].mIndex;
5316 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5317 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5318
5319 // find what part of the curve this index volume belongs to, or if it's out of bounds
5320 int segment = 0;
5321 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5322 return 0.0f;
5323 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5324 segment = 0;
5325 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5326 segment = 1;
5327 } else if (volIdx <= curve[VOLMAX].mIndex) {
5328 segment = 2;
5329 } else { // out of bounds
5330 return 1.0f;
5331 }
5332
5333 // linear interpolation in the attenuation table in dB
5334 float decibels = curve[segment].mDBAttenuation +
5335 ((float)(volIdx - curve[segment].mIndex)) *
5336 ( (curve[segment+1].mDBAttenuation -
5337 curve[segment].mDBAttenuation) /
5338 ((float)(curve[segment+1].mIndex -
5339 curve[segment].mIndex)) );
5340
5341 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5342
5343 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5344 curve[segment].mIndex, volIdx,
5345 curve[segment+1].mIndex,
5346 curve[segment].mDBAttenuation,
5347 decibels,
5348 curve[segment+1].mDBAttenuation,
5349 amplification);
5350
5351 return amplification;
5352}
5353
Eric Laurente0720872014-03-11 09:30:41 -07005354const AudioPolicyManager::VolumeCurvePoint
5355 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005356 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5357};
5358
Eric Laurente0720872014-03-11 09:30:41 -07005359const AudioPolicyManager::VolumeCurvePoint
5360 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005361 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5362};
5363
Eric Laurente0720872014-03-11 09:30:41 -07005364const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005365 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5366 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5367};
5368
5369const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005370 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005371 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5372};
5373
Eric Laurente0720872014-03-11 09:30:41 -07005374const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005375 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005376 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005377};
5378
5379const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005380 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005381 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5382};
5383
Eric Laurente0720872014-03-11 09:30:41 -07005384const AudioPolicyManager::VolumeCurvePoint
5385 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005386 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5387};
5388
5389// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5390// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5391// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5392// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5393
Eric Laurente0720872014-03-11 09:30:41 -07005394const AudioPolicyManager::VolumeCurvePoint
5395 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005396 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5397};
5398
Eric Laurente0720872014-03-11 09:30:41 -07005399const AudioPolicyManager::VolumeCurvePoint
5400 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005401 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5402};
5403
Eric Laurente0720872014-03-11 09:30:41 -07005404const AudioPolicyManager::VolumeCurvePoint
5405 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005406 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5407};
5408
Eric Laurente0720872014-03-11 09:30:41 -07005409const AudioPolicyManager::VolumeCurvePoint
5410 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005411 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5412};
5413
Eric Laurente0720872014-03-11 09:30:41 -07005414const AudioPolicyManager::VolumeCurvePoint
5415 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005416 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5417};
5418
Eric Laurente0720872014-03-11 09:30:41 -07005419const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005420 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5421 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5422};
5423
5424const AudioPolicyManager::VolumeCurvePoint
5425 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5426 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5427};
5428
5429const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005430 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5431 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5432};
5433
5434const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005435 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5436 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005437 { // AUDIO_STREAM_VOICE_CALL
5438 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5439 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005440 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5441 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005442 },
5443 { // AUDIO_STREAM_SYSTEM
5444 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5445 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005446 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5447 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005448 },
5449 { // AUDIO_STREAM_RING
5450 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5451 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005452 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5453 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005454 },
5455 { // AUDIO_STREAM_MUSIC
5456 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5457 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005458 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5459 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005460 },
5461 { // AUDIO_STREAM_ALARM
5462 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5463 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005464 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5465 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005466 },
5467 { // AUDIO_STREAM_NOTIFICATION
5468 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5469 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005470 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5471 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005472 },
5473 { // AUDIO_STREAM_BLUETOOTH_SCO
5474 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5475 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005476 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5477 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005478 },
5479 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5480 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5481 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005482 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5483 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005484 },
5485 { // AUDIO_STREAM_DTMF
5486 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5487 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005488 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5489 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005490 },
5491 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005492 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5493 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5494 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5495 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5496 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005497 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005498 { // AUDIO_STREAM_ACCESSIBILITY
5499 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5500 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5501 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5502 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5503 },
5504 { // AUDIO_STREAM_REROUTING
5505 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5506 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5507 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5508 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5509 },
5510 { // AUDIO_STREAM_PATCH
5511 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5512 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5513 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5514 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5515 },
Eric Laurente552edb2014-03-10 17:42:56 -07005516};
5517
Eric Laurente0720872014-03-11 09:30:41 -07005518void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005519{
5520 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5521 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5522 mStreams[i].mVolumeCurve[j] =
5523 sVolumeProfiles[i][j];
5524 }
5525 }
5526
5527 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5528 if (mSpeakerDrcEnabled) {
5529 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5530 sDefaultSystemVolumeCurveDrc;
5531 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5532 sSpeakerSonificationVolumeCurveDrc;
5533 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5534 sSpeakerSonificationVolumeCurveDrc;
5535 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5536 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005537 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5538 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005539 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5540 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005541 }
5542}
5543
Eric Laurente0720872014-03-11 09:30:41 -07005544float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005545 int index,
5546 audio_io_handle_t output,
5547 audio_devices_t device)
5548{
5549 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005550 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005551 StreamDescriptor &streamDesc = mStreams[stream];
5552
5553 if (device == AUDIO_DEVICE_NONE) {
5554 device = outputDesc->device();
5555 }
5556
Eric Laurente552edb2014-03-10 17:42:56 -07005557 volume = volIndexToAmpl(device, streamDesc, index);
5558
5559 // if a headset is connected, apply the following rules to ring tones and notifications
5560 // to avoid sound level bursts in user's ears:
5561 // - always attenuate ring tones and notifications volume by 6dB
5562 // - if music is playing, always limit the volume to current music volume,
5563 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005564 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005565 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5566 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5567 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5568 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5569 ((stream_strategy == STRATEGY_SONIFICATION)
5570 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005571 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005572 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005573 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005574 streamDesc.mCanBeMuted) {
5575 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5576 // when the phone is ringing we must consider that music could have been paused just before
5577 // by the music application and behave as if music was active if the last music track was
5578 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005579 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005580 mLimitRingtoneVolume) {
5581 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005582 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5583 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005584 output,
5585 musicDevice);
5586 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5587 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5588 if (volume > minVol) {
5589 volume = minVol;
5590 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5591 }
5592 }
5593 }
5594
5595 return volume;
5596}
5597
Eric Laurente0720872014-03-11 09:30:41 -07005598status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005599 int index,
5600 audio_io_handle_t output,
5601 audio_devices_t device,
5602 int delayMs,
5603 bool force)
5604{
5605
5606 // do not change actual stream volume if the stream is muted
5607 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5608 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5609 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5610 return NO_ERROR;
5611 }
5612
5613 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005614 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5615 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5616 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5617 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005618 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005619 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005620 return INVALID_OPERATION;
5621 }
5622
5623 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005624 // unit gain if rerouting to external policy
5625 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5626 ssize_t index = mOutputs.indexOfKey(output);
5627 if (index >= 0) {
5628 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurentc722f302014-12-10 11:21:49 -08005629 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005630 ALOGV("max gain when rerouting for output=%d", output);
5631 volume = 1.0f;
5632 }
5633 }
5634
5635 }
Eric Laurente552edb2014-03-10 17:42:56 -07005636 // We actually change the volume if:
5637 // - the float value returned by computeVolume() changed
5638 // - the force flag is set
5639 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5640 force) {
5641 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5642 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5643 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5644 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005645 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5646 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005647 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005648 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005649 }
5650
Eric Laurent3b73df72014-03-11 09:06:29 -07005651 if (stream == AUDIO_STREAM_VOICE_CALL ||
5652 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005653 float voiceVolume;
5654 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005655 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005656 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5657 } else {
5658 voiceVolume = 1.0;
5659 }
5660
5661 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5662 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5663 mLastVoiceVolume = voiceVolume;
5664 }
5665 }
5666
5667 return NO_ERROR;
5668}
5669
Eric Laurente0720872014-03-11 09:30:41 -07005670void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005671 audio_devices_t device,
5672 int delayMs,
5673 bool force)
5674{
5675 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5676
Eric Laurent3b73df72014-03-11 09:06:29 -07005677 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005678 if (stream == AUDIO_STREAM_PATCH) {
5679 continue;
5680 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005681 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005682 mStreams[stream].getVolumeIndex(device),
5683 output,
5684 device,
5685 delayMs,
5686 force);
5687 }
5688}
5689
Eric Laurente0720872014-03-11 09:30:41 -07005690void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005691 bool on,
5692 audio_io_handle_t output,
5693 int delayMs,
5694 audio_devices_t device)
5695{
5696 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005697 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005698 if (stream == AUDIO_STREAM_PATCH) {
5699 continue;
5700 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005701 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5702 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005703 }
5704 }
5705}
5706
Eric Laurente0720872014-03-11 09:30:41 -07005707void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005708 bool on,
5709 audio_io_handle_t output,
5710 int delayMs,
5711 audio_devices_t device)
5712{
5713 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005714 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005715 if (device == AUDIO_DEVICE_NONE) {
5716 device = outputDesc->device();
5717 }
5718
5719 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5720 stream, on, output, outputDesc->mMuteCount[stream], device);
5721
5722 if (on) {
5723 if (outputDesc->mMuteCount[stream] == 0) {
5724 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005725 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5726 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005727 checkAndSetVolume(stream, 0, output, device, delayMs);
5728 }
5729 }
5730 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5731 outputDesc->mMuteCount[stream]++;
5732 } else {
5733 if (outputDesc->mMuteCount[stream] == 0) {
5734 ALOGV("setStreamMute() unmuting non muted stream!");
5735 return;
5736 }
5737 if (--outputDesc->mMuteCount[stream] == 0) {
5738 checkAndSetVolume(stream,
5739 streamDesc.getVolumeIndex(device),
5740 output,
5741 device,
5742 delayMs);
5743 }
5744 }
5745}
5746
Eric Laurente0720872014-03-11 09:30:41 -07005747void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005748 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005749{
5750 // if the stream pertains to sonification strategy and we are in call we must
5751 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5752 // in the device used for phone strategy and play the tone if the selected device does not
5753 // interfere with the device used for phone strategy
5754 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5755 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005756 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005757 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5758 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005759 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005760 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5761 stream, starting, outputDesc->mDevice, stateChange);
5762 if (outputDesc->mRefCount[stream]) {
5763 int muteCount = 1;
5764 if (stateChange) {
5765 muteCount = outputDesc->mRefCount[stream];
5766 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005767 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005768 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5769 for (int i = 0; i < muteCount; i++) {
5770 setStreamMute(stream, starting, mPrimaryOutput);
5771 }
5772 } else {
5773 ALOGV("handleIncallSonification() high visibility");
5774 if (outputDesc->device() &
5775 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5776 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5777 for (int i = 0; i < muteCount; i++) {
5778 setStreamMute(stream, starting, mPrimaryOutput);
5779 }
5780 }
5781 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005782 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5783 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005784 } else {
5785 mpClientInterface->stopTone();
5786 }
5787 }
5788 }
5789 }
5790}
5791
Eric Laurente0720872014-03-11 09:30:41 -07005792bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005793{
5794 return isStateInCall(mPhoneState);
5795}
5796
Eric Laurente0720872014-03-11 09:30:41 -07005797bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005798 return ((state == AUDIO_MODE_IN_CALL) ||
5799 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005800}
5801
Eric Laurente0720872014-03-11 09:30:41 -07005802uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005803{
5804 return MAX_EFFECTS_CPU_LOAD;
5805}
5806
Eric Laurente0720872014-03-11 09:30:41 -07005807uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005808{
5809 return MAX_EFFECTS_MEMORY;
5810}
5811
Eric Laurent6a94d692014-05-20 11:18:06 -07005812
Eric Laurente552edb2014-03-10 17:42:56 -07005813// --- AudioOutputDescriptor class implementation
5814
Eric Laurente0720872014-03-11 09:30:41 -07005815AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005816 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005817 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurentc722f302014-12-10 11:21:49 -08005818 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
Eric Laurent275e8e92014-11-30 15:14:47 -08005819 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005820 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5821{
5822 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005823 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005824 mRefCount[i] = 0;
5825 mCurVolume[i] = -1.0;
5826 mMuteCount[i] = 0;
5827 mStopTime[i] = 0;
5828 }
5829 for (int i = 0; i < NUM_STRATEGIES; i++) {
5830 mStrategyMutedByDevice[i] = false;
5831 }
5832 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005833 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005834 mSamplingRate = profile->pickSamplingRate();
5835 mFormat = profile->pickFormat();
5836 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005837 if (profile->mGains.size() > 0) {
5838 profile->mGains[0]->getDefaultConfig(&mGain);
5839 }
Eric Laurente552edb2014-03-10 17:42:56 -07005840 }
5841}
5842
Eric Laurente0720872014-03-11 09:30:41 -07005843audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005844{
5845 if (isDuplicated()) {
5846 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5847 } else {
5848 return mDevice;
5849 }
5850}
5851
Eric Laurente0720872014-03-11 09:30:41 -07005852uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005853{
5854 if (isDuplicated()) {
5855 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5856 } else {
5857 return mLatency;
5858 }
5859}
5860
Eric Laurente0720872014-03-11 09:30:41 -07005861bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005862 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005863{
5864 if (isDuplicated()) {
5865 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5866 } else if (outputDesc->isDuplicated()){
5867 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5868 } else {
5869 return (mProfile->mModule == outputDesc->mProfile->mModule);
5870 }
5871}
5872
Eric Laurente0720872014-03-11 09:30:41 -07005873void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005874 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005875{
5876 // forward usage count change to attached outputs
5877 if (isDuplicated()) {
5878 mOutput1->changeRefCount(stream, delta);
5879 mOutput2->changeRefCount(stream, delta);
5880 }
5881 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005882 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5883 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005884 mRefCount[stream] = 0;
5885 return;
5886 }
5887 mRefCount[stream] += delta;
5888 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5889}
5890
Eric Laurente0720872014-03-11 09:30:41 -07005891audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005892{
5893 if (isDuplicated()) {
5894 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5895 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005896 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005897 }
5898}
5899
Eric Laurente0720872014-03-11 09:30:41 -07005900bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005901{
5902 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5903}
5904
Eric Laurente0720872014-03-11 09:30:41 -07005905bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005906 uint32_t inPastMs,
5907 nsecs_t sysTime) const
5908{
5909 if ((sysTime == 0) && (inPastMs != 0)) {
5910 sysTime = systemTime();
5911 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005912 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005913 if (i == AUDIO_STREAM_PATCH) {
5914 continue;
5915 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005916 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005917 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005918 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005919 return true;
5920 }
5921 }
5922 return false;
5923}
5924
Eric Laurente0720872014-03-11 09:30:41 -07005925bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005926 uint32_t inPastMs,
5927 nsecs_t sysTime) const
5928{
5929 if (mRefCount[stream] != 0) {
5930 return true;
5931 }
5932 if (inPastMs == 0) {
5933 return false;
5934 }
5935 if (sysTime == 0) {
5936 sysTime = systemTime();
5937 }
5938 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5939 return true;
5940 }
5941 return false;
5942}
5943
Eric Laurent1c333e22014-05-20 10:48:17 -07005944void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005945 struct audio_port_config *dstConfig,
5946 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005947{
Eric Laurent84c70242014-06-23 08:46:27 -07005948 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5949
Eric Laurent1f2f2232014-06-02 12:01:23 -07005950 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5951 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5952 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005953 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005954 }
5955 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5956
Eric Laurent6a94d692014-05-20 11:18:06 -07005957 dstConfig->id = mId;
5958 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5959 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005960 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5961 dstConfig->ext.mix.handle = mIoHandle;
5962 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005963}
5964
5965void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5966 struct audio_port *port) const
5967{
Eric Laurent84c70242014-06-23 08:46:27 -07005968 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005969 mProfile->toAudioPort(port);
5970 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005971 toAudioPortConfig(&port->active_config);
5972 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005973 port->ext.mix.handle = mIoHandle;
5974 port->ext.mix.latency_class =
5975 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5976}
Eric Laurente552edb2014-03-10 17:42:56 -07005977
Eric Laurente0720872014-03-11 09:30:41 -07005978status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005979{
5980 const size_t SIZE = 256;
5981 char buffer[SIZE];
5982 String8 result;
5983
Eric Laurent4d416952014-08-10 14:07:09 -07005984 snprintf(buffer, SIZE, " ID: %d\n", mId);
5985 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005986 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5987 result.append(buffer);
5988 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5989 result.append(buffer);
5990 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5991 result.append(buffer);
5992 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5993 result.append(buffer);
5994 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5995 result.append(buffer);
5996 snprintf(buffer, SIZE, " Devices %08x\n", device());
5997 result.append(buffer);
5998 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5999 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07006000 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6001 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
6002 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07006003 result.append(buffer);
6004 }
6005 write(fd, result.string(), result.size());
6006
6007 return NO_ERROR;
6008}
6009
6010// --- AudioInputDescriptor class implementation
6011
Eric Laurent1c333e22014-05-20 10:48:17 -07006012AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006013 : mId(0), mIoHandle(0),
Eric Laurentc722f302014-12-10 11:21:49 -08006014 mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006015 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07006016{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006017 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006018 mSamplingRate = profile->pickSamplingRate();
6019 mFormat = profile->pickFormat();
6020 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07006021 if (profile->mGains.size() > 0) {
6022 profile->mGains[0]->getDefaultConfig(&mGain);
6023 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006024 }
Eric Laurente552edb2014-03-10 17:42:56 -07006025}
6026
Eric Laurent1c333e22014-05-20 10:48:17 -07006027void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006028 struct audio_port_config *dstConfig,
6029 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006030{
Eric Laurent84c70242014-06-23 08:46:27 -07006031 ALOG_ASSERT(mProfile != 0,
6032 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07006033 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6034 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6035 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006036 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006037 }
6038
6039 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6040
Eric Laurent6a94d692014-05-20 11:18:06 -07006041 dstConfig->id = mId;
6042 dstConfig->role = AUDIO_PORT_ROLE_SINK;
6043 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07006044 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6045 dstConfig->ext.mix.handle = mIoHandle;
6046 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07006047}
6048
6049void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6050 struct audio_port *port) const
6051{
Eric Laurent84c70242014-06-23 08:46:27 -07006052 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6053
Eric Laurent1c333e22014-05-20 10:48:17 -07006054 mProfile->toAudioPort(port);
6055 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006056 toAudioPortConfig(&port->active_config);
6057 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006058 port->ext.mix.handle = mIoHandle;
6059 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6060}
6061
Eric Laurente0720872014-03-11 09:30:41 -07006062status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006063{
6064 const size_t SIZE = 256;
6065 char buffer[SIZE];
6066 String8 result;
6067
Eric Laurent4d416952014-08-10 14:07:09 -07006068 snprintf(buffer, SIZE, " ID: %d\n", mId);
6069 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006070 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6071 result.append(buffer);
6072 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6073 result.append(buffer);
6074 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6075 result.append(buffer);
6076 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6077 result.append(buffer);
6078 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6079 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006080 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6081 result.append(buffer);
6082
Eric Laurente552edb2014-03-10 17:42:56 -07006083 write(fd, result.string(), result.size());
6084
6085 return NO_ERROR;
6086}
6087
6088// --- StreamDescriptor class implementation
6089
Eric Laurente0720872014-03-11 09:30:41 -07006090AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006091 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6092{
6093 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6094}
6095
Eric Laurente0720872014-03-11 09:30:41 -07006096int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006097{
Eric Laurente0720872014-03-11 09:30:41 -07006098 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006099 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6100 if (mIndexCur.indexOfKey(device) < 0) {
6101 device = AUDIO_DEVICE_OUT_DEFAULT;
6102 }
6103 return mIndexCur.valueFor(device);
6104}
6105
Eric Laurente0720872014-03-11 09:30:41 -07006106void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006107{
6108 const size_t SIZE = 256;
6109 char buffer[SIZE];
6110 String8 result;
6111
6112 snprintf(buffer, SIZE, "%s %02d %02d ",
6113 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6114 result.append(buffer);
6115 for (size_t i = 0; i < mIndexCur.size(); i++) {
6116 snprintf(buffer, SIZE, "%04x : %02d, ",
6117 mIndexCur.keyAt(i),
6118 mIndexCur.valueAt(i));
6119 result.append(buffer);
6120 }
6121 result.append("\n");
6122
6123 write(fd, result.string(), result.size());
6124}
6125
6126// --- EffectDescriptor class implementation
6127
Eric Laurente0720872014-03-11 09:30:41 -07006128status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006129{
6130 const size_t SIZE = 256;
6131 char buffer[SIZE];
6132 String8 result;
6133
6134 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6135 result.append(buffer);
6136 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6137 result.append(buffer);
6138 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6139 result.append(buffer);
6140 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6141 result.append(buffer);
6142 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6143 result.append(buffer);
6144 write(fd, result.string(), result.size());
6145
6146 return NO_ERROR;
6147}
6148
Eric Laurent1c333e22014-05-20 10:48:17 -07006149// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006150
Eric Laurente0720872014-03-11 09:30:41 -07006151AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006152 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6153 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006154{
6155}
6156
Eric Laurente0720872014-03-11 09:30:41 -07006157AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006158{
6159 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006160 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006161 }
6162 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006163 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006164 }
6165 free((void *)mName);
6166}
6167
Eric Laurent1afeecb2014-05-14 08:52:28 -07006168status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6169{
6170 cnode *node = root->first_child;
6171
6172 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6173
6174 while (node) {
6175 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6176 profile->loadSamplingRates((char *)node->value);
6177 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6178 profile->loadFormats((char *)node->value);
6179 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6180 profile->loadInChannels((char *)node->value);
6181 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6182 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6183 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006184 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6185 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006186 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6187 profile->loadGains(node);
6188 }
6189 node = node->next;
6190 }
6191 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6192 "loadInput() invalid supported devices");
6193 ALOGW_IF(profile->mChannelMasks.size() == 0,
6194 "loadInput() invalid supported channel masks");
6195 ALOGW_IF(profile->mSamplingRates.size() == 0,
6196 "loadInput() invalid supported sampling rates");
6197 ALOGW_IF(profile->mFormats.size() == 0,
6198 "loadInput() invalid supported formats");
6199 if (!profile->mSupportedDevices.isEmpty() &&
6200 (profile->mChannelMasks.size() != 0) &&
6201 (profile->mSamplingRates.size() != 0) &&
6202 (profile->mFormats.size() != 0)) {
6203
6204 ALOGV("loadInput() adding input Supported Devices %04x",
6205 profile->mSupportedDevices.types());
6206
6207 mInputProfiles.add(profile);
6208 return NO_ERROR;
6209 } else {
6210 return BAD_VALUE;
6211 }
6212}
6213
6214status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6215{
6216 cnode *node = root->first_child;
6217
6218 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6219
6220 while (node) {
6221 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6222 profile->loadSamplingRates((char *)node->value);
6223 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6224 profile->loadFormats((char *)node->value);
6225 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6226 profile->loadOutChannels((char *)node->value);
6227 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6228 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6229 mDeclaredDevices);
6230 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006231 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006232 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6233 profile->loadGains(node);
6234 }
6235 node = node->next;
6236 }
6237 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6238 "loadOutput() invalid supported devices");
6239 ALOGW_IF(profile->mChannelMasks.size() == 0,
6240 "loadOutput() invalid supported channel masks");
6241 ALOGW_IF(profile->mSamplingRates.size() == 0,
6242 "loadOutput() invalid supported sampling rates");
6243 ALOGW_IF(profile->mFormats.size() == 0,
6244 "loadOutput() invalid supported formats");
6245 if (!profile->mSupportedDevices.isEmpty() &&
6246 (profile->mChannelMasks.size() != 0) &&
6247 (profile->mSamplingRates.size() != 0) &&
6248 (profile->mFormats.size() != 0)) {
6249
6250 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6251 profile->mSupportedDevices.types(), profile->mFlags);
6252
6253 mOutputProfiles.add(profile);
6254 return NO_ERROR;
6255 } else {
6256 return BAD_VALUE;
6257 }
6258}
6259
6260status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6261{
6262 cnode *node = root->first_child;
6263
6264 audio_devices_t type = AUDIO_DEVICE_NONE;
6265 while (node) {
6266 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6267 type = parseDeviceNames((char *)node->value);
6268 break;
6269 }
6270 node = node->next;
6271 }
6272 if (type == AUDIO_DEVICE_NONE ||
6273 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6274 ALOGW("loadDevice() bad type %08x", type);
6275 return BAD_VALUE;
6276 }
6277 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6278 deviceDesc->mModule = this;
6279
6280 node = root->first_child;
6281 while (node) {
6282 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6283 deviceDesc->mAddress = String8((char *)node->value);
6284 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6285 if (audio_is_input_device(type)) {
6286 deviceDesc->loadInChannels((char *)node->value);
6287 } else {
6288 deviceDesc->loadOutChannels((char *)node->value);
6289 }
6290 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6291 deviceDesc->loadGains(node);
6292 }
6293 node = node->next;
6294 }
6295
6296 ALOGV("loadDevice() adding device name %s type %08x address %s",
6297 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6298
6299 mDeclaredDevices.add(deviceDesc);
6300
6301 return NO_ERROR;
6302}
6303
Eric Laurent275e8e92014-11-30 15:14:47 -08006304status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6305 audio_devices_t device, String8 address)
6306{
6307 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6308
6309 profile->mSamplingRates.add(config->sample_rate);
6310 profile->mChannelMasks.add(config->channel_mask);
6311 profile->mFormats.add(config->format);
6312
6313 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6314 devDesc->mAddress = address;
6315 profile->mSupportedDevices.add(devDesc);
6316
6317 mOutputProfiles.add(profile);
6318
6319 return NO_ERROR;
6320}
6321
6322status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6323{
6324 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6325 if (mOutputProfiles[i]->mName == name) {
6326 mOutputProfiles.removeAt(i);
6327 break;
6328 }
6329 }
6330
6331 return NO_ERROR;
6332}
6333
6334status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6335 audio_devices_t device, String8 address)
6336{
6337 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6338
6339 profile->mSamplingRates.add(config->sample_rate);
6340 profile->mChannelMasks.add(config->channel_mask);
6341 profile->mFormats.add(config->format);
6342
6343 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6344 devDesc->mAddress = address;
6345 profile->mSupportedDevices.add(devDesc);
6346
6347 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6348
6349 mInputProfiles.add(profile);
6350
6351 return NO_ERROR;
6352}
6353
6354status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6355{
6356 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6357 if (mInputProfiles[i]->mName == name) {
6358 mInputProfiles.removeAt(i);
6359 break;
6360 }
6361 }
6362
6363 return NO_ERROR;
6364}
6365
6366
Eric Laurente0720872014-03-11 09:30:41 -07006367void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006368{
6369 const size_t SIZE = 256;
6370 char buffer[SIZE];
6371 String8 result;
6372
6373 snprintf(buffer, SIZE, " - name: %s\n", mName);
6374 result.append(buffer);
6375 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6376 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006377 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6378 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006379 write(fd, result.string(), result.size());
6380 if (mOutputProfiles.size()) {
6381 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6382 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006383 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006384 write(fd, buffer, strlen(buffer));
6385 mOutputProfiles[i]->dump(fd);
6386 }
6387 }
6388 if (mInputProfiles.size()) {
6389 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6390 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006391 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006392 write(fd, buffer, strlen(buffer));
6393 mInputProfiles[i]->dump(fd);
6394 }
6395 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006396 if (mDeclaredDevices.size()) {
6397 write(fd, " - devices:\n", strlen(" - devices:\n"));
6398 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6399 mDeclaredDevices[i]->dump(fd, 4, i);
6400 }
6401 }
Eric Laurente552edb2014-03-10 17:42:56 -07006402}
6403
Eric Laurent1c333e22014-05-20 10:48:17 -07006404// --- AudioPort class implementation
6405
Eric Laurenta121f902014-06-03 13:32:54 -07006406
6407AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6408 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006409 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006410{
6411 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6412 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6413}
6414
Eric Laurent1c333e22014-05-20 10:48:17 -07006415void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6416{
6417 port->role = mRole;
6418 port->type = mType;
6419 unsigned int i;
6420 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006421 if (mSamplingRates[i] != 0) {
6422 port->sample_rates[i] = mSamplingRates[i];
6423 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006424 }
6425 port->num_sample_rates = i;
6426 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006427 if (mChannelMasks[i] != 0) {
6428 port->channel_masks[i] = mChannelMasks[i];
6429 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006430 }
6431 port->num_channel_masks = i;
6432 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006433 if (mFormats[i] != 0) {
6434 port->formats[i] = mFormats[i];
6435 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006436 }
6437 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006438
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006439 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006440
6441 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6442 port->gains[i] = mGains[i]->mGain;
6443 }
6444 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006445}
6446
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006447void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6448 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6449 const uint32_t rate = port->mSamplingRates.itemAt(k);
6450 if (rate != 0) { // skip "dynamic" rates
6451 bool hasRate = false;
6452 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6453 if (rate == mSamplingRates.itemAt(l)) {
6454 hasRate = true;
6455 break;
6456 }
6457 }
6458 if (!hasRate) { // never import a sampling rate twice
6459 mSamplingRates.add(rate);
6460 }
6461 }
6462 }
6463 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6464 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6465 if (mask != 0) { // skip "dynamic" masks
6466 bool hasMask = false;
6467 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6468 if (mask == mChannelMasks.itemAt(l)) {
6469 hasMask = true;
6470 break;
6471 }
6472 }
6473 if (!hasMask) { // never import a channel mask twice
6474 mChannelMasks.add(mask);
6475 }
6476 }
6477 }
6478 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6479 const audio_format_t format = port->mFormats.itemAt(k);
6480 if (format != 0) { // skip "dynamic" formats
6481 bool hasFormat = false;
6482 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6483 if (format == mFormats.itemAt(l)) {
6484 hasFormat = true;
6485 break;
6486 }
6487 }
6488 if (!hasFormat) { // never import a channel mask twice
6489 mFormats.add(format);
6490 }
6491 }
6492 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006493 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6494 sp<AudioGain> gain = port->mGains.itemAt(k);
6495 if (gain != 0) {
6496 bool hasGain = false;
6497 for (size_t l = 0 ; l < mGains.size() ; l++) {
6498 if (gain == mGains.itemAt(l)) {
6499 hasGain = true;
6500 break;
6501 }
6502 }
6503 if (!hasGain) { // never import a gain twice
6504 mGains.add(gain);
6505 }
6506 }
6507 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006508}
6509
6510void AudioPolicyManager::AudioPort::clearCapabilities() {
6511 mChannelMasks.clear();
6512 mFormats.clear();
6513 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006514 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006515}
Eric Laurent1c333e22014-05-20 10:48:17 -07006516
6517void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6518{
6519 char *str = strtok(name, "|");
6520
6521 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6522 // rates should be read from the output stream after it is opened for the first time
6523 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6524 mSamplingRates.add(0);
6525 return;
6526 }
6527
6528 while (str != NULL) {
6529 uint32_t rate = atoi(str);
6530 if (rate != 0) {
6531 ALOGV("loadSamplingRates() adding rate %d", rate);
6532 mSamplingRates.add(rate);
6533 }
6534 str = strtok(NULL, "|");
6535 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006536}
6537
6538void AudioPolicyManager::AudioPort::loadFormats(char *name)
6539{
6540 char *str = strtok(name, "|");
6541
6542 // by convention, "0' in the first entry in mFormats indicates the supported formats
6543 // should be read from the output stream after it is opened for the first time
6544 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6545 mFormats.add(AUDIO_FORMAT_DEFAULT);
6546 return;
6547 }
6548
6549 while (str != NULL) {
6550 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6551 ARRAY_SIZE(sFormatNameToEnumTable),
6552 str);
6553 if (format != AUDIO_FORMAT_DEFAULT) {
6554 mFormats.add(format);
6555 }
6556 str = strtok(NULL, "|");
6557 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006558}
6559
6560void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6561{
6562 const char *str = strtok(name, "|");
6563
6564 ALOGV("loadInChannels() %s", name);
6565
6566 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6567 mChannelMasks.add(0);
6568 return;
6569 }
6570
6571 while (str != NULL) {
6572 audio_channel_mask_t channelMask =
6573 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6574 ARRAY_SIZE(sInChannelsNameToEnumTable),
6575 str);
6576 if (channelMask != 0) {
6577 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6578 mChannelMasks.add(channelMask);
6579 }
6580 str = strtok(NULL, "|");
6581 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006582}
6583
6584void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6585{
6586 const char *str = strtok(name, "|");
6587
6588 ALOGV("loadOutChannels() %s", name);
6589
6590 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6591 // masks should be read from the output stream after it is opened for the first time
6592 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6593 mChannelMasks.add(0);
6594 return;
6595 }
6596
6597 while (str != NULL) {
6598 audio_channel_mask_t channelMask =
6599 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6600 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6601 str);
6602 if (channelMask != 0) {
6603 mChannelMasks.add(channelMask);
6604 }
6605 str = strtok(NULL, "|");
6606 }
6607 return;
6608}
6609
Eric Laurent1afeecb2014-05-14 08:52:28 -07006610audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6611{
6612 const char *str = strtok(name, "|");
6613
6614 ALOGV("loadGainMode() %s", name);
6615 audio_gain_mode_t mode = 0;
6616 while (str != NULL) {
6617 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6618 ARRAY_SIZE(sGainModeNameToEnumTable),
6619 str);
6620 str = strtok(NULL, "|");
6621 }
6622 return mode;
6623}
6624
Eric Laurenta121f902014-06-03 13:32:54 -07006625void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006626{
6627 cnode *node = root->first_child;
6628
Eric Laurenta121f902014-06-03 13:32:54 -07006629 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006630
6631 while (node) {
6632 if (strcmp(node->name, GAIN_MODE) == 0) {
6633 gain->mGain.mode = loadGainMode((char *)node->value);
6634 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006635 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006636 gain->mGain.channel_mask =
6637 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6638 ARRAY_SIZE(sInChannelsNameToEnumTable),
6639 (char *)node->value);
6640 } else {
6641 gain->mGain.channel_mask =
6642 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6643 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6644 (char *)node->value);
6645 }
6646 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6647 gain->mGain.min_value = atoi((char *)node->value);
6648 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6649 gain->mGain.max_value = atoi((char *)node->value);
6650 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6651 gain->mGain.default_value = atoi((char *)node->value);
6652 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6653 gain->mGain.step_value = atoi((char *)node->value);
6654 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6655 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6656 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6657 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6658 }
6659 node = node->next;
6660 }
6661
6662 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6663 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6664
6665 if (gain->mGain.mode == 0) {
6666 return;
6667 }
6668 mGains.add(gain);
6669}
6670
6671void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6672{
6673 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006674 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006675 while (node) {
6676 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006677 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006678 node = node->next;
6679 }
6680}
6681
Glenn Kastencbd48022014-07-24 13:46:44 -07006682status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006683{
Eric Laurent0daea392014-12-04 19:14:54 -08006684 if (mSamplingRates.isEmpty()) {
6685 return NO_ERROR;
6686 }
6687
Eric Laurenta121f902014-06-03 13:32:54 -07006688 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6689 if (mSamplingRates[i] == samplingRate) {
6690 return NO_ERROR;
6691 }
6692 }
6693 return BAD_VALUE;
6694}
6695
Glenn Kastencbd48022014-07-24 13:46:44 -07006696status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6697 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006698{
Eric Laurent0daea392014-12-04 19:14:54 -08006699 if (mSamplingRates.isEmpty()) {
6700 return NO_ERROR;
6701 }
6702
Glenn Kastencbd48022014-07-24 13:46:44 -07006703 // Search for the closest supported sampling rate that is above (preferred)
6704 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6705 // The sampling rates do not need to be sorted in ascending order.
6706 ssize_t maxBelow = -1;
6707 ssize_t minAbove = -1;
6708 uint32_t candidate;
6709 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6710 candidate = mSamplingRates[i];
6711 if (candidate == samplingRate) {
6712 if (updatedSamplingRate != NULL) {
6713 *updatedSamplingRate = candidate;
6714 }
6715 return NO_ERROR;
6716 }
6717 // candidate < desired
6718 if (candidate < samplingRate) {
6719 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6720 maxBelow = i;
6721 }
6722 // candidate > desired
6723 } else {
6724 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6725 minAbove = i;
6726 }
6727 }
6728 }
6729 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6730 // TODO Move these assumptions out.
6731 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6732 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6733 // due to approximation by an int32_t of the
6734 // phase increments
6735 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6736 if (minAbove >= 0) {
6737 candidate = mSamplingRates[minAbove];
6738 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6739 if (updatedSamplingRate != NULL) {
6740 *updatedSamplingRate = candidate;
6741 }
6742 return NO_ERROR;
6743 }
6744 }
6745 // But if we have to up-sample from a lower sampling rate, that's OK.
6746 if (maxBelow >= 0) {
6747 candidate = mSamplingRates[maxBelow];
6748 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6749 if (updatedSamplingRate != NULL) {
6750 *updatedSamplingRate = candidate;
6751 }
6752 return NO_ERROR;
6753 }
6754 }
6755 // leave updatedSamplingRate unmodified
6756 return BAD_VALUE;
6757}
6758
6759status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6760{
Eric Laurent0daea392014-12-04 19:14:54 -08006761 if (mChannelMasks.isEmpty()) {
6762 return NO_ERROR;
6763 }
6764
Glenn Kastencbd48022014-07-24 13:46:44 -07006765 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006766 if (mChannelMasks[i] == channelMask) {
6767 return NO_ERROR;
6768 }
6769 }
6770 return BAD_VALUE;
6771}
6772
Glenn Kastencbd48022014-07-24 13:46:44 -07006773status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6774 const
6775{
Eric Laurent0daea392014-12-04 19:14:54 -08006776 if (mChannelMasks.isEmpty()) {
6777 return NO_ERROR;
6778 }
6779
Glenn Kastencbd48022014-07-24 13:46:44 -07006780 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6781 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6782 // FIXME Does not handle multi-channel automatic conversions yet
6783 audio_channel_mask_t supported = mChannelMasks[i];
6784 if (supported == channelMask) {
6785 return NO_ERROR;
6786 }
6787 if (isRecordThread) {
6788 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6789 // FIXME Abstract this out to a table.
6790 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6791 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6792 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6793 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6794 return NO_ERROR;
6795 }
6796 }
6797 }
6798 return BAD_VALUE;
6799}
6800
Eric Laurenta121f902014-06-03 13:32:54 -07006801status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6802{
Eric Laurent0daea392014-12-04 19:14:54 -08006803 if (mFormats.isEmpty()) {
6804 return NO_ERROR;
6805 }
6806
Eric Laurenta121f902014-06-03 13:32:54 -07006807 for (size_t i = 0; i < mFormats.size(); i ++) {
6808 if (mFormats[i] == format) {
6809 return NO_ERROR;
6810 }
6811 }
6812 return BAD_VALUE;
6813}
6814
Eric Laurent1e693b52014-07-09 15:03:28 -07006815
6816uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6817{
6818 // special case for uninitialized dynamic profile
6819 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6820 return 0;
6821 }
6822
Eric Laurent828bcff2014-09-07 12:26:06 -07006823 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6824 // channel count / sampling rate combination chosen will be supported by the connected
6825 // sink
6826 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6827 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6828 uint32_t samplingRate = UINT_MAX;
6829 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6830 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6831 samplingRate = mSamplingRates[i];
6832 }
6833 }
6834 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6835 }
6836
Eric Laurent1e693b52014-07-09 15:03:28 -07006837 uint32_t samplingRate = 0;
6838 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6839
6840 // For mixed output and inputs, use max mixer sampling rates. Do not
6841 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006842 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006843 maxRate = UINT_MAX;
6844 }
6845 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6846 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6847 samplingRate = mSamplingRates[i];
6848 }
6849 }
6850 return samplingRate;
6851}
6852
6853audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6854{
6855 // special case for uninitialized dynamic profile
6856 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6857 return AUDIO_CHANNEL_NONE;
6858 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006859 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006860
6861 // For direct outputs, pick minimum channel count: this helps ensuring that the
6862 // channel count / sampling rate combination chosen will be supported by the connected
6863 // sink
6864 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6865 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6866 uint32_t channelCount = UINT_MAX;
6867 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6868 uint32_t cnlCount;
6869 if (mUseInChannelMask) {
6870 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6871 } else {
6872 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6873 }
6874 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6875 channelMask = mChannelMasks[i];
6876 channelCount = cnlCount;
6877 }
6878 }
6879 return channelMask;
6880 }
6881
Eric Laurent1e693b52014-07-09 15:03:28 -07006882 uint32_t channelCount = 0;
6883 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6884
6885 // For mixed output and inputs, use max mixer channel count. Do not
6886 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006887 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006888 maxCount = UINT_MAX;
6889 }
6890 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6891 uint32_t cnlCount;
6892 if (mUseInChannelMask) {
6893 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6894 } else {
6895 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6896 }
6897 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6898 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006899 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006900 }
6901 }
6902 return channelMask;
6903}
6904
Andy Hung9a605382014-07-28 16:16:31 -07006905/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006906const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6907 AUDIO_FORMAT_DEFAULT,
6908 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006909 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006910 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006911 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006912 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006913};
6914
6915int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6916 audio_format_t format2)
6917{
6918 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6919 // compressed format and better than any PCM format. This is by design of pickFormat()
6920 if (!audio_is_linear_pcm(format1)) {
6921 if (!audio_is_linear_pcm(format2)) {
6922 return 0;
6923 }
6924 return 1;
6925 }
6926 if (!audio_is_linear_pcm(format2)) {
6927 return -1;
6928 }
6929
6930 int index1 = -1, index2 = -1;
6931 for (size_t i = 0;
6932 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6933 i ++) {
6934 if (sPcmFormatCompareTable[i] == format1) {
6935 index1 = i;
6936 }
6937 if (sPcmFormatCompareTable[i] == format2) {
6938 index2 = i;
6939 }
6940 }
6941 // format1 not found => index1 < 0 => format2 > format1
6942 // format2 not found => index2 < 0 => format2 < format1
6943 return index1 - index2;
6944}
6945
6946audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6947{
6948 // special case for uninitialized dynamic profile
6949 if (mFormats.size() == 1 && mFormats[0] == 0) {
6950 return AUDIO_FORMAT_DEFAULT;
6951 }
6952
6953 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006954 audio_format_t bestFormat =
6955 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6956 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006957 // For mixed output and inputs, use best mixer output format. Do not
6958 // limit format otherwise
6959 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6960 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006961 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006962 bestFormat = AUDIO_FORMAT_INVALID;
6963 }
6964
6965 for (size_t i = 0; i < mFormats.size(); i ++) {
6966 if ((compareFormats(mFormats[i], format) > 0) &&
6967 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6968 format = mFormats[i];
6969 }
6970 }
6971 return format;
6972}
6973
Eric Laurenta121f902014-06-03 13:32:54 -07006974status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6975 int index) const
6976{
6977 if (index < 0 || (size_t)index >= mGains.size()) {
6978 return BAD_VALUE;
6979 }
6980 return mGains[index]->checkConfig(gainConfig);
6981}
6982
Eric Laurent1afeecb2014-05-14 08:52:28 -07006983void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6984{
6985 const size_t SIZE = 256;
6986 char buffer[SIZE];
6987 String8 result;
6988
6989 if (mName.size() != 0) {
6990 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6991 result.append(buffer);
6992 }
6993
6994 if (mSamplingRates.size() != 0) {
6995 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6996 result.append(buffer);
6997 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006998 if (i == 0 && mSamplingRates[i] == 0) {
6999 snprintf(buffer, SIZE, "Dynamic");
7000 } else {
7001 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7002 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007003 result.append(buffer);
7004 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7005 }
7006 result.append("\n");
7007 }
7008
7009 if (mChannelMasks.size() != 0) {
7010 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7011 result.append(buffer);
7012 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007013 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7014
7015 if (i == 0 && mChannelMasks[i] == 0) {
7016 snprintf(buffer, SIZE, "Dynamic");
7017 } else {
7018 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7019 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007020 result.append(buffer);
7021 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7022 }
7023 result.append("\n");
7024 }
7025
7026 if (mFormats.size() != 0) {
7027 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7028 result.append(buffer);
7029 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007030 const char *formatStr = enumToString(sFormatNameToEnumTable,
7031 ARRAY_SIZE(sFormatNameToEnumTable),
7032 mFormats[i]);
7033 if (i == 0 && strcmp(formatStr, "") == 0) {
7034 snprintf(buffer, SIZE, "Dynamic");
7035 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07007036 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07007037 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007038 result.append(buffer);
7039 result.append(i == (mFormats.size() - 1) ? "" : ", ");
7040 }
7041 result.append("\n");
7042 }
7043 write(fd, result.string(), result.size());
7044 if (mGains.size() != 0) {
7045 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7046 write(fd, buffer, strlen(buffer) + 1);
7047 result.append(buffer);
7048 for (size_t i = 0; i < mGains.size(); i++) {
7049 mGains[i]->dump(fd, spaces + 2, i);
7050 }
7051 }
7052}
7053
7054// --- AudioGain class implementation
7055
Eric Laurenta121f902014-06-03 13:32:54 -07007056AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07007057{
Eric Laurenta121f902014-06-03 13:32:54 -07007058 mIndex = index;
7059 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007060 memset(&mGain, 0, sizeof(struct audio_gain));
7061}
7062
Eric Laurenta121f902014-06-03 13:32:54 -07007063void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7064{
7065 config->index = mIndex;
7066 config->mode = mGain.mode;
7067 config->channel_mask = mGain.channel_mask;
7068 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7069 config->values[0] = mGain.default_value;
7070 } else {
7071 uint32_t numValues;
7072 if (mUseInChannelMask) {
7073 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7074 } else {
7075 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7076 }
7077 for (size_t i = 0; i < numValues; i++) {
7078 config->values[i] = mGain.default_value;
7079 }
7080 }
7081 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7082 config->ramp_duration_ms = mGain.min_ramp_ms;
7083 }
7084}
7085
7086status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7087{
7088 if ((config->mode & ~mGain.mode) != 0) {
7089 return BAD_VALUE;
7090 }
7091 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7092 if ((config->values[0] < mGain.min_value) ||
7093 (config->values[0] > mGain.max_value)) {
7094 return BAD_VALUE;
7095 }
7096 } else {
7097 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7098 return BAD_VALUE;
7099 }
7100 uint32_t numValues;
7101 if (mUseInChannelMask) {
7102 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7103 } else {
7104 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7105 }
7106 for (size_t i = 0; i < numValues; i++) {
7107 if ((config->values[i] < mGain.min_value) ||
7108 (config->values[i] > mGain.max_value)) {
7109 return BAD_VALUE;
7110 }
7111 }
7112 }
7113 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7114 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7115 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7116 return BAD_VALUE;
7117 }
7118 }
7119 return NO_ERROR;
7120}
7121
Eric Laurent1afeecb2014-05-14 08:52:28 -07007122void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7123{
7124 const size_t SIZE = 256;
7125 char buffer[SIZE];
7126 String8 result;
7127
7128 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7129 result.append(buffer);
7130 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7131 result.append(buffer);
7132 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7133 result.append(buffer);
7134 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7135 result.append(buffer);
7136 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7137 result.append(buffer);
7138 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7139 result.append(buffer);
7140 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7141 result.append(buffer);
7142 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7143 result.append(buffer);
7144 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7145 result.append(buffer);
7146
7147 write(fd, result.string(), result.size());
7148}
7149
Eric Laurent1f2f2232014-06-02 12:01:23 -07007150// --- AudioPortConfig class implementation
7151
7152AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7153{
7154 mSamplingRate = 0;
7155 mChannelMask = AUDIO_CHANNEL_NONE;
7156 mFormat = AUDIO_FORMAT_INVALID;
7157 mGain.index = -1;
7158}
7159
Eric Laurenta121f902014-06-03 13:32:54 -07007160status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7161 const struct audio_port_config *config,
7162 struct audio_port_config *backupConfig)
7163{
7164 struct audio_port_config localBackupConfig;
7165 status_t status = NO_ERROR;
7166
7167 localBackupConfig.config_mask = config->config_mask;
7168 toAudioPortConfig(&localBackupConfig);
7169
Marco Nelissen961ec212014-08-25 15:58:39 -07007170 sp<AudioPort> audioport = getAudioPort();
7171 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007172 status = NO_INIT;
7173 goto exit;
7174 }
7175 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007176 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007177 if (status != NO_ERROR) {
7178 goto exit;
7179 }
7180 mSamplingRate = config->sample_rate;
7181 }
7182 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007183 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007184 if (status != NO_ERROR) {
7185 goto exit;
7186 }
7187 mChannelMask = config->channel_mask;
7188 }
7189 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007190 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007191 if (status != NO_ERROR) {
7192 goto exit;
7193 }
7194 mFormat = config->format;
7195 }
7196 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007197 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007198 if (status != NO_ERROR) {
7199 goto exit;
7200 }
7201 mGain = config->gain;
7202 }
7203
7204exit:
7205 if (status != NO_ERROR) {
7206 applyAudioPortConfig(&localBackupConfig);
7207 }
7208 if (backupConfig != NULL) {
7209 *backupConfig = localBackupConfig;
7210 }
7211 return status;
7212}
7213
Eric Laurent1f2f2232014-06-02 12:01:23 -07007214void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7215 struct audio_port_config *dstConfig,
7216 const struct audio_port_config *srcConfig) const
7217{
7218 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7219 dstConfig->sample_rate = mSamplingRate;
7220 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7221 dstConfig->sample_rate = srcConfig->sample_rate;
7222 }
7223 } else {
7224 dstConfig->sample_rate = 0;
7225 }
7226 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7227 dstConfig->channel_mask = mChannelMask;
7228 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7229 dstConfig->channel_mask = srcConfig->channel_mask;
7230 }
7231 } else {
7232 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7233 }
7234 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7235 dstConfig->format = mFormat;
7236 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7237 dstConfig->format = srcConfig->format;
7238 }
7239 } else {
7240 dstConfig->format = AUDIO_FORMAT_INVALID;
7241 }
7242 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7243 dstConfig->gain = mGain;
7244 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7245 dstConfig->gain = srcConfig->gain;
7246 }
7247 } else {
7248 dstConfig->gain.index = -1;
7249 }
7250 if (dstConfig->gain.index != -1) {
7251 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7252 } else {
7253 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7254 }
7255}
7256
Eric Laurent1c333e22014-05-20 10:48:17 -07007257// --- IOProfile class implementation
7258
Eric Laurent1afeecb2014-05-14 08:52:28 -07007259AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007260 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007261 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007262{
7263}
7264
Eric Laurente0720872014-03-11 09:30:41 -07007265AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007266{
7267}
7268
7269// checks if the IO profile is compatible with specified parameters.
7270// Sampling rate, format and channel mask must be specified in order to
7271// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007272bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007273 String8 address,
7274 uint32_t samplingRate,
7275 uint32_t *updatedSamplingRate,
7276 audio_format_t format,
7277 audio_channel_mask_t channelMask,
7278 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007279{
Glenn Kastencbd48022014-07-24 13:46:44 -07007280 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7281 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7282 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007283
Eric Laurent275e8e92014-11-30 15:14:47 -08007284 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007285 return false;
7286 }
7287
7288 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007289 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007290 }
7291 uint32_t myUpdatedSamplingRate = samplingRate;
7292 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007293 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007294 }
7295 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7296 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007297 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007298 }
7299
7300 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7301 return false;
7302 }
7303
7304 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7305 checkExactChannelMask(channelMask) != NO_ERROR)) {
7306 return false;
7307 }
7308 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7309 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7310 return false;
7311 }
7312
7313 if (isPlaybackThread && (mFlags & flags) != flags) {
7314 return false;
7315 }
7316 // The only input flag that is allowed to be different is the fast flag.
7317 // An existing fast stream is compatible with a normal track request.
7318 // An existing normal stream is compatible with a fast track request,
7319 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007320 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007321 ~AUDIO_INPUT_FLAG_FAST)) {
7322 return false;
7323 }
7324
7325 if (updatedSamplingRate != NULL) {
7326 *updatedSamplingRate = myUpdatedSamplingRate;
7327 }
7328 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007329}
7330
Eric Laurente0720872014-03-11 09:30:41 -07007331void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007332{
7333 const size_t SIZE = 256;
7334 char buffer[SIZE];
7335 String8 result;
7336
Eric Laurent1afeecb2014-05-14 08:52:28 -07007337 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007338
Eric Laurente552edb2014-03-10 17:42:56 -07007339 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7340 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007341 snprintf(buffer, SIZE, " - devices:\n");
7342 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007343 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007344 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7345 mSupportedDevices[i]->dump(fd, 6, i);
7346 }
Eric Laurente552edb2014-03-10 17:42:56 -07007347}
7348
Eric Laurentd4692962014-05-05 18:13:44 -07007349void AudioPolicyManager::IOProfile::log()
7350{
7351 const size_t SIZE = 256;
7352 char buffer[SIZE];
7353 String8 result;
7354
7355 ALOGV(" - sampling rates: ");
7356 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7357 ALOGV(" %d", mSamplingRates[i]);
7358 }
7359
7360 ALOGV(" - channel masks: ");
7361 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7362 ALOGV(" 0x%04x", mChannelMasks[i]);
7363 }
7364
7365 ALOGV(" - formats: ");
7366 for (size_t i = 0; i < mFormats.size(); i++) {
7367 ALOGV(" 0x%08x", mFormats[i]);
7368 }
7369
7370 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7371 ALOGV(" - flags: 0x%04x\n", mFlags);
7372}
7373
7374
Eric Laurent3a4311c2014-03-17 12:00:47 -07007375// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007376
Eric Laurent1f2f2232014-06-02 12:01:23 -07007377
7378AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7379 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7380 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7381 AUDIO_PORT_ROLE_SOURCE,
7382 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007383 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007384{
Eric Laurenta121f902014-06-03 13:32:54 -07007385 if (mGains.size() > 0) {
7386 mGains[0]->getDefaultConfig(&mGain);
7387 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07007388}
7389
Eric Laurent3a4311c2014-03-17 12:00:47 -07007390bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007391{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007392 // Devices are considered equal if they:
7393 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7394 // - have the same address or one device does not specify the address
7395 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007396 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007397 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007398 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007399 mChannelMask == other->mChannelMask);
7400}
7401
7402void AudioPolicyManager::DeviceVector::refreshTypes()
7403{
Eric Laurent1c333e22014-05-20 10:48:17 -07007404 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007405 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007406 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007407 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007408 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007409}
7410
7411ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7412{
7413 for(size_t i = 0; i < size(); i++) {
7414 if (item->equals(itemAt(i))) {
7415 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007416 }
7417 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007418 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007419}
7420
Eric Laurent3a4311c2014-03-17 12:00:47 -07007421ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007422{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007423 ssize_t ret = indexOf(item);
7424
7425 if (ret < 0) {
7426 ret = SortedVector::add(item);
7427 if (ret >= 0) {
7428 refreshTypes();
7429 }
7430 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007431 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007432 ret = -1;
7433 }
7434 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007435}
7436
Eric Laurent3a4311c2014-03-17 12:00:47 -07007437ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7438{
7439 size_t i;
7440 ssize_t ret = indexOf(item);
7441
7442 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007443 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007444 } else {
7445 ret = SortedVector::removeAt(ret);
7446 if (ret >= 0) {
7447 refreshTypes();
7448 }
7449 }
7450 return ret;
7451}
7452
7453void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7454{
7455 DeviceVector deviceList;
7456
7457 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7458 types &= ~role_bit;
7459
7460 while (types) {
7461 uint32_t i = 31 - __builtin_clz(types);
7462 uint32_t type = 1 << i;
7463 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007464 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007465 }
7466}
7467
Eric Laurent1afeecb2014-05-14 08:52:28 -07007468void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7469 const DeviceVector& declaredDevices)
7470{
7471 char *devName = strtok(name, "|");
7472 while (devName != NULL) {
7473 if (strlen(devName) != 0) {
7474 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7475 ARRAY_SIZE(sDeviceNameToEnumTable),
7476 devName);
7477 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007478 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007479 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7480 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007481 dev->mAddress = String8("0");
7482 }
7483 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007484 } else {
7485 sp<DeviceDescriptor> deviceDesc =
7486 declaredDevices.getDeviceFromName(String8(devName));
7487 if (deviceDesc != 0) {
7488 add(deviceDesc);
7489 }
7490 }
7491 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007492 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007493 }
7494}
7495
Eric Laurent1c333e22014-05-20 10:48:17 -07007496sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7497 audio_devices_t type, String8 address) const
7498{
7499 sp<DeviceDescriptor> device;
7500 for (size_t i = 0; i < size(); i++) {
7501 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007502 if (address == "" || itemAt(i)->mAddress == address) {
7503 device = itemAt(i);
7504 if (itemAt(i)->mAddress == address) {
7505 break;
7506 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007507 }
7508 }
7509 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007510 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007511 type, address.string(), device.get());
7512 return device;
7513}
7514
Eric Laurent6a94d692014-05-20 11:18:06 -07007515sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7516 audio_port_handle_t id) const
7517{
7518 sp<DeviceDescriptor> device;
7519 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007520 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007521 if (itemAt(i)->mId == id) {
7522 device = itemAt(i);
7523 break;
7524 }
7525 }
7526 return device;
7527}
7528
Eric Laurent1c333e22014-05-20 10:48:17 -07007529AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7530 audio_devices_t type) const
7531{
7532 DeviceVector devices;
7533 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7534 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7535 devices.add(itemAt(i));
7536 type &= ~itemAt(i)->mDeviceType;
7537 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7538 itemAt(i)->mDeviceType, itemAt(i).get());
7539 }
7540 }
7541 return devices;
7542}
7543
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007544AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7545 audio_devices_t type, String8 address) const
7546{
7547 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007548 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007549 if (itemAt(i)->mDeviceType == type) {
7550 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007551 devices.add(itemAt(i));
7552 }
7553 }
7554 }
7555 return devices;
7556}
7557
Eric Laurent1afeecb2014-05-14 08:52:28 -07007558sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7559 const String8& name) const
7560{
7561 sp<DeviceDescriptor> device;
7562 for (size_t i = 0; i < size(); i++) {
7563 if (itemAt(i)->mName == name) {
7564 device = itemAt(i);
7565 break;
7566 }
7567 }
7568 return device;
7569}
7570
Eric Laurent6a94d692014-05-20 11:18:06 -07007571void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7572 struct audio_port_config *dstConfig,
7573 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007574{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007575 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7576 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007577 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007578 }
7579
7580 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7581
Eric Laurent6a94d692014-05-20 11:18:06 -07007582 dstConfig->id = mId;
7583 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007584 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007585 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007586 dstConfig->ext.device.type = mDeviceType;
7587 dstConfig->ext.device.hw_module = mModule->mHandle;
7588 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007589}
7590
7591void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7592{
Eric Laurent83b88082014-06-20 18:31:16 -07007593 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007594 AudioPort::toAudioPort(port);
7595 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007596 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007597 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007598 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007599 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7600}
7601
Eric Laurent1afeecb2014-05-14 08:52:28 -07007602status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007603{
7604 const size_t SIZE = 256;
7605 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007606 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007607
Eric Laurent1afeecb2014-05-14 08:52:28 -07007608 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7609 result.append(buffer);
7610 if (mId != 0) {
7611 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7612 result.append(buffer);
7613 }
7614 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7615 enumToString(sDeviceNameToEnumTable,
7616 ARRAY_SIZE(sDeviceNameToEnumTable),
7617 mDeviceType));
7618 result.append(buffer);
7619 if (mAddress.size() != 0) {
7620 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7621 result.append(buffer);
7622 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007623 write(fd, result.string(), result.size());
7624 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007625
7626 return NO_ERROR;
7627}
7628
Eric Laurent4d416952014-08-10 14:07:09 -07007629status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7630{
7631 const size_t SIZE = 256;
7632 char buffer[SIZE];
7633 String8 result;
7634
7635
7636 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7637 result.append(buffer);
7638 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7639 result.append(buffer);
7640 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7641 result.append(buffer);
7642 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7643 result.append(buffer);
7644 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7645 result.append(buffer);
7646 for (size_t i = 0; i < mPatch.num_sources; i++) {
7647 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7648 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7649 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7650 ARRAY_SIZE(sDeviceNameToEnumTable),
7651 mPatch.sources[i].ext.device.type));
7652 } else {
7653 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7654 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7655 }
7656 result.append(buffer);
7657 }
7658 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7659 result.append(buffer);
7660 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7661 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7662 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7663 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7664 ARRAY_SIZE(sDeviceNameToEnumTable),
7665 mPatch.sinks[i].ext.device.type));
7666 } else {
7667 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7668 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7669 }
7670 result.append(buffer);
7671 }
7672
7673 write(fd, result.string(), result.size());
7674 return NO_ERROR;
7675}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007676
7677// --- audio_policy.conf file parsing
7678
Eric Laurent5dbe4712014-09-19 19:04:57 -07007679uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007680{
7681 uint32_t flag = 0;
7682
7683 // it is OK to cast name to non const here as we are not going to use it after
7684 // strtok() modifies it
7685 char *flagName = strtok(name, "|");
7686 while (flagName != NULL) {
7687 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007688 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7689 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007690 flagName);
7691 }
7692 flagName = strtok(NULL, "|");
7693 }
7694 //force direct flag if offload flag is set: offloading implies a direct output stream
7695 // and all common behaviors are driven by checking only the direct flag
7696 // this should normally be set appropriately in the policy configuration file
7697 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7698 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7699 }
7700
Eric Laurent5dbe4712014-09-19 19:04:57 -07007701 return flag;
7702}
7703
7704uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7705{
7706 uint32_t flag = 0;
7707
7708 // it is OK to cast name to non const here as we are not going to use it after
7709 // strtok() modifies it
7710 char *flagName = strtok(name, "|");
7711 while (flagName != NULL) {
7712 if (strlen(flagName) != 0) {
7713 flag |= stringToEnum(sInputFlagNameToEnumTable,
7714 ARRAY_SIZE(sInputFlagNameToEnumTable),
7715 flagName);
7716 }
7717 flagName = strtok(NULL, "|");
7718 }
7719 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007720}
7721
Eric Laurente0720872014-03-11 09:30:41 -07007722audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007723{
7724 uint32_t device = 0;
7725
7726 char *devName = strtok(name, "|");
7727 while (devName != NULL) {
7728 if (strlen(devName) != 0) {
7729 device |= stringToEnum(sDeviceNameToEnumTable,
7730 ARRAY_SIZE(sDeviceNameToEnumTable),
7731 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007732 }
Eric Laurente552edb2014-03-10 17:42:56 -07007733 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007734 }
Eric Laurente552edb2014-03-10 17:42:56 -07007735 return device;
7736}
7737
Eric Laurente0720872014-03-11 09:30:41 -07007738void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007739{
Eric Laurente552edb2014-03-10 17:42:56 -07007740 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007741 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007742 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007743
Eric Laurent1afeecb2014-05-14 08:52:28 -07007744 node = config_find(root, DEVICES_TAG);
7745 if (node != NULL) {
7746 node = node->first_child;
7747 while (node) {
7748 ALOGV("loadHwModule() loading device %s", node->name);
7749 status_t tmpStatus = module->loadDevice(node);
7750 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7751 status = tmpStatus;
7752 }
7753 node = node->next;
7754 }
7755 }
7756 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007757 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007758 node = node->first_child;
7759 while (node) {
7760 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007761 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007762 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7763 status = tmpStatus;
7764 }
7765 node = node->next;
7766 }
7767 }
7768 node = config_find(root, INPUTS_TAG);
7769 if (node != NULL) {
7770 node = node->first_child;
7771 while (node) {
7772 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007773 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007774 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7775 status = tmpStatus;
7776 }
7777 node = node->next;
7778 }
7779 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007780 loadGlobalConfig(root, module);
7781
Eric Laurente552edb2014-03-10 17:42:56 -07007782 if (status == NO_ERROR) {
7783 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007784 }
7785}
7786
Eric Laurente0720872014-03-11 09:30:41 -07007787void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007788{
7789 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7790 if (node == NULL) {
7791 return;
7792 }
7793
7794 node = node->first_child;
7795 while (node) {
7796 ALOGV("loadHwModules() loading module %s", node->name);
7797 loadHwModule(node);
7798 node = node->next;
7799 }
7800}
7801
Eric Laurent1f2f2232014-06-02 12:01:23 -07007802void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007803{
7804 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007805
Eric Laurente552edb2014-03-10 17:42:56 -07007806 if (node == NULL) {
7807 return;
7808 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007809 DeviceVector declaredDevices;
7810 if (module != NULL) {
7811 declaredDevices = module->mDeclaredDevices;
7812 }
7813
Eric Laurente552edb2014-03-10 17:42:56 -07007814 node = node->first_child;
7815 while (node) {
7816 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007817 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7818 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007819 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7820 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007821 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007822 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007823 ARRAY_SIZE(sDeviceNameToEnumTable),
7824 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007825 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007826 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007827 } else {
7828 ALOGW("loadGlobalConfig() default device not specified");
7829 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007830 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007831 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007832 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7833 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007834 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007835 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7836 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7837 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007838 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7839 uint32_t major, minor;
7840 sscanf((char *)node->value, "%u.%u", &major, &minor);
7841 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7842 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7843 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007844 }
7845 node = node->next;
7846 }
7847}
7848
Eric Laurente0720872014-03-11 09:30:41 -07007849status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007850{
7851 cnode *root;
7852 char *data;
7853
7854 data = (char *)load_file(path, NULL);
7855 if (data == NULL) {
7856 return -ENODEV;
7857 }
7858 root = config_node("", "");
7859 config_load(root, data);
7860
Eric Laurente552edb2014-03-10 17:42:56 -07007861 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007862 // legacy audio_policy.conf files have one global_configuration section
7863 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007864 config_free(root);
7865 free(root);
7866 free(data);
7867
7868 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7869
7870 return NO_ERROR;
7871}
7872
Eric Laurente0720872014-03-11 09:30:41 -07007873void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007874{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007875 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007876 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007877 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7878 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007879 mAvailableOutputDevices.add(mDefaultOutputDevice);
7880 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007881
7882 module = new HwModule("primary");
7883
Eric Laurent1afeecb2014-05-14 08:52:28 -07007884 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007885 profile->mSamplingRates.add(44100);
7886 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7887 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007888 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007889 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7890 module->mOutputProfiles.add(profile);
7891
Eric Laurent1afeecb2014-05-14 08:52:28 -07007892 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007893 profile->mSamplingRates.add(8000);
7894 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7895 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007896 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007897 module->mInputProfiles.add(profile);
7898
7899 mHwModules.add(module);
7900}
7901
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007902audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7903{
7904 // flags to stream type mapping
7905 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7906 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7907 }
7908 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7909 return AUDIO_STREAM_BLUETOOTH_SCO;
7910 }
7911
7912 // usage to stream type mapping
7913 switch (attr->usage) {
7914 case AUDIO_USAGE_MEDIA:
7915 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007916 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7917 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007918 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007919 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7920 return AUDIO_STREAM_ALARM;
7921 }
7922 if (isStreamActive(AUDIO_STREAM_RING)) {
7923 return AUDIO_STREAM_RING;
7924 }
7925 if (isInCall()) {
7926 return AUDIO_STREAM_VOICE_CALL;
7927 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08007928 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007929 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7930 return AUDIO_STREAM_SYSTEM;
7931 case AUDIO_USAGE_VOICE_COMMUNICATION:
7932 return AUDIO_STREAM_VOICE_CALL;
7933
7934 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7935 return AUDIO_STREAM_DTMF;
7936
7937 case AUDIO_USAGE_ALARM:
7938 return AUDIO_STREAM_ALARM;
7939 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7940 return AUDIO_STREAM_RING;
7941
7942 case AUDIO_USAGE_NOTIFICATION:
7943 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7944 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7945 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7946 case AUDIO_USAGE_NOTIFICATION_EVENT:
7947 return AUDIO_STREAM_NOTIFICATION;
7948
7949 case AUDIO_USAGE_UNKNOWN:
7950 default:
7951 return AUDIO_STREAM_MUSIC;
7952 }
7953}
Eric Laurente83b55d2014-11-14 10:06:21 -08007954
7955bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
7956 // has flags that map to a strategy?
7957 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7958 return true;
7959 }
7960
7961 // has known usage?
7962 switch (paa->usage) {
7963 case AUDIO_USAGE_UNKNOWN:
7964 case AUDIO_USAGE_MEDIA:
7965 case AUDIO_USAGE_VOICE_COMMUNICATION:
7966 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7967 case AUDIO_USAGE_ALARM:
7968 case AUDIO_USAGE_NOTIFICATION:
7969 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7970 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7971 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7972 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7973 case AUDIO_USAGE_NOTIFICATION_EVENT:
7974 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7975 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7976 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7977 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007978 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08007979 break;
7980 default:
7981 return false;
7982 }
7983 return true;
7984}
7985
Eric Laurente552edb2014-03-10 17:42:56 -07007986}; // namespace android