blob: 5c87c5ec1b63ddb93c49eedfb1cdd677450c1220 [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()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// 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 Laurentdf3dc7e2014-07-27 18:39:40 -070046#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070047#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070048#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070053// Definitions for audio_policy.conf file parsing
54// ----------------------------------------------------------------------------
55
56struct StringToEnum {
57 const char *name;
58 uint32_t value;
59};
60
61#define STRING_TO_ENUM(string) { #string, string }
62#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
63
64const StringToEnum sDeviceNameToEnumTable[] = {
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070078 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070079 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070085 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070090 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050091 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
93 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070097 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700105 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700106 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
107 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
108 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700110 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900111 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112};
113
114const StringToEnum sFlagNameToEnumTable[] = {
115 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
121};
122
123const StringToEnum sFormatNameToEnumTable[] = {
124 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
125 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
127 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
128 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
129 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
130 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
131 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530132 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700142 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700143 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
144 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
145 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
146 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
147 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700148};
149
150const StringToEnum sOutChannelsNameToEnumTable[] = {
151 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
152 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700153 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700154 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
155 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
156};
157
158const StringToEnum sInChannelsNameToEnumTable[] = {
159 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
161 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
162};
163
Eric Laurent1afeecb2014-05-14 08:52:28 -0700164const StringToEnum sGainModeNameToEnumTable[] = {
165 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
166 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
167 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
168};
169
Eric Laurent3a4311c2014-03-17 12:00:47 -0700170
171uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
172 size_t size,
173 const char *name)
174{
175 for (size_t i = 0; i < size; i++) {
176 if (strcmp(table[i].name, name) == 0) {
177 ALOGV("stringToEnum() found %s", table[i].name);
178 return table[i].value;
179 }
180 }
181 return 0;
182}
183
184const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
185 size_t size,
186 uint32_t value)
187{
188 for (size_t i = 0; i < size; i++) {
189 if (table[i].value == value) {
190 return table[i].name;
191 }
192 }
193 return "";
194}
195
196bool AudioPolicyManager::stringToBool(const char *value)
197{
198 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
199}
200
201
202// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700203// AudioPolicyInterface implementation
204// ----------------------------------------------------------------------------
205
206
Eric Laurente0720872014-03-11 09:30:41 -0700207status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700208 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700209 const char *device_address)
210{
Eric Laurent22226012014-08-01 17:00:54 -0700211 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700212
Eric Laurent22226012014-08-01 17:00:54 -0700213 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
214 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700215
216 // connect/disconnect only 1 device at a time
217 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
218
Eric Laurente552edb2014-03-10 17:42:56 -0700219 // handle output devices
220 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700221 SortedVector <audio_io_handle_t> outputs;
222
Eric Laurent1afeecb2014-05-14 08:52:28 -0700223 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
224 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700225 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
226
Eric Laurente552edb2014-03-10 17:42:56 -0700227 // save a copy of the opened output descriptors before any output is opened or closed
228 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
229 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700230 switch (state)
231 {
232 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700233 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700234 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700235 ALOGW("setDeviceConnectionState() device already connected: %x", device);
236 return INVALID_OPERATION;
237 }
238 ALOGV("setDeviceConnectionState() connecting device %x", device);
239
Eric Laurente552edb2014-03-10 17:42:56 -0700240 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700241 index = mAvailableOutputDevices.add(devDesc);
242 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700243 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700244 if (module == 0) {
245 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
246 device);
247 mAvailableOutputDevices.remove(devDesc);
248 return INVALID_OPERATION;
249 }
250 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700251 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 } else {
253 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700254 }
255
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700256 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
257 mAvailableOutputDevices.remove(devDesc);
258 return INVALID_OPERATION;
259 }
260 // outputs should never be empty here
261 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
262 "checkOutputsForDevice() returned no outputs but status OK");
263 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
264 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700265 break;
266 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700267 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700268 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700269 ALOGW("setDeviceConnectionState() device not connected: %x", device);
270 return INVALID_OPERATION;
271 }
272
273 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
274 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700275 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700276
Eric Laurent3a4311c2014-03-17 12:00:47 -0700277 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700278 } break;
279
280 default:
281 ALOGE("setDeviceConnectionState() invalid state: %x", state);
282 return BAD_VALUE;
283 }
284
Eric Laurent3a4311c2014-03-17 12:00:47 -0700285 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
286 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700287 checkA2dpSuspend();
288 checkOutputForAllStrategies();
289 // outputs must be closed after checkOutputForAllStrategies() is executed
290 if (!outputs.isEmpty()) {
291 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700292 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700293 // close unused outputs after device disconnection or direct outputs that have been
294 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700295 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700296 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
297 (desc->mDirectOpenCount == 0))) {
298 closeOutput(outputs[i]);
299 }
300 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700301 // check again after closing A2DP output to reset mA2dpSuspended if needed
302 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700303 }
304
305 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700306 if (mPhoneState == AUDIO_MODE_IN_CALL) {
307 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
308 updateCallRouting(newDevice);
309 }
Eric Laurente552edb2014-03-10 17:42:56 -0700310 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700311 audio_io_handle_t output = mOutputs.keyAt(i);
312 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
313 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
314 true /*fromCache*/);
315 // do not force device change on duplicated output because if device is 0, it will
316 // also force a device 0 for the two outputs it is duplicated to which may override
317 // a valid device selection on those outputs.
318 bool force = !mOutputs.valueAt(i)->isDuplicated()
319 && (!deviceDistinguishesOnAddress(device)
320 // always force when disconnecting (a non-duplicated device)
321 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
322 setOutputDevice(output, newDevice, force, 0);
323 }
Eric Laurente552edb2014-03-10 17:42:56 -0700324 }
325
Eric Laurent72aa32f2014-05-30 18:51:48 -0700326 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700327 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700328 } // end if is output device
329
Eric Laurente552edb2014-03-10 17:42:56 -0700330 // handle input devices
331 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700332 SortedVector <audio_io_handle_t> inputs;
333
Eric Laurent1afeecb2014-05-14 08:52:28 -0700334 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
335 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700336 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700337 switch (state)
338 {
339 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700340 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700341 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700342 ALOGW("setDeviceConnectionState() device already connected: %d", device);
343 return INVALID_OPERATION;
344 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700345 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700346 if (module == NULL) {
347 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
348 device);
349 return INVALID_OPERATION;
350 }
Eric Laurentd4692962014-05-05 18:13:44 -0700351 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
352 return INVALID_OPERATION;
353 }
354
Eric Laurent3a4311c2014-03-17 12:00:47 -0700355 index = mAvailableInputDevices.add(devDesc);
356 if (index >= 0) {
357 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700358 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 } else {
360 return NO_MEMORY;
361 }
Eric Laurentd4692962014-05-05 18:13:44 -0700362 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700363
364 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700365 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700366 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700367 ALOGW("setDeviceConnectionState() device not connected: %d", device);
368 return INVALID_OPERATION;
369 }
Eric Laurentd4692962014-05-05 18:13:44 -0700370 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700371 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700372 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700373
374 default:
375 ALOGE("setDeviceConnectionState() invalid state: %x", state);
376 return BAD_VALUE;
377 }
378
Eric Laurentd4692962014-05-05 18:13:44 -0700379 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700380
Eric Laurentc2730ba2014-07-20 15:47:07 -0700381 if (mPhoneState == AUDIO_MODE_IN_CALL) {
382 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
383 updateCallRouting(newDevice);
384 }
385
Eric Laurentb52c1522014-05-20 11:27:36 -0700386 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700387 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700388 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700389
390 ALOGW("setDeviceConnectionState() invalid device: %x", device);
391 return BAD_VALUE;
392}
393
Eric Laurente0720872014-03-11 09:30:41 -0700394audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700395 const char *device_address)
396{
Eric Laurent3b73df72014-03-11 09:06:29 -0700397 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700398 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700399 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700400 ssize_t index;
401 DeviceVector *deviceVector;
402
Eric Laurente552edb2014-03-10 17:42:56 -0700403 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700404 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700405 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700406 deviceVector = &mAvailableInputDevices;
407 } else {
408 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
409 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700410 }
411
Eric Laurent3a4311c2014-03-17 12:00:47 -0700412 index = deviceVector->indexOf(devDesc);
413 if (index >= 0) {
414 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
415 } else {
416 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
417 }
Eric Laurente552edb2014-03-10 17:42:56 -0700418}
419
Eric Laurentc2730ba2014-07-20 15:47:07 -0700420void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
421{
422 bool createTxPatch = false;
423 struct audio_patch patch;
424 patch.num_sources = 1;
425 patch.num_sinks = 1;
426 status_t status;
427 audio_patch_handle_t afPatchHandle;
428 DeviceVector deviceList;
429
430 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
431 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
432
433 // release existing RX patch if any
434 if (mCallRxPatch != 0) {
435 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
436 mCallRxPatch.clear();
437 }
438 // release TX patch if any
439 if (mCallTxPatch != 0) {
440 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
441 mCallTxPatch.clear();
442 }
443
444 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
445 // via setOutputDevice() on primary output.
446 // Otherwise, create two audio patches for TX and RX path.
447 if (availablePrimaryOutputDevices() & rxDevice) {
448 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
449 // If the TX device is also on the primary HW module, setOutputDevice() will take care
450 // of it due to legacy implementation. If not, create a patch.
451 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
452 == AUDIO_DEVICE_NONE) {
453 createTxPatch = true;
454 }
455 } else {
456 // create RX path audio patch
457 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
458 ALOG_ASSERT(!deviceList.isEmpty(),
459 "updateCallRouting() selected device not in output device list");
460 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
461 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
462 ALOG_ASSERT(!deviceList.isEmpty(),
463 "updateCallRouting() no telephony RX device");
464 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
465
466 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
467 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
468
469 // request to reuse existing output stream if one is already opened to reach the RX device
470 SortedVector<audio_io_handle_t> outputs =
471 getOutputsForDevice(rxDevice, mOutputs);
472 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
473 if (output != AUDIO_IO_HANDLE_NONE) {
474 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
475 ALOG_ASSERT(!outputDesc->isDuplicated(),
476 "updateCallRouting() RX device output is duplicated");
477 outputDesc->toAudioPortConfig(&patch.sources[1]);
478 patch.num_sources = 2;
479 }
480
481 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
482 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
483 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
484 status);
485 if (status == NO_ERROR) {
486 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
487 &patch, mUidCached);
488 mCallRxPatch->mAfPatchHandle = afPatchHandle;
489 mCallRxPatch->mUid = mUidCached;
490 }
491 createTxPatch = true;
492 }
493 if (createTxPatch) {
494
495 struct audio_patch patch;
496 patch.num_sources = 1;
497 patch.num_sinks = 1;
498 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
499 ALOG_ASSERT(!deviceList.isEmpty(),
500 "updateCallRouting() selected device not in input device list");
501 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
502 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
503 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
504 ALOG_ASSERT(!deviceList.isEmpty(),
505 "updateCallRouting() no telephony TX device");
506 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
507 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
508
509 SortedVector<audio_io_handle_t> outputs =
510 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
511 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
512 // request to reuse existing output stream if one is already opened to reach the TX
513 // path output device
514 if (output != AUDIO_IO_HANDLE_NONE) {
515 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
516 ALOG_ASSERT(!outputDesc->isDuplicated(),
517 "updateCallRouting() RX device output is duplicated");
518 outputDesc->toAudioPortConfig(&patch.sources[1]);
519 patch.num_sources = 2;
520 }
521
522 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
523 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
524 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
525 status);
526 if (status == NO_ERROR) {
527 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
528 &patch, mUidCached);
529 mCallTxPatch->mAfPatchHandle = afPatchHandle;
530 mCallTxPatch->mUid = mUidCached;
531 }
532 }
533}
534
Eric Laurente0720872014-03-11 09:30:41 -0700535void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700536{
537 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700538 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700539 ALOGW("setPhoneState() invalid state %d", state);
540 return;
541 }
542
543 if (state == mPhoneState ) {
544 ALOGW("setPhoneState() setting same state %d", state);
545 return;
546 }
547
548 // if leaving call state, handle special case of active streams
549 // pertaining to sonification strategy see handleIncallSonification()
550 if (isInCall()) {
551 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700552 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
553 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700554 }
555 }
556
557 // store previous phone state for management of sonification strategy below
558 int oldState = mPhoneState;
559 mPhoneState = state;
560 bool force = false;
561
562 // are we entering or starting a call
563 if (!isStateInCall(oldState) && isStateInCall(state)) {
564 ALOGV(" Entering call in setPhoneState()");
565 // force routing command to audio hardware when starting a call
566 // even if no device change is needed
567 force = true;
568 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
569 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
570 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
571 }
572 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
573 ALOGV(" Exiting call in setPhoneState()");
574 // force routing command to audio hardware when exiting a call
575 // even if no device change is needed
576 force = true;
577 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
578 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
579 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
580 }
581 } else if (isStateInCall(state) && (state != oldState)) {
582 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
583 // force routing command to audio hardware when switching between telephony and VoIP
584 // even if no device change is needed
585 force = true;
586 }
587
588 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700589 checkA2dpSuspend();
590 checkOutputForAllStrategies();
591 updateDevicesAndOutputs();
592
Eric Laurent1f2f2232014-06-02 12:01:23 -0700593 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700594
Eric Laurente552edb2014-03-10 17:42:56 -0700595 int delayMs = 0;
596 if (isStateInCall(state)) {
597 nsecs_t sysTime = systemTime();
598 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700599 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700600 // mute media and sonification strategies and delay device switch by the largest
601 // latency of any output where either strategy is active.
602 // This avoid sending the ring tone or music tail into the earpiece or headset.
603 if ((desc->isStrategyActive(STRATEGY_MEDIA,
604 SONIFICATION_HEADSET_MUSIC_DELAY,
605 sysTime) ||
606 desc->isStrategyActive(STRATEGY_SONIFICATION,
607 SONIFICATION_HEADSET_MUSIC_DELAY,
608 sysTime)) &&
609 (delayMs < (int)desc->mLatency*2)) {
610 delayMs = desc->mLatency*2;
611 }
612 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
613 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
614 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
615 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
616 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
617 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
618 }
619 }
620
Eric Laurentc2730ba2014-07-20 15:47:07 -0700621 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
622 // the device returned is not necessarily reachable via this output
623 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
624 // force routing command to audio hardware when ending call
625 // even if no device change is needed
626 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
627 rxDevice = hwOutputDesc->device();
628 }
Eric Laurente552edb2014-03-10 17:42:56 -0700629
Eric Laurentc2730ba2014-07-20 15:47:07 -0700630 if (state == AUDIO_MODE_IN_CALL) {
631 updateCallRouting(rxDevice, delayMs);
632 } else if (oldState == AUDIO_MODE_IN_CALL) {
633 if (mCallRxPatch != 0) {
634 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
635 mCallRxPatch.clear();
636 }
637 if (mCallTxPatch != 0) {
638 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
639 mCallTxPatch.clear();
640 }
641 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
642 } else {
643 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
644 }
Eric Laurente552edb2014-03-10 17:42:56 -0700645 // if entering in call state, handle special case of active streams
646 // pertaining to sonification strategy see handleIncallSonification()
647 if (isStateInCall(state)) {
648 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700649 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
650 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700651 }
652 }
653
654 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700655 if (state == AUDIO_MODE_RINGTONE &&
656 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700657 mLimitRingtoneVolume = true;
658 } else {
659 mLimitRingtoneVolume = false;
660 }
661}
662
Eric Laurente0720872014-03-11 09:30:41 -0700663void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700664 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700665{
666 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
667
668 bool forceVolumeReeval = false;
669 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700670 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
671 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
672 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700673 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
674 return;
675 }
676 forceVolumeReeval = true;
677 mForceUse[usage] = config;
678 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700679 case AUDIO_POLICY_FORCE_FOR_MEDIA:
680 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
681 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
682 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
683 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900684 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700685 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
686 return;
687 }
688 mForceUse[usage] = config;
689 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700690 case AUDIO_POLICY_FORCE_FOR_RECORD:
691 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
692 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700693 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
694 return;
695 }
696 mForceUse[usage] = config;
697 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700698 case AUDIO_POLICY_FORCE_FOR_DOCK:
699 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
700 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
701 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
702 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
703 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700704 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
705 }
706 forceVolumeReeval = true;
707 mForceUse[usage] = config;
708 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700709 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
710 if (config != AUDIO_POLICY_FORCE_NONE &&
711 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700712 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
713 }
714 forceVolumeReeval = true;
715 mForceUse[usage] = config;
716 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900717 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
718 if (config != AUDIO_POLICY_FORCE_NONE &&
719 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
720 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
721 }
722 mForceUse[usage] = config;
723 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700724 default:
725 ALOGW("setForceUse() invalid usage %d", usage);
726 break;
727 }
728
729 // check for device and output changes triggered by new force usage
730 checkA2dpSuspend();
731 checkOutputForAllStrategies();
732 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700733 if (mPhoneState == AUDIO_MODE_IN_CALL) {
734 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
735 updateCallRouting(newDevice);
736 }
Eric Laurente552edb2014-03-10 17:42:56 -0700737 for (size_t i = 0; i < mOutputs.size(); i++) {
738 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700739 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700740 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
741 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
742 }
Eric Laurente552edb2014-03-10 17:42:56 -0700743 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
744 applyStreamVolumes(output, newDevice, 0, true);
745 }
746 }
747
748 audio_io_handle_t activeInput = getActiveInput();
749 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700750 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700751 }
752
753}
754
Eric Laurente0720872014-03-11 09:30:41 -0700755audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700756{
757 return mForceUse[usage];
758}
759
Eric Laurente0720872014-03-11 09:30:41 -0700760void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700761{
762 ALOGV("setSystemProperty() property %s, value %s", property, value);
763}
764
765// Find a direct output profile compatible with the parameters passed, even if the input flags do
766// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700767sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700768 audio_devices_t device,
769 uint32_t samplingRate,
770 audio_format_t format,
771 audio_channel_mask_t channelMask,
772 audio_output_flags_t flags)
773{
774 for (size_t i = 0; i < mHwModules.size(); i++) {
775 if (mHwModules[i]->mHandle == 0) {
776 continue;
777 }
778 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700779 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700780 bool found = profile->isCompatibleProfile(device, samplingRate,
781 NULL /*updatedSamplingRate*/, format, channelMask,
782 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
783 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700784 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
785 return profile;
786 }
Eric Laurente552edb2014-03-10 17:42:56 -0700787 }
788 }
789 return 0;
790}
791
Eric Laurente0720872014-03-11 09:30:41 -0700792audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700793 uint32_t samplingRate,
794 audio_format_t format,
795 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700796 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700797 const audio_offload_info_t *offloadInfo)
798{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700799
Eric Laurent3b73df72014-03-11 09:06:29 -0700800 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700801 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
802 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
803 device, stream, samplingRate, format, channelMask, flags);
804
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700805 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
806 offloadInfo);
807}
808
809audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
810 uint32_t samplingRate,
811 audio_format_t format,
812 audio_channel_mask_t channelMask,
813 audio_output_flags_t flags,
814 const audio_offload_info_t *offloadInfo)
815{
816 if (attr == NULL) {
817 ALOGE("getOutputForAttr() called with NULL audio attributes");
818 return 0;
819 }
820 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
821 attr->usage, attr->content_type, attr->tags);
822
823 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
824 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
825 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
826 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
827 device, samplingRate, format, channelMask, flags);
828
829 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
830 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
831 offloadInfo);
832}
833
834audio_io_handle_t AudioPolicyManager::getOutputForDevice(
835 audio_devices_t device,
836 audio_stream_type_t stream,
837 uint32_t samplingRate,
838 audio_format_t format,
839 audio_channel_mask_t channelMask,
840 audio_output_flags_t flags,
841 const audio_offload_info_t *offloadInfo)
842{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700843 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700844 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700845 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700846
Eric Laurente552edb2014-03-10 17:42:56 -0700847#ifdef AUDIO_POLICY_TEST
848 if (mCurOutput != 0) {
849 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
850 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
851
852 if (mTestOutputs[mCurOutput] == 0) {
853 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700854 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700855 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700856 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700857 outputDesc->mFlags =
858 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700859 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700860 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
861 config.sample_rate = mTestSamplingRate;
862 config.channel_mask = mTestChannels;
863 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700864 if (offloadInfo != NULL) {
865 config.offload_info = *offloadInfo;
866 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700867 status = mpClientInterface->openOutput(0,
868 &mTestOutputs[mCurOutput],
869 &config,
870 &outputDesc->mDevice,
871 String8(""),
872 &outputDesc->mLatency,
873 outputDesc->mFlags);
874 if (status == NO_ERROR) {
875 outputDesc->mSamplingRate = config.sample_rate;
876 outputDesc->mFormat = config.format;
877 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700878 AudioParameter outputCmd = AudioParameter();
879 outputCmd.addInt(String8("set_id"),mCurOutput);
880 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
881 addOutput(mTestOutputs[mCurOutput], outputDesc);
882 }
883 }
884 return mTestOutputs[mCurOutput];
885 }
886#endif //AUDIO_POLICY_TEST
887
888 // open a direct output if required by specified parameters
889 //force direct flag if offload flag is set: offloading implies a direct output stream
890 // and all common behaviors are driven by checking only the direct flag
891 // this should normally be set appropriately in the policy configuration file
892 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700893 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700894 }
895
896 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
897 // creating an offloaded track and tearing it down immediately after start when audioflinger
898 // detects there is an active non offloadable effect.
899 // FIXME: We should check the audio session here but we do not have it in this context.
900 // This may prevent offloading in rare situations where effects are left active by apps
901 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700902 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700903 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
904 !isNonOffloadableEffectEnabled()) {
905 profile = getProfileForDirectOutput(device,
906 samplingRate,
907 format,
908 channelMask,
909 (audio_output_flags_t)flags);
910 }
911
Eric Laurent1c333e22014-05-20 10:48:17 -0700912 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700913 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700914
915 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700916 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700917 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
918 outputDesc = desc;
919 // reuse direct output if currently open and configured with same parameters
920 if ((samplingRate == outputDesc->mSamplingRate) &&
921 (format == outputDesc->mFormat) &&
922 (channelMask == outputDesc->mChannelMask)) {
923 outputDesc->mDirectOpenCount++;
924 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
925 return mOutputs.keyAt(i);
926 }
927 }
928 }
929 // close direct output if currently open and configured with different parameters
930 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700931 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700932 }
933 outputDesc = new AudioOutputDescriptor(profile);
934 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700935 outputDesc->mLatency = 0;
936 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700937 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
938 config.sample_rate = samplingRate;
939 config.channel_mask = channelMask;
940 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700941 if (offloadInfo != NULL) {
942 config.offload_info = *offloadInfo;
943 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700944 status = mpClientInterface->openOutput(profile->mModule->mHandle,
945 &output,
946 &config,
947 &outputDesc->mDevice,
948 String8(""),
949 &outputDesc->mLatency,
950 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700951
952 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700953 if (status != NO_ERROR ||
954 (samplingRate != 0 && samplingRate != config.sample_rate) ||
955 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
956 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700957 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
958 "format %d %d, channelMask %04x %04x", output, samplingRate,
959 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
960 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700961 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700962 mpClientInterface->closeOutput(output);
963 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700964 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700965 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700966 outputDesc->mSamplingRate = config.sample_rate;
967 outputDesc->mChannelMask = config.channel_mask;
968 outputDesc->mFormat = config.format;
969 outputDesc->mRefCount[stream] = 0;
970 outputDesc->mStopTime[stream] = 0;
971 outputDesc->mDirectOpenCount = 1;
972
Eric Laurente552edb2014-03-10 17:42:56 -0700973 audio_io_handle_t srcOutput = getOutputForEffect();
974 addOutput(output, outputDesc);
975 audio_io_handle_t dstOutput = getOutputForEffect();
976 if (dstOutput == output) {
977 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
978 }
979 mPreviousOutputs = mOutputs;
980 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700981 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700982 return output;
983 }
984
985 // ignoring channel mask due to downmix capability in mixer
986
987 // open a non direct output
988
989 // for non direct outputs, only PCM is supported
990 if (audio_is_linear_pcm(format)) {
991 // get which output is suitable for the specified stream. The actual
992 // routing change will happen when startOutput() will be called
993 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
994
995 output = selectOutput(outputs, flags);
996 }
997 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
998 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
999
1000 ALOGV("getOutput() returns output %d", output);
1001
1002 return output;
1003}
1004
Eric Laurente0720872014-03-11 09:30:41 -07001005audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -07001006 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001007{
1008 // select one output among several that provide a path to a particular device or set of
1009 // devices (the list was previously build by getOutputsForDevice()).
1010 // The priority is as follows:
1011 // 1: the output with the highest number of requested policy flags
1012 // 2: the primary output
1013 // 3: the first output in the list
1014
1015 if (outputs.size() == 0) {
1016 return 0;
1017 }
1018 if (outputs.size() == 1) {
1019 return outputs[0];
1020 }
1021
1022 int maxCommonFlags = 0;
1023 audio_io_handle_t outputFlags = 0;
1024 audio_io_handle_t outputPrimary = 0;
1025
1026 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001027 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001028 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001029 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001030 if (commonFlags > maxCommonFlags) {
1031 outputFlags = outputs[i];
1032 maxCommonFlags = commonFlags;
1033 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1034 }
1035 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1036 outputPrimary = outputs[i];
1037 }
1038 }
1039 }
1040
1041 if (outputFlags != 0) {
1042 return outputFlags;
1043 }
1044 if (outputPrimary != 0) {
1045 return outputPrimary;
1046 }
1047
1048 return outputs[0];
1049}
1050
Eric Laurente0720872014-03-11 09:30:41 -07001051status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001052 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001053 int session)
1054{
1055 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1056 ssize_t index = mOutputs.indexOfKey(output);
1057 if (index < 0) {
1058 ALOGW("startOutput() unknown output %d", output);
1059 return BAD_VALUE;
1060 }
1061
Eric Laurent1f2f2232014-06-02 12:01:23 -07001062 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001063
1064 // increment usage count for this stream on the requested output:
1065 // NOTE that the usage count is the same for duplicated output and hardware output which is
1066 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1067 outputDesc->changeRefCount(stream, 1);
1068
1069 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001070 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001071 routing_strategy strategy = getStrategy(stream);
1072 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1073 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1074 uint32_t waitMs = 0;
1075 bool force = false;
1076 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001077 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001078 if (desc != outputDesc) {
1079 // force a device change if any other output is managed by the same hw
1080 // module and has a current device selection that differs from selected device.
1081 // In this case, the audio HAL must receive the new device selection so that it can
1082 // change the device currently selected by the other active output.
1083 if (outputDesc->sharesHwModuleWith(desc) &&
1084 desc->device() != newDevice) {
1085 force = true;
1086 }
1087 // wait for audio on other active outputs to be presented when starting
1088 // a notification so that audio focus effect can propagate.
1089 uint32_t latency = desc->latency();
1090 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1091 waitMs = latency;
1092 }
1093 }
1094 }
1095 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1096
1097 // handle special case for sonification while in call
1098 if (isInCall()) {
1099 handleIncallSonification(stream, true, false);
1100 }
1101
1102 // apply volume rules for current stream and device if necessary
1103 checkAndSetVolume(stream,
1104 mStreams[stream].getVolumeIndex(newDevice),
1105 output,
1106 newDevice);
1107
1108 // update the outputs if starting an output with a stream that can affect notification
1109 // routing
1110 handleNotificationRoutingForStream(stream);
1111 if (waitMs > muteWaitMs) {
1112 usleep((waitMs - muteWaitMs) * 2 * 1000);
1113 }
1114 }
1115 return NO_ERROR;
1116}
1117
1118
Eric Laurente0720872014-03-11 09:30:41 -07001119status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001120 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001121 int session)
1122{
1123 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1124 ssize_t index = mOutputs.indexOfKey(output);
1125 if (index < 0) {
1126 ALOGW("stopOutput() unknown output %d", output);
1127 return BAD_VALUE;
1128 }
1129
Eric Laurent1f2f2232014-06-02 12:01:23 -07001130 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001131
1132 // handle special case for sonification while in call
1133 if (isInCall()) {
1134 handleIncallSonification(stream, false, false);
1135 }
1136
1137 if (outputDesc->mRefCount[stream] > 0) {
1138 // decrement usage count of this stream on the output
1139 outputDesc->changeRefCount(stream, -1);
1140 // store time at which the stream was stopped - see isStreamActive()
1141 if (outputDesc->mRefCount[stream] == 0) {
1142 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001143 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001144 // delay the device switch by twice the latency because stopOutput() is executed when
1145 // the track stop() command is received and at that time the audio track buffer can
1146 // still contain data that needs to be drained. The latency only covers the audio HAL
1147 // and kernel buffers. Also the latency does not always include additional delay in the
1148 // audio path (audio DSP, CODEC ...)
1149 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1150
1151 // force restoring the device selection on other active outputs if it differs from the
1152 // one being selected for this output
1153 for (size_t i = 0; i < mOutputs.size(); i++) {
1154 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001155 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001156 if (curOutput != output &&
1157 desc->isActive() &&
1158 outputDesc->sharesHwModuleWith(desc) &&
1159 (newDevice != desc->device())) {
1160 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001161 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001162 true,
1163 outputDesc->mLatency*2);
1164 }
1165 }
1166 // update the outputs if stopping one with a stream that can affect notification routing
1167 handleNotificationRoutingForStream(stream);
1168 }
1169 return NO_ERROR;
1170 } else {
1171 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1172 return INVALID_OPERATION;
1173 }
1174}
1175
Eric Laurente0720872014-03-11 09:30:41 -07001176void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001177{
1178 ALOGV("releaseOutput() %d", output);
1179 ssize_t index = mOutputs.indexOfKey(output);
1180 if (index < 0) {
1181 ALOGW("releaseOutput() releasing unknown output %d", output);
1182 return;
1183 }
1184
1185#ifdef AUDIO_POLICY_TEST
1186 int testIndex = testOutputIndex(output);
1187 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001188 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001189 if (outputDesc->isActive()) {
1190 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001191 mOutputs.removeItem(output);
1192 mTestOutputs[testIndex] = 0;
1193 }
1194 return;
1195 }
1196#endif //AUDIO_POLICY_TEST
1197
Eric Laurent1f2f2232014-06-02 12:01:23 -07001198 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001199 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001200 if (desc->mDirectOpenCount <= 0) {
1201 ALOGW("releaseOutput() invalid open count %d for output %d",
1202 desc->mDirectOpenCount, output);
1203 return;
1204 }
1205 if (--desc->mDirectOpenCount == 0) {
1206 closeOutput(output);
1207 // If effects where present on the output, audioflinger moved them to the primary
1208 // output by default: move them back to the appropriate output.
1209 audio_io_handle_t dstOutput = getOutputForEffect();
1210 if (dstOutput != mPrimaryOutput) {
1211 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1212 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001213 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001214 }
1215 }
1216}
1217
1218
Eric Laurente0720872014-03-11 09:30:41 -07001219audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001220 uint32_t samplingRate,
1221 audio_format_t format,
1222 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001223 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001224 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001225{
Eric Laurent4dc68062014-07-28 17:26:49 -07001226 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001227 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001228 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001229
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001230 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001231
1232 if (device == AUDIO_DEVICE_NONE) {
1233 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001234 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001235 }
1236
1237 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001238 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001239 case AUDIO_SOURCE_VOICE_UPLINK:
1240 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1241 break;
1242 case AUDIO_SOURCE_VOICE_DOWNLINK:
1243 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1244 break;
1245 case AUDIO_SOURCE_VOICE_CALL:
1246 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1247 break;
1248 default:
1249 break;
1250 }
1251
Eric Laurent1c333e22014-05-20 10:48:17 -07001252 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001253 samplingRate,
1254 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001255 channelMask,
1256 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001257 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001258 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1259 "channelMask 0x%X, flags %#x",
1260 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001261 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001262 }
1263
1264 if (profile->mModule->mHandle == 0) {
1265 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001266 return AUDIO_IO_HANDLE_NONE;
1267 }
1268
1269 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1270 config.sample_rate = samplingRate;
1271 config.channel_mask = channelMask;
1272 config.format = format;
1273 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001274
1275 bool isSoundTrigger = false;
1276 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1277 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1278 if (index >= 0) {
1279 input = mSoundTriggerSessions.valueFor(session);
1280 isSoundTrigger = true;
1281 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1282 }
1283 }
1284
Eric Laurentcf2c0212014-07-25 16:20:43 -07001285 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1286 &input,
1287 &config,
1288 &device,
1289 String8(""),
1290 inputSource,
1291 flags);
1292
1293 // only accept input with the exact requested set of parameters
1294 if (status != NO_ERROR ||
1295 (samplingRate != config.sample_rate) ||
1296 (format != config.format) ||
1297 (channelMask != config.channel_mask)) {
1298 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1299 samplingRate, format, channelMask);
1300 if (input != AUDIO_IO_HANDLE_NONE) {
1301 mpClientInterface->closeInput(input);
1302 }
1303 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001304 }
1305
Eric Laurent1f2f2232014-06-02 12:01:23 -07001306 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001307 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001308 inputDesc->mRefCount = 0;
1309 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001310 inputDesc->mSamplingRate = samplingRate;
1311 inputDesc->mFormat = format;
1312 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001313 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001314 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001315 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001316
Eric Laurentd4692962014-05-05 18:13:44 -07001317 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001318 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001319 return input;
1320}
1321
Eric Laurent4dc68062014-07-28 17:26:49 -07001322status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1323 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001324{
1325 ALOGV("startInput() input %d", input);
1326 ssize_t index = mInputs.indexOfKey(input);
1327 if (index < 0) {
1328 ALOGW("startInput() unknown input %d", input);
1329 return BAD_VALUE;
1330 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001331 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001332
Eric Laurent4dc68062014-07-28 17:26:49 -07001333 index = inputDesc->mSessions.indexOf(session);
1334 if (index < 0) {
1335 ALOGW("startInput() unknown session %d on input %d", session, input);
1336 return BAD_VALUE;
1337 }
1338
Glenn Kasten74a8e252014-07-24 14:09:55 -07001339 // virtual input devices are compatible with other input devices
1340 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1341
1342 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001343 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001344 if (activeInput != 0 && activeInput != input) {
1345
1346 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1347 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001348 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001349 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001350 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001351 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1352 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001353 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001354 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001355 return INVALID_OPERATION;
1356 }
1357 }
1358 }
1359
Glenn Kasten74a8e252014-07-24 14:09:55 -07001360 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001361 if (activeInputsCount() == 0) {
1362 SoundTrigger::setCaptureState(true);
1363 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001364 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001365
Glenn Kasten74a8e252014-07-24 14:09:55 -07001366 // Automatically enable the remote submix output when input is started.
1367 // For remote submix (a virtual device), we open only one input per capture request.
1368 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1369 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1370 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1371 }
Eric Laurente552edb2014-03-10 17:42:56 -07001372 }
1373
Eric Laurente552edb2014-03-10 17:42:56 -07001374 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1375
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001376 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001377 return NO_ERROR;
1378}
1379
Eric Laurent4dc68062014-07-28 17:26:49 -07001380status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1381 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001382{
1383 ALOGV("stopInput() input %d", input);
1384 ssize_t index = mInputs.indexOfKey(input);
1385 if (index < 0) {
1386 ALOGW("stopInput() unknown input %d", input);
1387 return BAD_VALUE;
1388 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001389 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001390
Eric Laurent4dc68062014-07-28 17:26:49 -07001391 index = inputDesc->mSessions.indexOf(session);
1392 if (index < 0) {
1393 ALOGW("stopInput() unknown session %d on input %d", session, input);
1394 return BAD_VALUE;
1395 }
1396
Eric Laurente552edb2014-03-10 17:42:56 -07001397 if (inputDesc->mRefCount == 0) {
1398 ALOGW("stopInput() input %d already stopped", input);
1399 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001400 }
1401
1402 inputDesc->mRefCount--;
1403 if (inputDesc->mRefCount == 0) {
1404
Eric Laurente552edb2014-03-10 17:42:56 -07001405 // automatically disable the remote submix output when input is stopped
1406 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1407 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001408 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001409 }
1410
Eric Laurent1c333e22014-05-20 10:48:17 -07001411 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001412
1413 if (activeInputsCount() == 0) {
1414 SoundTrigger::setCaptureState(false);
1415 }
Eric Laurente552edb2014-03-10 17:42:56 -07001416 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001417 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001418}
1419
Eric Laurent4dc68062014-07-28 17:26:49 -07001420void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1421 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001422{
1423 ALOGV("releaseInput() %d", input);
1424 ssize_t index = mInputs.indexOfKey(input);
1425 if (index < 0) {
1426 ALOGW("releaseInput() releasing unknown input %d", input);
1427 return;
1428 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001429 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1430 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001431
1432 index = inputDesc->mSessions.indexOf(session);
1433 if (index < 0) {
1434 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1435 return;
1436 }
1437 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001438 if (inputDesc->mOpenRefCount == 0) {
1439 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1440 return;
1441 }
1442 inputDesc->mOpenRefCount--;
1443 if (inputDesc->mOpenRefCount > 0) {
1444 ALOGV("releaseInput() exit > 0");
1445 return;
1446 }
1447
Eric Laurente552edb2014-03-10 17:42:56 -07001448 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001449 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001450 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001451 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001452 ALOGV("releaseInput() exit");
1453}
1454
Eric Laurentd4692962014-05-05 18:13:44 -07001455void AudioPolicyManager::closeAllInputs() {
1456 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1457 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1458 }
1459 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001460 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001461}
1462
Eric Laurente0720872014-03-11 09:30:41 -07001463void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001464 int indexMin,
1465 int indexMax)
1466{
1467 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1468 if (indexMin < 0 || indexMin >= indexMax) {
1469 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1470 return;
1471 }
1472 mStreams[stream].mIndexMin = indexMin;
1473 mStreams[stream].mIndexMax = indexMax;
1474}
1475
Eric Laurente0720872014-03-11 09:30:41 -07001476status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001477 int index,
1478 audio_devices_t device)
1479{
1480
1481 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1482 return BAD_VALUE;
1483 }
1484 if (!audio_is_output_device(device)) {
1485 return BAD_VALUE;
1486 }
1487
1488 // Force max volume if stream cannot be muted
1489 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1490
1491 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1492 stream, device, index);
1493
1494 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1495 // clear all device specific values
1496 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1497 mStreams[stream].mIndexCur.clear();
1498 }
1499 mStreams[stream].mIndexCur.add(device, index);
1500
1501 // compute and apply stream volume on all outputs according to connected device
1502 status_t status = NO_ERROR;
1503 for (size_t i = 0; i < mOutputs.size(); i++) {
1504 audio_devices_t curDevice =
1505 getDeviceForVolume(mOutputs.valueAt(i)->device());
1506 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1507 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1508 if (volStatus != NO_ERROR) {
1509 status = volStatus;
1510 }
1511 }
1512 }
1513 return status;
1514}
1515
Eric Laurente0720872014-03-11 09:30:41 -07001516status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001517 int *index,
1518 audio_devices_t device)
1519{
1520 if (index == NULL) {
1521 return BAD_VALUE;
1522 }
1523 if (!audio_is_output_device(device)) {
1524 return BAD_VALUE;
1525 }
1526 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1527 // the strategy the stream belongs to.
1528 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1529 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1530 }
1531 device = getDeviceForVolume(device);
1532
1533 *index = mStreams[stream].getVolumeIndex(device);
1534 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1535 return NO_ERROR;
1536}
1537
Eric Laurente0720872014-03-11 09:30:41 -07001538audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001539 const SortedVector<audio_io_handle_t>& outputs)
1540{
1541 // select one output among several suitable for global effects.
1542 // The priority is as follows:
1543 // 1: An offloaded output. If the effect ends up not being offloadable,
1544 // AudioFlinger will invalidate the track and the offloaded output
1545 // will be closed causing the effect to be moved to a PCM output.
1546 // 2: A deep buffer output
1547 // 3: the first output in the list
1548
1549 if (outputs.size() == 0) {
1550 return 0;
1551 }
1552
1553 audio_io_handle_t outputOffloaded = 0;
1554 audio_io_handle_t outputDeepBuffer = 0;
1555
1556 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001557 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001558 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001559 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1560 outputOffloaded = outputs[i];
1561 }
1562 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1563 outputDeepBuffer = outputs[i];
1564 }
1565 }
1566
1567 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1568 outputOffloaded, outputDeepBuffer);
1569 if (outputOffloaded != 0) {
1570 return outputOffloaded;
1571 }
1572 if (outputDeepBuffer != 0) {
1573 return outputDeepBuffer;
1574 }
1575
1576 return outputs[0];
1577}
1578
Eric Laurente0720872014-03-11 09:30:41 -07001579audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001580{
1581 // apply simple rule where global effects are attached to the same output as MUSIC streams
1582
Eric Laurent3b73df72014-03-11 09:06:29 -07001583 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001584 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1585 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1586
1587 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1588 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1589 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1590
1591 return output;
1592}
1593
Eric Laurente0720872014-03-11 09:30:41 -07001594status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001595 audio_io_handle_t io,
1596 uint32_t strategy,
1597 int session,
1598 int id)
1599{
1600 ssize_t index = mOutputs.indexOfKey(io);
1601 if (index < 0) {
1602 index = mInputs.indexOfKey(io);
1603 if (index < 0) {
1604 ALOGW("registerEffect() unknown io %d", io);
1605 return INVALID_OPERATION;
1606 }
1607 }
1608
1609 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1610 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1611 desc->name, desc->memoryUsage);
1612 return INVALID_OPERATION;
1613 }
1614 mTotalEffectsMemory += desc->memoryUsage;
1615 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1616 desc->name, io, strategy, session, id);
1617 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1618
Eric Laurent1f2f2232014-06-02 12:01:23 -07001619 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1620 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1621 effectDesc->mIo = io;
1622 effectDesc->mStrategy = (routing_strategy)strategy;
1623 effectDesc->mSession = session;
1624 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001625
Eric Laurent1f2f2232014-06-02 12:01:23 -07001626 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001627
1628 return NO_ERROR;
1629}
1630
Eric Laurente0720872014-03-11 09:30:41 -07001631status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001632{
1633 ssize_t index = mEffects.indexOfKey(id);
1634 if (index < 0) {
1635 ALOGW("unregisterEffect() unknown effect ID %d", id);
1636 return INVALID_OPERATION;
1637 }
1638
Eric Laurent1f2f2232014-06-02 12:01:23 -07001639 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001640
Eric Laurent1f2f2232014-06-02 12:01:23 -07001641 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001642
Eric Laurent1f2f2232014-06-02 12:01:23 -07001643 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001644 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001645 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1646 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001647 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001648 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001649 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001650 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001651
1652 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001653
1654 return NO_ERROR;
1655}
1656
Eric Laurente0720872014-03-11 09:30:41 -07001657status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001658{
1659 ssize_t index = mEffects.indexOfKey(id);
1660 if (index < 0) {
1661 ALOGW("unregisterEffect() unknown effect ID %d", id);
1662 return INVALID_OPERATION;
1663 }
1664
1665 return setEffectEnabled(mEffects.valueAt(index), enabled);
1666}
1667
Eric Laurent1f2f2232014-06-02 12:01:23 -07001668status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001669{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001670 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001671 ALOGV("setEffectEnabled(%s) effect already %s",
1672 enabled?"true":"false", enabled?"enabled":"disabled");
1673 return INVALID_OPERATION;
1674 }
1675
1676 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001677 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001678 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001679 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001680 return INVALID_OPERATION;
1681 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001682 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001683 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1684 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001685 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001686 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001687 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1688 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001689 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001690 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001691 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1692 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001693 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001694 return NO_ERROR;
1695}
1696
Eric Laurente0720872014-03-11 09:30:41 -07001697bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001698{
1699 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001700 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1701 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1702 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001703 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001704 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001705 return true;
1706 }
1707 }
1708 return false;
1709}
1710
Eric Laurente0720872014-03-11 09:30:41 -07001711bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001712{
1713 nsecs_t sysTime = systemTime();
1714 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001715 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001716 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001717 return true;
1718 }
1719 }
1720 return false;
1721}
1722
Eric Laurente0720872014-03-11 09:30:41 -07001723bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001724 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001725{
1726 nsecs_t sysTime = systemTime();
1727 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001728 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001729 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001730 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001731 return true;
1732 }
1733 }
1734 return false;
1735}
1736
Eric Laurente0720872014-03-11 09:30:41 -07001737bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001738{
1739 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001740 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001741 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001742 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001743 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1744 && (inputDescriptor->mRefCount > 0)) {
1745 return true;
1746 }
1747 }
1748 return false;
1749}
1750
1751
Eric Laurente0720872014-03-11 09:30:41 -07001752status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001753{
1754 const size_t SIZE = 256;
1755 char buffer[SIZE];
1756 String8 result;
1757
1758 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1759 result.append(buffer);
1760
1761 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1762 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001763 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1764 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001765 snprintf(buffer, SIZE, " Force use for communications %d\n",
1766 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001767 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001768 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001769 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001770 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001771 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001772 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001773 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001774 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001775 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001776 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1777 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1778 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001779
Eric Laurent3a4311c2014-03-17 12:00:47 -07001780 snprintf(buffer, SIZE, " Available output devices:\n");
1781 result.append(buffer);
1782 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001783 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001784 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001785 }
1786 snprintf(buffer, SIZE, "\n Available input devices:\n");
1787 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001788 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001789 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001790 }
Eric Laurente552edb2014-03-10 17:42:56 -07001791
1792 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1793 write(fd, buffer, strlen(buffer));
1794 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001795 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001796 write(fd, buffer, strlen(buffer));
1797 mHwModules[i]->dump(fd);
1798 }
1799
1800 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1801 write(fd, buffer, strlen(buffer));
1802 for (size_t i = 0; i < mOutputs.size(); i++) {
1803 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1804 write(fd, buffer, strlen(buffer));
1805 mOutputs.valueAt(i)->dump(fd);
1806 }
1807
1808 snprintf(buffer, SIZE, "\nInputs dump:\n");
1809 write(fd, buffer, strlen(buffer));
1810 for (size_t i = 0; i < mInputs.size(); i++) {
1811 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1812 write(fd, buffer, strlen(buffer));
1813 mInputs.valueAt(i)->dump(fd);
1814 }
1815
1816 snprintf(buffer, SIZE, "\nStreams dump:\n");
1817 write(fd, buffer, strlen(buffer));
1818 snprintf(buffer, SIZE,
1819 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1820 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001821 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001822 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001823 write(fd, buffer, strlen(buffer));
1824 mStreams[i].dump(fd);
1825 }
1826
1827 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1828 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1829 write(fd, buffer, strlen(buffer));
1830
1831 snprintf(buffer, SIZE, "Registered effects:\n");
1832 write(fd, buffer, strlen(buffer));
1833 for (size_t i = 0; i < mEffects.size(); i++) {
1834 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1835 write(fd, buffer, strlen(buffer));
1836 mEffects.valueAt(i)->dump(fd);
1837 }
1838
1839
1840 return NO_ERROR;
1841}
1842
1843// This function checks for the parameters which can be offloaded.
1844// This can be enhanced depending on the capability of the DSP and policy
1845// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001846bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001847{
1848 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001849 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001850 offloadInfo.sample_rate, offloadInfo.channel_mask,
1851 offloadInfo.format,
1852 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1853 offloadInfo.has_video);
1854
1855 // Check if offload has been disabled
1856 char propValue[PROPERTY_VALUE_MAX];
1857 if (property_get("audio.offload.disable", propValue, "0")) {
1858 if (atoi(propValue) != 0) {
1859 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1860 return false;
1861 }
1862 }
1863
1864 // Check if stream type is music, then only allow offload as of now.
1865 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1866 {
1867 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1868 return false;
1869 }
1870
1871 //TODO: enable audio offloading with video when ready
1872 if (offloadInfo.has_video)
1873 {
1874 ALOGV("isOffloadSupported: has_video == true, returning false");
1875 return false;
1876 }
1877
1878 //If duration is less than minimum value defined in property, return false
1879 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1880 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1881 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1882 return false;
1883 }
1884 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1885 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1886 return false;
1887 }
1888
1889 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1890 // creating an offloaded track and tearing it down immediately after start when audioflinger
1891 // detects there is an active non offloadable effect.
1892 // FIXME: We should check the audio session here but we do not have it in this context.
1893 // This may prevent offloading in rare situations where effects are left active by apps
1894 // in the background.
1895 if (isNonOffloadableEffectEnabled()) {
1896 return false;
1897 }
1898
1899 // See if there is a profile to support this.
1900 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001901 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001902 offloadInfo.sample_rate,
1903 offloadInfo.format,
1904 offloadInfo.channel_mask,
1905 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001906 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1907 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001908}
1909
Eric Laurent6a94d692014-05-20 11:18:06 -07001910status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1911 audio_port_type_t type,
1912 unsigned int *num_ports,
1913 struct audio_port *ports,
1914 unsigned int *generation)
1915{
1916 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1917 generation == NULL) {
1918 return BAD_VALUE;
1919 }
1920 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1921 if (ports == NULL) {
1922 *num_ports = 0;
1923 }
1924
1925 size_t portsWritten = 0;
1926 size_t portsMax = *num_ports;
1927 *num_ports = 0;
1928 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1929 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1930 for (size_t i = 0;
1931 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1932 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1933 }
1934 *num_ports += mAvailableOutputDevices.size();
1935 }
1936 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1937 for (size_t i = 0;
1938 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1939 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1940 }
1941 *num_ports += mAvailableInputDevices.size();
1942 }
1943 }
1944 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1945 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1946 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1947 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1948 }
1949 *num_ports += mInputs.size();
1950 }
1951 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001952 size_t numOutputs = 0;
1953 for (size_t i = 0; i < mOutputs.size(); i++) {
1954 if (!mOutputs[i]->isDuplicated()) {
1955 numOutputs++;
1956 if (portsWritten < portsMax) {
1957 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1958 }
1959 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001960 }
Eric Laurent84c70242014-06-23 08:46:27 -07001961 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001962 }
1963 }
1964 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001965 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001966 return NO_ERROR;
1967}
1968
1969status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1970{
1971 return NO_ERROR;
1972}
1973
Eric Laurent1f2f2232014-06-02 12:01:23 -07001974sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001975 audio_port_handle_t id) const
1976{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001977 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001978 for (size_t i = 0; i < mOutputs.size(); i++) {
1979 outputDesc = mOutputs.valueAt(i);
1980 if (outputDesc->mId == id) {
1981 break;
1982 }
1983 }
1984 return outputDesc;
1985}
1986
Eric Laurent1f2f2232014-06-02 12:01:23 -07001987sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001988 audio_port_handle_t id) const
1989{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001990 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001991 for (size_t i = 0; i < mInputs.size(); i++) {
1992 inputDesc = mInputs.valueAt(i);
1993 if (inputDesc->mId == id) {
1994 break;
1995 }
1996 }
1997 return inputDesc;
1998}
1999
Eric Laurent1f2f2232014-06-02 12:01:23 -07002000sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2001 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002002{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002003 sp <HwModule> module;
2004
Eric Laurent6a94d692014-05-20 11:18:06 -07002005 for (size_t i = 0; i < mHwModules.size(); i++) {
2006 if (mHwModules[i]->mHandle == 0) {
2007 continue;
2008 }
2009 if (audio_is_output_device(device)) {
2010 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2011 {
2012 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2013 return mHwModules[i];
2014 }
2015 }
2016 } else {
2017 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2018 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2019 device & ~AUDIO_DEVICE_BIT_IN) {
2020 return mHwModules[i];
2021 }
2022 }
2023 }
2024 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002025 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002026}
2027
Eric Laurent1f2f2232014-06-02 12:01:23 -07002028sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002029{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002030 sp <HwModule> module;
2031
Eric Laurent1afeecb2014-05-14 08:52:28 -07002032 for (size_t i = 0; i < mHwModules.size(); i++)
2033 {
2034 if (strcmp(mHwModules[i]->mName, name) == 0) {
2035 return mHwModules[i];
2036 }
2037 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002038 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002039}
2040
Eric Laurentc2730ba2014-07-20 15:47:07 -07002041audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2042{
2043 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2044 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2045 return devices & mAvailableOutputDevices.types();
2046}
2047
2048audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2049{
2050 audio_module_handle_t primaryHandle =
2051 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2052 audio_devices_t devices = AUDIO_DEVICE_NONE;
2053 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2054 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2055 devices |= mAvailableInputDevices[i]->mDeviceType;
2056 }
2057 }
2058 return devices;
2059}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002060
Eric Laurent6a94d692014-05-20 11:18:06 -07002061status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2062 audio_patch_handle_t *handle,
2063 uid_t uid)
2064{
2065 ALOGV("createAudioPatch()");
2066
2067 if (handle == NULL || patch == NULL) {
2068 return BAD_VALUE;
2069 }
2070 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2071
2072 if (patch->num_sources > 1 || patch->num_sinks > 1) {
2073 return INVALID_OPERATION;
2074 }
2075 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
2076 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
2077 return INVALID_OPERATION;
2078 }
2079
2080 sp<AudioPatch> patchDesc;
2081 ssize_t index = mAudioPatches.indexOfKey(*handle);
2082
2083 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
2084 patch->sinks[0].type);
2085 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2086 patch->sources[0].role,
2087 patch->sources[0].type);
2088
2089 if (index >= 0) {
2090 patchDesc = mAudioPatches.valueAt(index);
2091 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2092 mUidCached, patchDesc->mUid, uid);
2093 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2094 return INVALID_OPERATION;
2095 }
2096 } else {
2097 *handle = 0;
2098 }
2099
2100 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
2101 // TODO add support for mix to mix connection
2102 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
2103 ALOGV("createAudioPatch() source mix sink not device");
2104 return BAD_VALUE;
2105 }
2106 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07002107 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002108 if (outputDesc == NULL) {
2109 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2110 return BAD_VALUE;
2111 }
Eric Laurent84c70242014-06-23 08:46:27 -07002112 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2113 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002114 if (patchDesc != 0) {
2115 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2116 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2117 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2118 return BAD_VALUE;
2119 }
2120 }
2121 sp<DeviceDescriptor> devDesc =
2122 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
2123 if (devDesc == 0) {
2124 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
2125 return BAD_VALUE;
2126 }
2127
Eric Laurent84c70242014-06-23 08:46:27 -07002128 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07002129 patch->sources[0].sample_rate,
Glenn Kastencbd48022014-07-24 13:46:44 -07002130 NULL, // updatedSamplingRate
Eric Laurent6a94d692014-05-20 11:18:06 -07002131 patch->sources[0].format,
2132 patch->sources[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002133 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Eric Laurent83b88082014-06-20 18:31:16 -07002134 ALOGV("createAudioPatch() profile not supported");
Eric Laurent6a94d692014-05-20 11:18:06 -07002135 return INVALID_OPERATION;
2136 }
2137 // TODO: reconfigure output format and channels here
2138 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002139 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002140 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07002141 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07002142 true,
2143 0,
2144 handle);
2145 index = mAudioPatches.indexOfKey(*handle);
2146 if (index >= 0) {
2147 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2148 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2149 }
2150 patchDesc = mAudioPatches.valueAt(index);
2151 patchDesc->mUid = uid;
2152 ALOGV("createAudioPatch() success");
2153 } else {
2154 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2155 return INVALID_OPERATION;
2156 }
2157 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2158 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2159 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07002160 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002161 if (inputDesc == NULL) {
2162 return BAD_VALUE;
2163 }
2164 if (patchDesc != 0) {
2165 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2166 return BAD_VALUE;
2167 }
2168 }
2169 sp<DeviceDescriptor> devDesc =
2170 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2171 if (devDesc == 0) {
2172 return BAD_VALUE;
2173 }
2174
Eric Laurent84c70242014-06-23 08:46:27 -07002175 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002176 patch->sinks[0].sample_rate,
2177 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002178 patch->sinks[0].format,
2179 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002180 // FIXME for the parameter type,
2181 // and the NONE
2182 (audio_output_flags_t)
2183 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002184 return INVALID_OPERATION;
2185 }
2186 // TODO: reconfigure output format and channels here
2187 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002188 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002189 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07002190 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07002191 true,
2192 handle);
2193 index = mAudioPatches.indexOfKey(*handle);
2194 if (index >= 0) {
2195 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2196 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2197 }
2198 patchDesc = mAudioPatches.valueAt(index);
2199 patchDesc->mUid = uid;
2200 ALOGV("createAudioPatch() success");
2201 } else {
2202 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2203 return INVALID_OPERATION;
2204 }
2205 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2206 // device to device connection
2207 if (patchDesc != 0) {
2208 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
2209 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2210 return BAD_VALUE;
2211 }
2212 }
2213
2214 sp<DeviceDescriptor> srcDeviceDesc =
2215 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2216 sp<DeviceDescriptor> sinkDeviceDesc =
2217 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
2218 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
2219 return BAD_VALUE;
2220 }
2221 //update source and sink with our own data as the data passed in the patch may
2222 // be incomplete.
2223 struct audio_patch newPatch = *patch;
2224 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
2225 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
2226
Eric Laurent6a94d692014-05-20 11:18:06 -07002227 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
Eric Laurent83b88082014-06-20 18:31:16 -07002228 SortedVector<audio_io_handle_t> outputs =
2229 getOutputsForDevice(sinkDeviceDesc->mDeviceType, mOutputs);
2230 // if the sink device is reachable via an opened output stream, request to go via
2231 // this output stream by adding a second source to the patch description
2232 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2233 if (output != AUDIO_IO_HANDLE_NONE) {
2234 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2235 if (outputDesc->isDuplicated()) {
2236 return INVALID_OPERATION;
2237 }
2238 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2239 newPatch.num_sources = 2;
2240 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002241 }
2242 // TODO: check from routing capabilities in config file and other conflicting patches
2243
2244 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2245 if (index >= 0) {
2246 afPatchHandle = patchDesc->mAfPatchHandle;
2247 }
2248
2249 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2250 &afPatchHandle,
2251 0);
2252 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2253 status, afPatchHandle);
2254 if (status == NO_ERROR) {
2255 if (index < 0) {
2256 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2257 &newPatch, uid);
2258 addAudioPatch(patchDesc->mHandle, patchDesc);
2259 } else {
2260 patchDesc->mPatch = newPatch;
2261 }
2262 patchDesc->mAfPatchHandle = afPatchHandle;
2263 *handle = patchDesc->mHandle;
2264 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002265 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002266 } else {
2267 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2268 status);
2269 return INVALID_OPERATION;
2270 }
2271 } else {
2272 return BAD_VALUE;
2273 }
2274 } else {
2275 return BAD_VALUE;
2276 }
2277 return NO_ERROR;
2278}
2279
2280status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2281 uid_t uid)
2282{
2283 ALOGV("releaseAudioPatch() patch %d", handle);
2284
2285 ssize_t index = mAudioPatches.indexOfKey(handle);
2286
2287 if (index < 0) {
2288 return BAD_VALUE;
2289 }
2290 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2291 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2292 mUidCached, patchDesc->mUid, uid);
2293 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2294 return INVALID_OPERATION;
2295 }
2296
2297 struct audio_patch *patch = &patchDesc->mPatch;
2298 patchDesc->mUid = mUidCached;
2299 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002300 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002301 if (outputDesc == NULL) {
2302 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2303 return BAD_VALUE;
2304 }
2305
2306 setOutputDevice(outputDesc->mIoHandle,
2307 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2308 true,
2309 0,
2310 NULL);
2311 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2312 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002313 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002314 if (inputDesc == NULL) {
2315 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2316 return BAD_VALUE;
2317 }
2318 setInputDevice(inputDesc->mIoHandle,
2319 getNewInputDevice(inputDesc->mIoHandle),
2320 true,
2321 NULL);
2322 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2323 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2324 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2325 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2326 status, patchDesc->mAfPatchHandle);
2327 removeAudioPatch(patchDesc->mHandle);
2328 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002329 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002330 } else {
2331 return BAD_VALUE;
2332 }
2333 } else {
2334 return BAD_VALUE;
2335 }
2336 return NO_ERROR;
2337}
2338
2339status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2340 struct audio_patch *patches,
2341 unsigned int *generation)
2342{
2343 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2344 generation == NULL) {
2345 return BAD_VALUE;
2346 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002347 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002348 *num_patches, patches, mAudioPatches.size());
2349 if (patches == NULL) {
2350 *num_patches = 0;
2351 }
2352
2353 size_t patchesWritten = 0;
2354 size_t patchesMax = *num_patches;
2355 for (size_t i = 0;
2356 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2357 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2358 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002359 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002360 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2361 }
2362 *num_patches = mAudioPatches.size();
2363
2364 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002365 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002366 return NO_ERROR;
2367}
2368
Eric Laurente1715a42014-05-20 11:30:42 -07002369status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002370{
Eric Laurente1715a42014-05-20 11:30:42 -07002371 ALOGV("setAudioPortConfig()");
2372
2373 if (config == NULL) {
2374 return BAD_VALUE;
2375 }
2376 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2377 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002378 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2379 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002380 }
2381
Eric Laurenta121f902014-06-03 13:32:54 -07002382 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002383 if (config->type == AUDIO_PORT_TYPE_MIX) {
2384 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002385 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002386 if (outputDesc == NULL) {
2387 return BAD_VALUE;
2388 }
Eric Laurent84c70242014-06-23 08:46:27 -07002389 ALOG_ASSERT(!outputDesc->isDuplicated(),
2390 "setAudioPortConfig() called on duplicated output %d",
2391 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002392 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002393 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002394 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002395 if (inputDesc == NULL) {
2396 return BAD_VALUE;
2397 }
Eric Laurenta121f902014-06-03 13:32:54 -07002398 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002399 } else {
2400 return BAD_VALUE;
2401 }
2402 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2403 sp<DeviceDescriptor> deviceDesc;
2404 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2405 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2406 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2407 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2408 } else {
2409 return BAD_VALUE;
2410 }
2411 if (deviceDesc == NULL) {
2412 return BAD_VALUE;
2413 }
Eric Laurenta121f902014-06-03 13:32:54 -07002414 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002415 } else {
2416 return BAD_VALUE;
2417 }
2418
Eric Laurenta121f902014-06-03 13:32:54 -07002419 struct audio_port_config backupConfig;
2420 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2421 if (status == NO_ERROR) {
2422 struct audio_port_config newConfig;
2423 audioPortConfig->toAudioPortConfig(&newConfig, config);
2424 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002425 }
Eric Laurenta121f902014-06-03 13:32:54 -07002426 if (status != NO_ERROR) {
2427 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002428 }
Eric Laurente1715a42014-05-20 11:30:42 -07002429
2430 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002431}
2432
2433void AudioPolicyManager::clearAudioPatches(uid_t uid)
2434{
2435 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2436 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2437 if (patchDesc->mUid == uid) {
2438 // releaseAudioPatch() removes the patch from mAudioPatches
2439 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2440 i--;
2441 }
2442 }
2443 }
2444}
2445
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002446status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2447 audio_io_handle_t *ioHandle,
2448 audio_devices_t *device)
2449{
2450 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2451 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2452 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2453
2454 mSoundTriggerSessions.add(*session, *ioHandle);
2455
2456 return NO_ERROR;
2457}
2458
2459status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2460{
2461 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2462 if (index < 0) {
2463 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2464 return BAD_VALUE;
2465 }
2466
2467 mSoundTriggerSessions.removeItem(session);
2468 return NO_ERROR;
2469}
2470
Eric Laurent6a94d692014-05-20 11:18:06 -07002471status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2472 const sp<AudioPatch>& patch)
2473{
2474 ssize_t index = mAudioPatches.indexOfKey(handle);
2475
2476 if (index >= 0) {
2477 ALOGW("addAudioPatch() patch %d already in", handle);
2478 return ALREADY_EXISTS;
2479 }
2480 mAudioPatches.add(handle, patch);
2481 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2482 "sink handle %d",
2483 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2484 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2485 return NO_ERROR;
2486}
2487
2488status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2489{
2490 ssize_t index = mAudioPatches.indexOfKey(handle);
2491
2492 if (index < 0) {
2493 ALOGW("removeAudioPatch() patch %d not in", handle);
2494 return ALREADY_EXISTS;
2495 }
2496 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2497 mAudioPatches.valueAt(index)->mAfPatchHandle);
2498 mAudioPatches.removeItemsAt(index);
2499 return NO_ERROR;
2500}
2501
Eric Laurente552edb2014-03-10 17:42:56 -07002502// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002503// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002504// ----------------------------------------------------------------------------
2505
Eric Laurent3a4311c2014-03-17 12:00:47 -07002506uint32_t AudioPolicyManager::nextUniqueId()
2507{
2508 return android_atomic_inc(&mNextUniqueId);
2509}
2510
Eric Laurent6a94d692014-05-20 11:18:06 -07002511uint32_t AudioPolicyManager::nextAudioPortGeneration()
2512{
2513 return android_atomic_inc(&mAudioPortGeneration);
2514}
2515
Eric Laurente0720872014-03-11 09:30:41 -07002516AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002517 :
2518#ifdef AUDIO_POLICY_TEST
2519 Thread(false),
2520#endif //AUDIO_POLICY_TEST
2521 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002522 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002523 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2524 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002525 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002526 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2527 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002528{
Eric Laurent6a94d692014-05-20 11:18:06 -07002529 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002530 mpClientInterface = clientInterface;
2531
Eric Laurent3b73df72014-03-11 09:06:29 -07002532 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2533 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002534 }
2535
Eric Laurent1afeecb2014-05-14 08:52:28 -07002536 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002537 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2538 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2539 ALOGE("could not load audio policy configuration file, setting defaults");
2540 defaultAudioPolicyConfig();
2541 }
2542 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002543 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002544
2545 // must be done after reading the policy
2546 initializeVolumeCurves();
2547
2548 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002549 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2550 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002551 for (size_t i = 0; i < mHwModules.size(); i++) {
2552 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2553 if (mHwModules[i]->mHandle == 0) {
2554 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2555 continue;
2556 }
2557 // open all output streams needed to access attached devices
2558 // except for direct output streams that are only opened when they are actually
2559 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002560 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002561 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2562 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002563 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002564
Eric Laurent3a4311c2014-03-17 12:00:47 -07002565 if (outProfile->mSupportedDevices.isEmpty()) {
2566 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2567 continue;
2568 }
2569
Eric Laurent83b88082014-06-20 18:31:16 -07002570 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2571 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2572 profileType = mDefaultOutputDevice->mDeviceType;
2573 } else {
2574 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2575 }
2576 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002577 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002578 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002579
Eric Laurent83b88082014-06-20 18:31:16 -07002580 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002581 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2582 config.sample_rate = outputDesc->mSamplingRate;
2583 config.channel_mask = outputDesc->mChannelMask;
2584 config.format = outputDesc->mFormat;
2585 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2586 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2587 &output,
2588 &config,
2589 &outputDesc->mDevice,
2590 String8(""),
2591 &outputDesc->mLatency,
2592 outputDesc->mFlags);
2593
2594 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002595 ALOGW("Cannot open output stream for device %08x on hw module %s",
2596 outputDesc->mDevice,
2597 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002598 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002599 outputDesc->mSamplingRate = config.sample_rate;
2600 outputDesc->mChannelMask = config.channel_mask;
2601 outputDesc->mFormat = config.format;
2602
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002603 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002604 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002605 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002606 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002607 // give a valid ID to an attached device once confirmed it is reachable
2608 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2609 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002610 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002611 }
2612 }
Eric Laurente552edb2014-03-10 17:42:56 -07002613 if (mPrimaryOutput == 0 &&
2614 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2615 mPrimaryOutput = output;
2616 }
2617 addOutput(output, outputDesc);
2618 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002619 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002620 true);
2621 }
2622 }
2623 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002624 // open input streams needed to access attached devices to validate
2625 // mAvailableInputDevices list
2626 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2627 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002628 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002629
Eric Laurent3a4311c2014-03-17 12:00:47 -07002630 if (inProfile->mSupportedDevices.isEmpty()) {
2631 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2632 continue;
2633 }
2634
Eric Laurent83b88082014-06-20 18:31:16 -07002635 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2636 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002637 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002638
2639 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002640 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002641
Eric Laurentcf2c0212014-07-25 16:20:43 -07002642 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2643 config.sample_rate = inputDesc->mSamplingRate;
2644 config.channel_mask = inputDesc->mChannelMask;
2645 config.format = inputDesc->mFormat;
2646 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2647 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2648 &input,
2649 &config,
2650 &inputDesc->mDevice,
2651 String8(""),
2652 AUDIO_SOURCE_MIC,
2653 AUDIO_INPUT_FLAG_NONE);
2654
2655 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002656 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002657 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002658 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002659 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002660 // give a valid ID to an attached device once confirmed it is reachable
2661 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2662 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002663 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002664 }
2665 }
2666 mpClientInterface->closeInput(input);
2667 } else {
2668 ALOGW("Cannot open input stream for device %08x on hw module %s",
2669 inputDesc->mDevice,
2670 mHwModules[i]->mName);
2671 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002672 }
2673 }
2674 }
2675 // make sure all attached devices have been allocated a unique ID
2676 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2677 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002678 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002679 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2680 continue;
2681 }
2682 i++;
2683 }
2684 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2685 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002686 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002687 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2688 continue;
2689 }
2690 i++;
2691 }
2692 // make sure default device is reachable
2693 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002694 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002695 }
Eric Laurente552edb2014-03-10 17:42:56 -07002696
2697 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2698
2699 updateDevicesAndOutputs();
2700
2701#ifdef AUDIO_POLICY_TEST
2702 if (mPrimaryOutput != 0) {
2703 AudioParameter outputCmd = AudioParameter();
2704 outputCmd.addInt(String8("set_id"), 0);
2705 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2706
2707 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2708 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002709 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2710 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002711 mTestLatencyMs = 0;
2712 mCurOutput = 0;
2713 mDirectOutput = false;
2714 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2715 mTestOutputs[i] = 0;
2716 }
2717
2718 const size_t SIZE = 256;
2719 char buffer[SIZE];
2720 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2721 run(buffer, ANDROID_PRIORITY_AUDIO);
2722 }
2723#endif //AUDIO_POLICY_TEST
2724}
2725
Eric Laurente0720872014-03-11 09:30:41 -07002726AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002727{
2728#ifdef AUDIO_POLICY_TEST
2729 exit();
2730#endif //AUDIO_POLICY_TEST
2731 for (size_t i = 0; i < mOutputs.size(); i++) {
2732 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002733 }
2734 for (size_t i = 0; i < mInputs.size(); i++) {
2735 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002736 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002737 mAvailableOutputDevices.clear();
2738 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002739 mOutputs.clear();
2740 mInputs.clear();
2741 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002742}
2743
Eric Laurente0720872014-03-11 09:30:41 -07002744status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002745{
2746 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2747}
2748
2749#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002750bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002751{
2752 ALOGV("entering threadLoop()");
2753 while (!exitPending())
2754 {
2755 String8 command;
2756 int valueInt;
2757 String8 value;
2758
2759 Mutex::Autolock _l(mLock);
2760 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2761
2762 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2763 AudioParameter param = AudioParameter(command);
2764
2765 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2766 valueInt != 0) {
2767 ALOGV("Test command %s received", command.string());
2768 String8 target;
2769 if (param.get(String8("target"), target) != NO_ERROR) {
2770 target = "Manager";
2771 }
2772 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2773 param.remove(String8("test_cmd_policy_output"));
2774 mCurOutput = valueInt;
2775 }
2776 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2777 param.remove(String8("test_cmd_policy_direct"));
2778 if (value == "false") {
2779 mDirectOutput = false;
2780 } else if (value == "true") {
2781 mDirectOutput = true;
2782 }
2783 }
2784 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2785 param.remove(String8("test_cmd_policy_input"));
2786 mTestInput = valueInt;
2787 }
2788
2789 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2790 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002791 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002792 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002793 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002794 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002795 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002796 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002797 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002798 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002799 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002800 if (target == "Manager") {
2801 mTestFormat = format;
2802 } else if (mTestOutputs[mCurOutput] != 0) {
2803 AudioParameter outputParam = AudioParameter();
2804 outputParam.addInt(String8("format"), format);
2805 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2806 }
2807 }
2808 }
2809 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2810 param.remove(String8("test_cmd_policy_channels"));
2811 int channels = 0;
2812
2813 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002814 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002815 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002816 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002817 }
2818 if (channels != 0) {
2819 if (target == "Manager") {
2820 mTestChannels = channels;
2821 } else if (mTestOutputs[mCurOutput] != 0) {
2822 AudioParameter outputParam = AudioParameter();
2823 outputParam.addInt(String8("channels"), channels);
2824 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2825 }
2826 }
2827 }
2828 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2829 param.remove(String8("test_cmd_policy_sampleRate"));
2830 if (valueInt >= 0 && valueInt <= 96000) {
2831 int samplingRate = valueInt;
2832 if (target == "Manager") {
2833 mTestSamplingRate = samplingRate;
2834 } else if (mTestOutputs[mCurOutput] != 0) {
2835 AudioParameter outputParam = AudioParameter();
2836 outputParam.addInt(String8("sampling_rate"), samplingRate);
2837 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2838 }
2839 }
2840 }
2841
2842 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2843 param.remove(String8("test_cmd_policy_reopen"));
2844
Eric Laurent1f2f2232014-06-02 12:01:23 -07002845 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002846 mpClientInterface->closeOutput(mPrimaryOutput);
2847
2848 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2849
Eric Laurente552edb2014-03-10 17:42:56 -07002850 mOutputs.removeItem(mPrimaryOutput);
2851
Eric Laurent1f2f2232014-06-02 12:01:23 -07002852 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002853 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002854 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2855 config.sample_rate = outputDesc->mSamplingRate;
2856 config.channel_mask = outputDesc->mChannelMask;
2857 config.format = outputDesc->mFormat;
2858 status_t status = mpClientInterface->openOutput(moduleHandle,
2859 &mPrimaryOutput,
2860 &config,
2861 &outputDesc->mDevice,
2862 String8(""),
2863 &outputDesc->mLatency,
2864 outputDesc->mFlags);
2865 if (status != NO_ERROR) {
2866 ALOGE("Failed to reopen hardware output stream, "
2867 "samplingRate: %d, format %d, channels %d",
2868 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002869 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002870 outputDesc->mSamplingRate = config.sample_rate;
2871 outputDesc->mChannelMask = config.channel_mask;
2872 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002873 AudioParameter outputCmd = AudioParameter();
2874 outputCmd.addInt(String8("set_id"), 0);
2875 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2876 addOutput(mPrimaryOutput, outputDesc);
2877 }
2878 }
2879
2880
2881 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2882 }
2883 }
2884 return false;
2885}
2886
Eric Laurente0720872014-03-11 09:30:41 -07002887void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002888{
2889 {
2890 AutoMutex _l(mLock);
2891 requestExit();
2892 mWaitWorkCV.signal();
2893 }
2894 requestExitAndWait();
2895}
2896
Eric Laurente0720872014-03-11 09:30:41 -07002897int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002898{
2899 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2900 if (output == mTestOutputs[i]) return i;
2901 }
2902 return 0;
2903}
2904#endif //AUDIO_POLICY_TEST
2905
2906// ---
2907
Eric Laurent1f2f2232014-06-02 12:01:23 -07002908void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002909{
Eric Laurent1c333e22014-05-20 10:48:17 -07002910 outputDesc->mIoHandle = output;
2911 outputDesc->mId = nextUniqueId();
2912 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002913 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002914}
2915
Eric Laurent1f2f2232014-06-02 12:01:23 -07002916void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002917{
Eric Laurent1c333e22014-05-20 10:48:17 -07002918 inputDesc->mIoHandle = input;
2919 inputDesc->mId = nextUniqueId();
2920 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002921 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002922}
Eric Laurente552edb2014-03-10 17:42:56 -07002923
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002924void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2925 const String8 address /*in*/,
2926 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2927 // look for a match on the given address on the addresses of the outputs:
2928 // find the address by finding the patch that maps to this output
2929 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2930 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2931 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2932 if (patchIdx >= 0) {
2933 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2934 const int numSinks = patchDesc->mPatch.num_sinks;
2935 for (ssize_t j=0; j < numSinks; j++) {
2936 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2937 const char* patchAddr =
2938 patchDesc->mPatch.sinks[j].ext.device.address;
2939 if (strncmp(patchAddr,
2940 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2941 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2942 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2943 outputs.add(desc->mIoHandle);
2944 break;
2945 }
2946 }
2947 }
2948 }
2949}
2950
Eric Laurente0720872014-03-11 09:30:41 -07002951status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002952 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002953 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002954 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002955{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002956 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002957
Eric Laurent3b73df72014-03-11 09:06:29 -07002958 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002959 // first list already open outputs that can be routed to this device
2960 for (size_t i = 0; i < mOutputs.size(); i++) {
2961 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002962 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002963 if (!deviceDistinguishesOnAddress(device)) {
2964 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2965 outputs.add(mOutputs.keyAt(i));
2966 } else {
2967 ALOGV(" checking address match due to device 0x%x", device);
2968 findIoHandlesByAddress(desc, address, outputs);
2969 }
Eric Laurente552edb2014-03-10 17:42:56 -07002970 }
2971 }
2972 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002973 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002974 for (size_t i = 0; i < mHwModules.size(); i++)
2975 {
2976 if (mHwModules[i]->mHandle == 0) {
2977 continue;
2978 }
2979 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2980 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002981 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002982 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002983 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2984 }
2985 }
2986 }
2987
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002988 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
2989
Eric Laurente552edb2014-03-10 17:42:56 -07002990 if (profiles.isEmpty() && outputs.isEmpty()) {
2991 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2992 return BAD_VALUE;
2993 }
2994
2995 // open outputs for matching profiles if needed. Direct outputs are also opened to
2996 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2997 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002998 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002999
3000 // nothing to do if one output is already opened for this profile
3001 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003002 for (j = 0; j < outputs.size(); j++) {
3003 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003004 if (!desc->isDuplicated() && desc->mProfile == profile) {
3005 break;
3006 }
3007 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003008 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003009 continue;
3010 }
3011
Eric Laurent83b88082014-06-20 18:31:16 -07003012 ALOGV("opening output for device %08x with params %s profile %p",
3013 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003014 desc = new AudioOutputDescriptor(profile);
3015 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003016 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3017 config.sample_rate = desc->mSamplingRate;
3018 config.channel_mask = desc->mChannelMask;
3019 config.format = desc->mFormat;
3020 config.offload_info.sample_rate = desc->mSamplingRate;
3021 config.offload_info.channel_mask = desc->mChannelMask;
3022 config.offload_info.format = desc->mFormat;
3023 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3024 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3025 &output,
3026 &config,
3027 &desc->mDevice,
3028 address,
3029 &desc->mLatency,
3030 desc->mFlags);
3031 if (status == NO_ERROR) {
3032 desc->mSamplingRate = config.sample_rate;
3033 desc->mChannelMask = config.channel_mask;
3034 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003035
Eric Laurentd4692962014-05-05 18:13:44 -07003036 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003037 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003038 char *param = audio_device_address_to_parameter(device, address);
3039 mpClientInterface->setParameters(output, String8(param));
3040 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003041 }
3042
Eric Laurentd4692962014-05-05 18:13:44 -07003043 // Here is where we step through and resolve any "dynamic" fields
3044 String8 reply;
3045 char *value;
3046 if (profile->mSamplingRates[0] == 0) {
3047 reply = mpClientInterface->getParameters(output,
3048 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003049 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003050 reply.string());
3051 value = strpbrk((char *)reply.string(), "=");
3052 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003053 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003054 }
Eric Laurentd4692962014-05-05 18:13:44 -07003055 }
3056 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3057 reply = mpClientInterface->getParameters(output,
3058 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003059 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003060 reply.string());
3061 value = strpbrk((char *)reply.string(), "=");
3062 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003063 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003064 }
Eric Laurentd4692962014-05-05 18:13:44 -07003065 }
3066 if (profile->mChannelMasks[0] == 0) {
3067 reply = mpClientInterface->getParameters(output,
3068 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003069 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003070 reply.string());
3071 value = strpbrk((char *)reply.string(), "=");
3072 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003073 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003074 }
Eric Laurentd4692962014-05-05 18:13:44 -07003075 }
3076 if (((profile->mSamplingRates[0] == 0) &&
3077 (profile->mSamplingRates.size() < 2)) ||
3078 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3079 (profile->mFormats.size() < 2)) ||
3080 ((profile->mChannelMasks[0] == 0) &&
3081 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003082 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003083 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003084 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003085 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3086 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003087 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003088 config.sample_rate = profile->pickSamplingRate();
3089 config.channel_mask = profile->pickChannelMask();
3090 config.format = profile->pickFormat();
3091 config.offload_info.sample_rate = config.sample_rate;
3092 config.offload_info.channel_mask = config.channel_mask;
3093 config.offload_info.format = config.format;
3094 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3095 &output,
3096 &config,
3097 &desc->mDevice,
3098 address,
3099 &desc->mLatency,
3100 desc->mFlags);
3101 if (status == NO_ERROR) {
3102 desc->mSamplingRate = config.sample_rate;
3103 desc->mChannelMask = config.channel_mask;
3104 desc->mFormat = config.format;
3105 } else {
3106 output = AUDIO_IO_HANDLE_NONE;
3107 }
Eric Laurentd4692962014-05-05 18:13:44 -07003108 }
3109
Eric Laurentcf2c0212014-07-25 16:20:43 -07003110 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003111 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003112 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003113 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003114
Eric Laurentd4692962014-05-05 18:13:44 -07003115 // set initial stream volume for device
3116 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003117
Eric Laurentd4692962014-05-05 18:13:44 -07003118 //TODO: configure audio effect output stage here
3119
3120 // open a duplicating output thread for the new output and the primary output
3121 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3122 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003123 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003124 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003125 sp<AudioOutputDescriptor> dupOutputDesc =
3126 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003127 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3128 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3129 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3130 dupOutputDesc->mFormat = desc->mFormat;
3131 dupOutputDesc->mChannelMask = desc->mChannelMask;
3132 dupOutputDesc->mLatency = desc->mLatency;
3133 addOutput(duplicatedOutput, dupOutputDesc);
3134 applyStreamVolumes(duplicatedOutput, device, 0, true);
3135 } else {
3136 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3137 mPrimaryOutput, output);
3138 mpClientInterface->closeOutput(output);
3139 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003140 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003141 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003142 }
Eric Laurente552edb2014-03-10 17:42:56 -07003143 }
3144 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003145 } else {
3146 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003147 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003148 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003149 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003150 profiles.removeAt(profile_index);
3151 profile_index--;
3152 } else {
3153 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003154 if (deviceDistinguishesOnAddress(device)) {
3155 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3156 device, address.string());
3157 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3158 NULL/*patch handle*/, address.string());
3159 }
Eric Laurente552edb2014-03-10 17:42:56 -07003160 ALOGV("checkOutputsForDevice(): adding output %d", output);
3161 }
3162 }
3163
3164 if (profiles.isEmpty()) {
3165 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3166 return BAD_VALUE;
3167 }
Eric Laurentd4692962014-05-05 18:13:44 -07003168 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003169 // check if one opened output is not needed any more after disconnecting one device
3170 for (size_t i = 0; i < mOutputs.size(); i++) {
3171 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003172 if (!desc->isDuplicated()) {
3173 if (!(desc->mProfile->mSupportedDevices.types()
3174 & mAvailableOutputDevices.types())) {
3175 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3176 mOutputs.keyAt(i));
3177 outputs.add(mOutputs.keyAt(i));
3178 } else if (deviceDistinguishesOnAddress(device) &&
3179 // exact match on device
3180 (desc->mProfile->mSupportedDevices.types() == device)) {
3181 findIoHandlesByAddress(desc, address, outputs);
3182 }
Eric Laurente552edb2014-03-10 17:42:56 -07003183 }
3184 }
Eric Laurentd4692962014-05-05 18:13:44 -07003185 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003186 for (size_t i = 0; i < mHwModules.size(); i++)
3187 {
3188 if (mHwModules[i]->mHandle == 0) {
3189 continue;
3190 }
3191 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3192 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003193 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003194 if (profile->mSupportedDevices.types() & device) {
3195 ALOGV("checkOutputsForDevice(): "
3196 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003197 if (profile->mSamplingRates[0] == 0) {
3198 profile->mSamplingRates.clear();
3199 profile->mSamplingRates.add(0);
3200 }
3201 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3202 profile->mFormats.clear();
3203 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3204 }
3205 if (profile->mChannelMasks[0] == 0) {
3206 profile->mChannelMasks.clear();
3207 profile->mChannelMasks.add(0);
3208 }
3209 }
3210 }
3211 }
3212 }
3213 return NO_ERROR;
3214}
3215
Eric Laurentd4692962014-05-05 18:13:44 -07003216status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3217 audio_policy_dev_state_t state,
3218 SortedVector<audio_io_handle_t>& inputs,
3219 const String8 address)
3220{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003221 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003222 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3223 // first list already open inputs that can be routed to this device
3224 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3225 desc = mInputs.valueAt(input_index);
3226 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3227 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3228 inputs.add(mInputs.keyAt(input_index));
3229 }
3230 }
3231
3232 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003233 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003234 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3235 {
3236 if (mHwModules[module_idx]->mHandle == 0) {
3237 continue;
3238 }
3239 for (size_t profile_index = 0;
3240 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3241 profile_index++)
3242 {
3243 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3244 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003245 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003246 profile_index, module_idx);
3247 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3248 }
3249 }
3250 }
3251
3252 if (profiles.isEmpty() && inputs.isEmpty()) {
3253 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3254 return BAD_VALUE;
3255 }
3256
3257 // open inputs for matching profiles if needed. Direct inputs are also opened to
3258 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3259 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3260
Eric Laurent1c333e22014-05-20 10:48:17 -07003261 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003262 // nothing to do if one input is already opened for this profile
3263 size_t input_index;
3264 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3265 desc = mInputs.valueAt(input_index);
3266 if (desc->mProfile == profile) {
3267 break;
3268 }
3269 }
3270 if (input_index != mInputs.size()) {
3271 continue;
3272 }
3273
3274 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3275 desc = new AudioInputDescriptor(profile);
3276 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003277 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3278 config.sample_rate = desc->mSamplingRate;
3279 config.channel_mask = desc->mChannelMask;
3280 config.format = desc->mFormat;
3281 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3282 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3283 &input,
3284 &config,
3285 &desc->mDevice,
3286 address,
3287 AUDIO_SOURCE_MIC,
3288 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003289
Eric Laurentcf2c0212014-07-25 16:20:43 -07003290 if (status == NO_ERROR) {
3291 desc->mSamplingRate = config.sample_rate;
3292 desc->mChannelMask = config.channel_mask;
3293 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003294
Eric Laurentd4692962014-05-05 18:13:44 -07003295 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003296 char *param = audio_device_address_to_parameter(device, address);
3297 mpClientInterface->setParameters(input, String8(param));
3298 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003299 }
3300
3301 // Here is where we step through and resolve any "dynamic" fields
3302 String8 reply;
3303 char *value;
3304 if (profile->mSamplingRates[0] == 0) {
3305 reply = mpClientInterface->getParameters(input,
3306 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3307 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3308 reply.string());
3309 value = strpbrk((char *)reply.string(), "=");
3310 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003311 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003312 }
3313 }
3314 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3315 reply = mpClientInterface->getParameters(input,
3316 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3317 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3318 value = strpbrk((char *)reply.string(), "=");
3319 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003320 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003321 }
3322 }
3323 if (profile->mChannelMasks[0] == 0) {
3324 reply = mpClientInterface->getParameters(input,
3325 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3326 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3327 reply.string());
3328 value = strpbrk((char *)reply.string(), "=");
3329 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003330 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003331 }
3332 }
3333 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3334 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3335 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3336 ALOGW("checkInputsForDevice() direct input missing param");
3337 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003338 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003339 }
3340
3341 if (input != 0) {
3342 addInput(input, desc);
3343 }
3344 } // endif input != 0
3345
Eric Laurentcf2c0212014-07-25 16:20:43 -07003346 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003347 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003348 profiles.removeAt(profile_index);
3349 profile_index--;
3350 } else {
3351 inputs.add(input);
3352 ALOGV("checkInputsForDevice(): adding input %d", input);
3353 }
3354 } // end scan profiles
3355
3356 if (profiles.isEmpty()) {
3357 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3358 return BAD_VALUE;
3359 }
3360 } else {
3361 // Disconnect
3362 // check if one opened input is not needed any more after disconnecting one device
3363 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3364 desc = mInputs.valueAt(input_index);
3365 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3366 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3367 mInputs.keyAt(input_index));
3368 inputs.add(mInputs.keyAt(input_index));
3369 }
3370 }
3371 // Clear any profiles associated with the disconnected device.
3372 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3373 if (mHwModules[module_index]->mHandle == 0) {
3374 continue;
3375 }
3376 for (size_t profile_index = 0;
3377 profile_index < mHwModules[module_index]->mInputProfiles.size();
3378 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003379 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003380 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003381 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003382 profile_index, module_index);
3383 if (profile->mSamplingRates[0] == 0) {
3384 profile->mSamplingRates.clear();
3385 profile->mSamplingRates.add(0);
3386 }
3387 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3388 profile->mFormats.clear();
3389 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3390 }
3391 if (profile->mChannelMasks[0] == 0) {
3392 profile->mChannelMasks.clear();
3393 profile->mChannelMasks.add(0);
3394 }
3395 }
3396 }
3397 }
3398 } // end disconnect
3399
3400 return NO_ERROR;
3401}
3402
3403
Eric Laurente0720872014-03-11 09:30:41 -07003404void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003405{
3406 ALOGV("closeOutput(%d)", output);
3407
Eric Laurent1f2f2232014-06-02 12:01:23 -07003408 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003409 if (outputDesc == NULL) {
3410 ALOGW("closeOutput() unknown output %d", output);
3411 return;
3412 }
3413
3414 // look for duplicated outputs connected to the output being removed.
3415 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003416 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003417 if (dupOutputDesc->isDuplicated() &&
3418 (dupOutputDesc->mOutput1 == outputDesc ||
3419 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003420 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003421 if (dupOutputDesc->mOutput1 == outputDesc) {
3422 outputDesc2 = dupOutputDesc->mOutput2;
3423 } else {
3424 outputDesc2 = dupOutputDesc->mOutput1;
3425 }
3426 // As all active tracks on duplicated output will be deleted,
3427 // and as they were also referenced on the other output, the reference
3428 // count for their stream type must be adjusted accordingly on
3429 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003430 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003431 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003432 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003433 }
3434 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3435 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3436
3437 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003438 mOutputs.removeItem(duplicatedOutput);
3439 }
3440 }
3441
3442 AudioParameter param;
3443 param.add(String8("closing"), String8("true"));
3444 mpClientInterface->setParameters(output, param.toString());
3445
3446 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003447 mOutputs.removeItem(output);
3448 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003449 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003450}
3451
Eric Laurente0720872014-03-11 09:30:41 -07003452SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003453 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003454{
3455 SortedVector<audio_io_handle_t> outputs;
3456
3457 ALOGVV("getOutputsForDevice() device %04x", device);
3458 for (size_t i = 0; i < openOutputs.size(); i++) {
3459 ALOGVV("output %d isDuplicated=%d device=%04x",
3460 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3461 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3462 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3463 outputs.add(openOutputs.keyAt(i));
3464 }
3465 }
3466 return outputs;
3467}
3468
Eric Laurente0720872014-03-11 09:30:41 -07003469bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003470 SortedVector<audio_io_handle_t>& outputs2)
3471{
3472 if (outputs1.size() != outputs2.size()) {
3473 return false;
3474 }
3475 for (size_t i = 0; i < outputs1.size(); i++) {
3476 if (outputs1[i] != outputs2[i]) {
3477 return false;
3478 }
3479 }
3480 return true;
3481}
3482
Eric Laurente0720872014-03-11 09:30:41 -07003483void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003484{
3485 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3486 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3487 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3488 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3489
3490 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3491 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3492 strategy, srcOutputs[0], dstOutputs[0]);
3493 // mute strategy while moving tracks from one output to another
3494 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003495 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003496 if (desc->isStrategyActive(strategy)) {
3497 setStrategyMute(strategy, true, srcOutputs[i]);
3498 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3499 }
3500 }
3501
3502 // Move effects associated to this strategy from previous output to new output
3503 if (strategy == STRATEGY_MEDIA) {
3504 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3505 SortedVector<audio_io_handle_t> moved;
3506 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003507 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3508 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3509 effectDesc->mIo != fxOutput) {
3510 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003511 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3512 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003513 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003514 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003515 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003516 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003517 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003518 }
3519 }
3520 }
3521 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003522 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3523 if (getStrategy((audio_stream_type_t)i) == strategy) {
3524 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003525 }
3526 }
3527 }
3528}
3529
Eric Laurente0720872014-03-11 09:30:41 -07003530void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003531{
3532 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3533 checkOutputForStrategy(STRATEGY_PHONE);
3534 checkOutputForStrategy(STRATEGY_SONIFICATION);
3535 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3536 checkOutputForStrategy(STRATEGY_MEDIA);
3537 checkOutputForStrategy(STRATEGY_DTMF);
3538}
3539
Eric Laurente0720872014-03-11 09:30:41 -07003540audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003541{
Eric Laurente552edb2014-03-10 17:42:56 -07003542 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003543 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003544 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3545 return mOutputs.keyAt(i);
3546 }
3547 }
3548
3549 return 0;
3550}
3551
Eric Laurente0720872014-03-11 09:30:41 -07003552void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003553{
Eric Laurente552edb2014-03-10 17:42:56 -07003554 audio_io_handle_t a2dpOutput = getA2dpOutput();
3555 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003556 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003557 return;
3558 }
3559
Eric Laurent3a4311c2014-03-17 12:00:47 -07003560 bool isScoConnected =
3561 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003562 // suspend A2DP output if:
3563 // (NOT already suspended) &&
3564 // ((SCO device is connected &&
3565 // (forced usage for communication || for record is SCO))) ||
3566 // (phone state is ringing || in call)
3567 //
3568 // restore A2DP output if:
3569 // (Already suspended) &&
3570 // ((SCO device is NOT connected ||
3571 // (forced usage NOT for communication && NOT for record is SCO))) &&
3572 // (phone state is NOT ringing && NOT in call)
3573 //
3574 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003575 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003576 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3577 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3578 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3579 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003580
3581 mpClientInterface->restoreOutput(a2dpOutput);
3582 mA2dpSuspended = false;
3583 }
3584 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003585 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003586 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3587 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3588 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3589 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003590
3591 mpClientInterface->suspendOutput(a2dpOutput);
3592 mA2dpSuspended = true;
3593 }
3594 }
3595}
3596
Eric Laurent1c333e22014-05-20 10:48:17 -07003597audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003598{
3599 audio_devices_t device = AUDIO_DEVICE_NONE;
3600
Eric Laurent1f2f2232014-06-02 12:01:23 -07003601 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003602
3603 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3604 if (index >= 0) {
3605 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3606 if (patchDesc->mUid != mUidCached) {
3607 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3608 outputDesc->device(), outputDesc->mPatchHandle);
3609 return outputDesc->device();
3610 }
3611 }
3612
Eric Laurente552edb2014-03-10 17:42:56 -07003613 // check the following by order of priority to request a routing change if necessary:
3614 // 1: the strategy enforced audible is active on the output:
3615 // use device for strategy enforced audible
3616 // 2: we are in call or the strategy phone is active on the output:
3617 // use device for strategy phone
3618 // 3: the strategy sonification is active on the output:
3619 // use device for strategy sonification
3620 // 4: the strategy "respectful" sonification is active on the output:
3621 // use device for strategy "respectful" sonification
3622 // 5: the strategy media is active on the output:
3623 // use device for strategy media
3624 // 6: the strategy DTMF is active on the output:
3625 // use device for strategy DTMF
3626 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3627 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3628 } else if (isInCall() ||
3629 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3630 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3631 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3632 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3633 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3634 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3635 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3636 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3637 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3638 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3639 }
3640
Eric Laurent1c333e22014-05-20 10:48:17 -07003641 ALOGV("getNewOutputDevice() selected device %x", device);
3642 return device;
3643}
3644
3645audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3646{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003647 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003648
3649 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3650 if (index >= 0) {
3651 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3652 if (patchDesc->mUid != mUidCached) {
3653 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3654 inputDesc->mDevice, inputDesc->mPatchHandle);
3655 return inputDesc->mDevice;
3656 }
3657 }
3658
Eric Laurent1c333e22014-05-20 10:48:17 -07003659 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3660
3661 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003662 return device;
3663}
3664
Eric Laurente0720872014-03-11 09:30:41 -07003665uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003666 return (uint32_t)getStrategy(stream);
3667}
3668
Eric Laurente0720872014-03-11 09:30:41 -07003669audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003670 // By checking the range of stream before calling getStrategy, we avoid
3671 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3672 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003673 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003674 return AUDIO_DEVICE_NONE;
3675 }
3676 audio_devices_t devices;
3677 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3678 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3679 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3680 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003681 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003682 if (outputDesc->isStrategyActive(strategy)) {
3683 devices = outputDesc->device();
3684 break;
3685 }
Eric Laurente552edb2014-03-10 17:42:56 -07003686 }
3687 return devices;
3688}
3689
Eric Laurente0720872014-03-11 09:30:41 -07003690AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003691 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003692 // stream to strategy mapping
3693 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003694 case AUDIO_STREAM_VOICE_CALL:
3695 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003696 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003697 case AUDIO_STREAM_RING:
3698 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003699 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003700 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003701 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003702 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003703 return STRATEGY_DTMF;
3704 default:
3705 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003706 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003707 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3708 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003709 case AUDIO_STREAM_TTS:
3710 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003711 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003712 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003713 return STRATEGY_ENFORCED_AUDIBLE;
3714 }
3715}
3716
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003717uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3718 // flags to strategy mapping
3719 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3720 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3721 }
3722
3723 // usage to strategy mapping
3724 switch (attr->usage) {
3725 case AUDIO_USAGE_MEDIA:
3726 case AUDIO_USAGE_GAME:
3727 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3728 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3729 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3730 return (uint32_t) STRATEGY_MEDIA;
3731
3732 case AUDIO_USAGE_VOICE_COMMUNICATION:
3733 return (uint32_t) STRATEGY_PHONE;
3734
3735 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3736 return (uint32_t) STRATEGY_DTMF;
3737
3738 case AUDIO_USAGE_ALARM:
3739 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3740 return (uint32_t) STRATEGY_SONIFICATION;
3741
3742 case AUDIO_USAGE_NOTIFICATION:
3743 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3744 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3745 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3746 case AUDIO_USAGE_NOTIFICATION_EVENT:
3747 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3748
3749 case AUDIO_USAGE_UNKNOWN:
3750 default:
3751 return (uint32_t) STRATEGY_MEDIA;
3752 }
3753}
3754
Eric Laurente0720872014-03-11 09:30:41 -07003755void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003756 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003757 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003758 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3759 updateDevicesAndOutputs();
3760 break;
3761 default:
3762 break;
3763 }
3764}
3765
Eric Laurente0720872014-03-11 09:30:41 -07003766audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003767 bool fromCache)
3768{
3769 uint32_t device = AUDIO_DEVICE_NONE;
3770
3771 if (fromCache) {
3772 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3773 strategy, mDeviceForStrategy[strategy]);
3774 return mDeviceForStrategy[strategy];
3775 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003776 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003777 switch (strategy) {
3778
3779 case STRATEGY_SONIFICATION_RESPECTFUL:
3780 if (isInCall()) {
3781 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003782 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003783 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3784 // while media is playing on a remote device, use the the sonification behavior.
3785 // Note that we test this usecase before testing if media is playing because
3786 // the isStreamActive() method only informs about the activity of a stream, not
3787 // if it's for local playback. Note also that we use the same delay between both tests
3788 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003789 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003790 // while media is playing (or has recently played), use the same device
3791 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3792 } else {
3793 // when media is not playing anymore, fall back on the sonification behavior
3794 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3795 }
3796
3797 break;
3798
3799 case STRATEGY_DTMF:
3800 if (!isInCall()) {
3801 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3802 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3803 break;
3804 }
3805 // when in call, DTMF and PHONE strategies follow the same rules
3806 // FALL THROUGH
3807
3808 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07003809 // Force use of only devices on primary output if:
3810 // - in call AND
3811 // - cannot route from voice call RX OR
3812 // - audio HAL version is < 3.0 and TX device is on the primary HW module
3813 if (mPhoneState == AUDIO_MODE_IN_CALL) {
3814 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
3815 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
3816 if (((mAvailableInputDevices.types() &
3817 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
3818 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
3819 (hwOutputDesc->mAudioPort->mModule->mHalVersion <
3820 AUDIO_DEVICE_API_VERSION_3_0))) {
3821 availableOutputDeviceTypes = availablePrimaryOutputDevices();
3822 }
3823 }
Eric Laurente552edb2014-03-10 17:42:56 -07003824 // for phone strategy, we first consider the forced use and then the available devices by order
3825 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003826 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3827 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003828 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003829 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003830 if (device) break;
3831 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003832 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003833 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003834 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003835 if (device) break;
3836 // if SCO device is requested but no SCO device is available, fall back to default case
3837 // FALL THROUGH
3838
3839 default: // FORCE_NONE
3840 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003841 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003842 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003843 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003844 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003845 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003846 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003847 if (device) break;
3848 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003849 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003850 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003851 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003852 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07003853 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
3854 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003855 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003856 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003857 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003858 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003859 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003860 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003861 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003862 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003863 if (device) break;
3864 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003865 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003866 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003867 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003868 if (device == AUDIO_DEVICE_NONE) {
3869 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3870 }
3871 break;
3872
Eric Laurent3b73df72014-03-11 09:06:29 -07003873 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003874 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3875 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003876 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003877 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003878 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003879 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003880 if (device) break;
3881 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003882 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003883 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003884 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003885 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003886 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003887 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003888 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003889 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003890 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003891 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003892 if (device) break;
3893 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003894 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3895 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003896 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003897 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003898 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003899 if (device == AUDIO_DEVICE_NONE) {
3900 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3901 }
3902 break;
3903 }
3904 break;
3905
3906 case STRATEGY_SONIFICATION:
3907
3908 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3909 // handleIncallSonification().
3910 if (isInCall()) {
3911 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3912 break;
3913 }
3914 // FALL THROUGH
3915
3916 case STRATEGY_ENFORCED_AUDIBLE:
3917 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3918 // except:
3919 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3920 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3921
3922 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003923 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003924 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003925 if (device == AUDIO_DEVICE_NONE) {
3926 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3927 }
3928 }
3929 // The second device used for sonification is the same as the device used by media strategy
3930 // FALL THROUGH
3931
3932 case STRATEGY_MEDIA: {
3933 uint32_t device2 = AUDIO_DEVICE_NONE;
3934 if (strategy != STRATEGY_SONIFICATION) {
3935 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003936 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003937 }
3938 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003939 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003940 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003941 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003942 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003943 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003944 }
3945 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003946 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003947 }
3948 }
3949 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003950 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003951 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003952 if ((device2 == AUDIO_DEVICE_NONE)) {
3953 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3954 }
Eric Laurente552edb2014-03-10 17:42:56 -07003955 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003956 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003957 }
3958 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003959 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003960 }
3961 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003962 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003963 }
3964 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003965 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003966 }
3967 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3968 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003969 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003970 }
3971 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003972 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003973 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003974 }
3975 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003976 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003977 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003978 int device3 = AUDIO_DEVICE_NONE;
3979 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003980 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09003981 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3982 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003983 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003984 }
Eric Laurente552edb2014-03-10 17:42:56 -07003985
Jungshik Jang839e4f32014-06-26 17:23:40 +09003986 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003987 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3988 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3989 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003990
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003991 // If hdmi system audio mode is on, remove speaker out of output list.
3992 if ((strategy == STRATEGY_MEDIA) &&
3993 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3994 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3995 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3996 }
3997
Eric Laurente552edb2014-03-10 17:42:56 -07003998 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003999 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004000 if (device == AUDIO_DEVICE_NONE) {
4001 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4002 }
4003 } break;
4004
4005 default:
4006 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4007 break;
4008 }
4009
4010 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4011 return device;
4012}
4013
Eric Laurente0720872014-03-11 09:30:41 -07004014void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004015{
4016 for (int i = 0; i < NUM_STRATEGIES; i++) {
4017 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4018 }
4019 mPreviousOutputs = mOutputs;
4020}
4021
Eric Laurent1f2f2232014-06-02 12:01:23 -07004022uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004023 audio_devices_t prevDevice,
4024 uint32_t delayMs)
4025{
4026 // mute/unmute strategies using an incompatible device combination
4027 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4028 // if unmuting, unmute only after the specified delay
4029 if (outputDesc->isDuplicated()) {
4030 return 0;
4031 }
4032
4033 uint32_t muteWaitMs = 0;
4034 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004035 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004036
4037 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4038 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4039 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4040 bool doMute = false;
4041
4042 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4043 doMute = true;
4044 outputDesc->mStrategyMutedByDevice[i] = true;
4045 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4046 doMute = true;
4047 outputDesc->mStrategyMutedByDevice[i] = false;
4048 }
Eric Laurent99401132014-05-07 19:48:15 -07004049 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004050 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004051 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004052 // skip output if it does not share any device with current output
4053 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4054 == AUDIO_DEVICE_NONE) {
4055 continue;
4056 }
4057 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4058 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4059 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4060 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4061 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004062 if (mute) {
4063 // FIXME: should not need to double latency if volume could be applied
4064 // immediately by the audioflinger mixer. We must account for the delay
4065 // between now and the next time the audioflinger thread for this output
4066 // will process a buffer (which corresponds to one buffer size,
4067 // usually 1/2 or 1/4 of the latency).
4068 if (muteWaitMs < desc->latency() * 2) {
4069 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004070 }
4071 }
4072 }
4073 }
4074 }
4075 }
4076
Eric Laurent99401132014-05-07 19:48:15 -07004077 // temporary mute output if device selection changes to avoid volume bursts due to
4078 // different per device volumes
4079 if (outputDesc->isActive() && (device != prevDevice)) {
4080 if (muteWaitMs < outputDesc->latency() * 2) {
4081 muteWaitMs = outputDesc->latency() * 2;
4082 }
4083 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4084 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004085 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004086 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004087 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004088 muteWaitMs *2, device);
4089 }
4090 }
4091 }
4092
Eric Laurente552edb2014-03-10 17:42:56 -07004093 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4094 if (muteWaitMs > delayMs) {
4095 muteWaitMs -= delayMs;
4096 usleep(muteWaitMs * 1000);
4097 return muteWaitMs;
4098 }
4099 return 0;
4100}
4101
Eric Laurente0720872014-03-11 09:30:41 -07004102uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004103 audio_devices_t device,
4104 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004105 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004106 audio_patch_handle_t *patchHandle,
4107 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004108{
4109 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004110 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004111 AudioParameter param;
4112 uint32_t muteWaitMs;
4113
4114 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004115 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4116 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004117 return muteWaitMs;
4118 }
4119 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4120 // output profile
4121 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004122 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004123 return 0;
4124 }
4125
4126 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004127 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004128
4129 audio_devices_t prevDevice = outputDesc->mDevice;
4130
4131 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4132
4133 if (device != AUDIO_DEVICE_NONE) {
4134 outputDesc->mDevice = device;
4135 }
4136 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4137
4138 // Do not change the routing if:
4139 // - the requested device is AUDIO_DEVICE_NONE
4140 // - the requested device is the same as current device and force is not specified.
4141 // Doing this check here allows the caller to call setOutputDevice() without conditions
4142 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4143 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4144 return muteWaitMs;
4145 }
4146
4147 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004148
Eric Laurente552edb2014-03-10 17:42:56 -07004149 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004150 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004151 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004152 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004153 DeviceVector deviceList = (address == NULL) ?
4154 mAvailableOutputDevices.getDevicesFromType(device)
4155 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004156 if (!deviceList.isEmpty()) {
4157 struct audio_patch patch;
4158 outputDesc->toAudioPortConfig(&patch.sources[0]);
4159 patch.num_sources = 1;
4160 patch.num_sinks = 0;
4161 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4162 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004163 patch.num_sinks++;
4164 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004165 ssize_t index;
4166 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4167 index = mAudioPatches.indexOfKey(*patchHandle);
4168 } else {
4169 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4170 }
4171 sp< AudioPatch> patchDesc;
4172 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4173 if (index >= 0) {
4174 patchDesc = mAudioPatches.valueAt(index);
4175 afPatchHandle = patchDesc->mAfPatchHandle;
4176 }
4177
Eric Laurent1c333e22014-05-20 10:48:17 -07004178 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004179 &afPatchHandle,
4180 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004181 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4182 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004183 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004184 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004185 if (index < 0) {
4186 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4187 &patch, mUidCached);
4188 addAudioPatch(patchDesc->mHandle, patchDesc);
4189 } else {
4190 patchDesc->mPatch = patch;
4191 }
4192 patchDesc->mAfPatchHandle = afPatchHandle;
4193 patchDesc->mUid = mUidCached;
4194 if (patchHandle) {
4195 *patchHandle = patchDesc->mHandle;
4196 }
4197 outputDesc->mPatchHandle = patchDesc->mHandle;
4198 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004199 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004200 }
4201 }
4202 }
Eric Laurente552edb2014-03-10 17:42:56 -07004203
4204 // update stream volumes according to new device
4205 applyStreamVolumes(output, device, delayMs);
4206
4207 return muteWaitMs;
4208}
4209
Eric Laurent1c333e22014-05-20 10:48:17 -07004210status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004211 int delayMs,
4212 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004213{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004214 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004215 ssize_t index;
4216 if (patchHandle) {
4217 index = mAudioPatches.indexOfKey(*patchHandle);
4218 } else {
4219 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4220 }
4221 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004222 return INVALID_OPERATION;
4223 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004224 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4225 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004226 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4227 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004228 removeAudioPatch(patchDesc->mHandle);
4229 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004230 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004231 return status;
4232}
4233
4234status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4235 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004236 bool force,
4237 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004238{
4239 status_t status = NO_ERROR;
4240
Eric Laurent1f2f2232014-06-02 12:01:23 -07004241 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004242 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4243 inputDesc->mDevice = device;
4244
4245 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4246 if (!deviceList.isEmpty()) {
4247 struct audio_patch patch;
4248 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004249 // AUDIO_SOURCE_HOTWORD is for internal use only:
4250 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004251 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4252 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004253 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4254 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004255 patch.num_sinks = 1;
4256 //only one input device for now
4257 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004258 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004259 ssize_t index;
4260 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4261 index = mAudioPatches.indexOfKey(*patchHandle);
4262 } else {
4263 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4264 }
4265 sp< AudioPatch> patchDesc;
4266 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4267 if (index >= 0) {
4268 patchDesc = mAudioPatches.valueAt(index);
4269 afPatchHandle = patchDesc->mAfPatchHandle;
4270 }
4271
Eric Laurent1c333e22014-05-20 10:48:17 -07004272 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004273 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004274 0);
4275 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004276 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004277 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004278 if (index < 0) {
4279 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4280 &patch, mUidCached);
4281 addAudioPatch(patchDesc->mHandle, patchDesc);
4282 } else {
4283 patchDesc->mPatch = patch;
4284 }
4285 patchDesc->mAfPatchHandle = afPatchHandle;
4286 patchDesc->mUid = mUidCached;
4287 if (patchHandle) {
4288 *patchHandle = patchDesc->mHandle;
4289 }
4290 inputDesc->mPatchHandle = patchDesc->mHandle;
4291 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004292 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004293 }
4294 }
4295 }
4296 return status;
4297}
4298
Eric Laurent6a94d692014-05-20 11:18:06 -07004299status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4300 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004301{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004302 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004303 ssize_t index;
4304 if (patchHandle) {
4305 index = mAudioPatches.indexOfKey(*patchHandle);
4306 } else {
4307 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4308 }
4309 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004310 return INVALID_OPERATION;
4311 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004312 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4313 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004314 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4315 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004316 removeAudioPatch(patchDesc->mHandle);
4317 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004318 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004319 return status;
4320}
4321
4322sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004323 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004324 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004325 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004326 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004327{
4328 // Choose an input profile based on the requested capture parameters: select the first available
4329 // profile supporting all requested parameters.
4330
4331 for (size_t i = 0; i < mHwModules.size(); i++)
4332 {
4333 if (mHwModules[i]->mHandle == 0) {
4334 continue;
4335 }
4336 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4337 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004338 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004339 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004340 if (profile->isCompatibleProfile(device, samplingRate,
4341 &samplingRate /*updatedSamplingRate*/,
4342 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004343 return profile;
4344 }
4345 }
4346 }
4347 return NULL;
4348}
4349
Eric Laurente0720872014-03-11 09:30:41 -07004350audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004351{
4352 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004353 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4354 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004355 switch (inputSource) {
4356 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004357 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004358 device = AUDIO_DEVICE_IN_VOICE_CALL;
4359 break;
4360 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004361 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004362
4363 case AUDIO_SOURCE_DEFAULT:
4364 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004365 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4366 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004367 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4368 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4369 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4370 device = AUDIO_DEVICE_IN_USB_DEVICE;
4371 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4372 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004373 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004374 break;
4375
4376 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4377 // Allow only use of devices on primary input if in call and HAL does not support routing
4378 // to voice call path.
4379 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4380 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4381 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4382 }
4383
4384 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4385 case AUDIO_POLICY_FORCE_BT_SCO:
4386 // if SCO device is requested but no SCO device is available, fall back to default case
4387 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4388 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4389 break;
4390 }
4391 // FALL THROUGH
4392
4393 default: // FORCE_NONE
4394 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4395 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4396 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4397 device = AUDIO_DEVICE_IN_USB_DEVICE;
4398 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4399 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4400 }
4401 break;
4402
4403 case AUDIO_POLICY_FORCE_SPEAKER:
4404 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4405 device = AUDIO_DEVICE_IN_BACK_MIC;
4406 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4407 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4408 }
4409 break;
4410 }
4411 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004412
Eric Laurente552edb2014-03-10 17:42:56 -07004413 case AUDIO_SOURCE_VOICE_RECOGNITION:
4414 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004415 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004416 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004417 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004418 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004419 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004420 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4421 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004422 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004423 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4424 }
4425 break;
4426 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004427 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004428 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004429 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004430 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4431 }
4432 break;
4433 case AUDIO_SOURCE_VOICE_DOWNLINK:
4434 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004435 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004436 device = AUDIO_DEVICE_IN_VOICE_CALL;
4437 }
4438 break;
4439 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004440 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004441 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4442 }
4443 break;
4444 default:
4445 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4446 break;
4447 }
4448 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4449 return device;
4450}
4451
Eric Laurente0720872014-03-11 09:30:41 -07004452bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004453{
4454 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4455 device &= ~AUDIO_DEVICE_BIT_IN;
4456 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4457 return true;
4458 }
4459 return false;
4460}
4461
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004462bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4463 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4464}
4465
Eric Laurente0720872014-03-11 09:30:41 -07004466audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004467{
4468 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004469 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004470 if ((input_descriptor->mRefCount > 0)
4471 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4472 return mInputs.keyAt(i);
4473 }
4474 }
4475 return 0;
4476}
4477
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004478uint32_t AudioPolicyManager::activeInputsCount() const
4479{
4480 uint32_t count = 0;
4481 for (size_t i = 0; i < mInputs.size(); i++) {
4482 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4483 if (desc->mRefCount > 0) {
4484 return count++;
4485 }
4486 }
4487 return count;
4488}
4489
Eric Laurente552edb2014-03-10 17:42:56 -07004490
Eric Laurente0720872014-03-11 09:30:41 -07004491audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004492{
4493 if (device == AUDIO_DEVICE_NONE) {
4494 // this happens when forcing a route update and no track is active on an output.
4495 // In this case the returned category is not important.
4496 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004497 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004498 // Multiple device selection is either:
4499 // - speaker + one other device: give priority to speaker in this case.
4500 // - one A2DP device + another device: happens with duplicated output. In this case
4501 // retain the device on the A2DP output as the other must not correspond to an active
4502 // selection if not the speaker.
4503 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4504 device = AUDIO_DEVICE_OUT_SPEAKER;
4505 } else {
4506 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4507 }
4508 }
4509
Eric Laurent3b73df72014-03-11 09:06:29 -07004510 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004511 "getDeviceForVolume() invalid device combination: %08x",
4512 device);
4513
4514 return device;
4515}
4516
Eric Laurente0720872014-03-11 09:30:41 -07004517AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004518{
4519 switch(getDeviceForVolume(device)) {
4520 case AUDIO_DEVICE_OUT_EARPIECE:
4521 return DEVICE_CATEGORY_EARPIECE;
4522 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4523 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4524 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4525 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4526 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4527 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4528 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004529 case AUDIO_DEVICE_OUT_LINE:
4530 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4531 /*USB? Remote submix?*/
4532 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004533 case AUDIO_DEVICE_OUT_SPEAKER:
4534 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4535 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004536 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4537 case AUDIO_DEVICE_OUT_USB_DEVICE:
4538 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4539 default:
4540 return DEVICE_CATEGORY_SPEAKER;
4541 }
4542}
4543
Eric Laurente0720872014-03-11 09:30:41 -07004544float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004545 int indexInUi)
4546{
4547 device_category deviceCategory = getDeviceCategory(device);
4548 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4549
4550 // the volume index in the UI is relative to the min and max volume indices for this stream type
4551 int nbSteps = 1 + curve[VOLMAX].mIndex -
4552 curve[VOLMIN].mIndex;
4553 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4554 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4555
4556 // find what part of the curve this index volume belongs to, or if it's out of bounds
4557 int segment = 0;
4558 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4559 return 0.0f;
4560 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4561 segment = 0;
4562 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4563 segment = 1;
4564 } else if (volIdx <= curve[VOLMAX].mIndex) {
4565 segment = 2;
4566 } else { // out of bounds
4567 return 1.0f;
4568 }
4569
4570 // linear interpolation in the attenuation table in dB
4571 float decibels = curve[segment].mDBAttenuation +
4572 ((float)(volIdx - curve[segment].mIndex)) *
4573 ( (curve[segment+1].mDBAttenuation -
4574 curve[segment].mDBAttenuation) /
4575 ((float)(curve[segment+1].mIndex -
4576 curve[segment].mIndex)) );
4577
4578 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4579
4580 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4581 curve[segment].mIndex, volIdx,
4582 curve[segment+1].mIndex,
4583 curve[segment].mDBAttenuation,
4584 decibels,
4585 curve[segment+1].mDBAttenuation,
4586 amplification);
4587
4588 return amplification;
4589}
4590
Eric Laurente0720872014-03-11 09:30:41 -07004591const AudioPolicyManager::VolumeCurvePoint
4592 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004593 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4594};
4595
Eric Laurente0720872014-03-11 09:30:41 -07004596const AudioPolicyManager::VolumeCurvePoint
4597 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004598 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4599};
4600
Eric Laurente0720872014-03-11 09:30:41 -07004601const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004602 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4603 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4604};
4605
4606const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004607 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004608 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4609};
4610
Eric Laurente0720872014-03-11 09:30:41 -07004611const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004612 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004613 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004614};
4615
4616const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004617 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004618 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4619};
4620
Eric Laurente0720872014-03-11 09:30:41 -07004621const AudioPolicyManager::VolumeCurvePoint
4622 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004623 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4624};
4625
4626// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4627// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4628// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4629// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4630
Eric Laurente0720872014-03-11 09:30:41 -07004631const AudioPolicyManager::VolumeCurvePoint
4632 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004633 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4634};
4635
Eric Laurente0720872014-03-11 09:30:41 -07004636const AudioPolicyManager::VolumeCurvePoint
4637 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004638 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4639};
4640
Eric Laurente0720872014-03-11 09:30:41 -07004641const AudioPolicyManager::VolumeCurvePoint
4642 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004643 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4644};
4645
Eric Laurente0720872014-03-11 09:30:41 -07004646const AudioPolicyManager::VolumeCurvePoint
4647 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004648 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4649};
4650
Eric Laurente0720872014-03-11 09:30:41 -07004651const AudioPolicyManager::VolumeCurvePoint
4652 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004653 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4654};
4655
Eric Laurente0720872014-03-11 09:30:41 -07004656const AudioPolicyManager::VolumeCurvePoint
4657 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4658 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004659 { // AUDIO_STREAM_VOICE_CALL
4660 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4661 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004662 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4663 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004664 },
4665 { // AUDIO_STREAM_SYSTEM
4666 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4667 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004668 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4669 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004670 },
4671 { // AUDIO_STREAM_RING
4672 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4673 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004674 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4675 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004676 },
4677 { // AUDIO_STREAM_MUSIC
4678 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4679 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004680 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4681 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004682 },
4683 { // AUDIO_STREAM_ALARM
4684 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4685 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004686 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4687 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004688 },
4689 { // AUDIO_STREAM_NOTIFICATION
4690 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4691 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004692 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4693 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004694 },
4695 { // AUDIO_STREAM_BLUETOOTH_SCO
4696 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4697 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004698 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4699 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004700 },
4701 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4702 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4703 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004704 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4705 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004706 },
4707 { // AUDIO_STREAM_DTMF
4708 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4709 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004710 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4711 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004712 },
4713 { // AUDIO_STREAM_TTS
4714 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4715 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004716 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4717 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004718 },
4719};
4720
Eric Laurente0720872014-03-11 09:30:41 -07004721void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004722{
4723 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4724 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4725 mStreams[i].mVolumeCurve[j] =
4726 sVolumeProfiles[i][j];
4727 }
4728 }
4729
4730 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4731 if (mSpeakerDrcEnabled) {
4732 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4733 sDefaultSystemVolumeCurveDrc;
4734 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4735 sSpeakerSonificationVolumeCurveDrc;
4736 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4737 sSpeakerSonificationVolumeCurveDrc;
4738 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4739 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004740 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4741 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004742 }
4743}
4744
Eric Laurente0720872014-03-11 09:30:41 -07004745float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004746 int index,
4747 audio_io_handle_t output,
4748 audio_devices_t device)
4749{
4750 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004751 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004752 StreamDescriptor &streamDesc = mStreams[stream];
4753
4754 if (device == AUDIO_DEVICE_NONE) {
4755 device = outputDesc->device();
4756 }
4757
Eric Laurente552edb2014-03-10 17:42:56 -07004758 volume = volIndexToAmpl(device, streamDesc, index);
4759
4760 // if a headset is connected, apply the following rules to ring tones and notifications
4761 // to avoid sound level bursts in user's ears:
4762 // - always attenuate ring tones and notifications volume by 6dB
4763 // - if music is playing, always limit the volume to current music volume,
4764 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004765 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004766 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4767 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4768 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4769 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4770 ((stream_strategy == STRATEGY_SONIFICATION)
4771 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004772 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004773 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004774 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004775 streamDesc.mCanBeMuted) {
4776 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4777 // when the phone is ringing we must consider that music could have been paused just before
4778 // by the music application and behave as if music was active if the last music track was
4779 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004780 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004781 mLimitRingtoneVolume) {
4782 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004783 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4784 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004785 output,
4786 musicDevice);
4787 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4788 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4789 if (volume > minVol) {
4790 volume = minVol;
4791 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4792 }
4793 }
4794 }
4795
4796 return volume;
4797}
4798
Eric Laurente0720872014-03-11 09:30:41 -07004799status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004800 int index,
4801 audio_io_handle_t output,
4802 audio_devices_t device,
4803 int delayMs,
4804 bool force)
4805{
4806
4807 // do not change actual stream volume if the stream is muted
4808 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4809 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4810 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4811 return NO_ERROR;
4812 }
4813
4814 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004815 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4816 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4817 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4818 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004819 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004820 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004821 return INVALID_OPERATION;
4822 }
4823
4824 float volume = computeVolume(stream, index, output, device);
4825 // We actually change the volume if:
4826 // - the float value returned by computeVolume() changed
4827 // - the force flag is set
4828 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4829 force) {
4830 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4831 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4832 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4833 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004834 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4835 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004836 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004837 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004838 }
4839
Eric Laurent3b73df72014-03-11 09:06:29 -07004840 if (stream == AUDIO_STREAM_VOICE_CALL ||
4841 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004842 float voiceVolume;
4843 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004844 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004845 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4846 } else {
4847 voiceVolume = 1.0;
4848 }
4849
4850 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4851 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4852 mLastVoiceVolume = voiceVolume;
4853 }
4854 }
4855
4856 return NO_ERROR;
4857}
4858
Eric Laurente0720872014-03-11 09:30:41 -07004859void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004860 audio_devices_t device,
4861 int delayMs,
4862 bool force)
4863{
4864 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4865
Eric Laurent3b73df72014-03-11 09:06:29 -07004866 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4867 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004868 mStreams[stream].getVolumeIndex(device),
4869 output,
4870 device,
4871 delayMs,
4872 force);
4873 }
4874}
4875
Eric Laurente0720872014-03-11 09:30:41 -07004876void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004877 bool on,
4878 audio_io_handle_t output,
4879 int delayMs,
4880 audio_devices_t device)
4881{
4882 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004883 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4884 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4885 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004886 }
4887 }
4888}
4889
Eric Laurente0720872014-03-11 09:30:41 -07004890void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004891 bool on,
4892 audio_io_handle_t output,
4893 int delayMs,
4894 audio_devices_t device)
4895{
4896 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004897 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004898 if (device == AUDIO_DEVICE_NONE) {
4899 device = outputDesc->device();
4900 }
4901
4902 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4903 stream, on, output, outputDesc->mMuteCount[stream], device);
4904
4905 if (on) {
4906 if (outputDesc->mMuteCount[stream] == 0) {
4907 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004908 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4909 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004910 checkAndSetVolume(stream, 0, output, device, delayMs);
4911 }
4912 }
4913 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4914 outputDesc->mMuteCount[stream]++;
4915 } else {
4916 if (outputDesc->mMuteCount[stream] == 0) {
4917 ALOGV("setStreamMute() unmuting non muted stream!");
4918 return;
4919 }
4920 if (--outputDesc->mMuteCount[stream] == 0) {
4921 checkAndSetVolume(stream,
4922 streamDesc.getVolumeIndex(device),
4923 output,
4924 device,
4925 delayMs);
4926 }
4927 }
4928}
4929
Eric Laurente0720872014-03-11 09:30:41 -07004930void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004931 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004932{
4933 // if the stream pertains to sonification strategy and we are in call we must
4934 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4935 // in the device used for phone strategy and play the tone if the selected device does not
4936 // interfere with the device used for phone strategy
4937 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4938 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004939 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004940 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4941 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004942 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004943 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4944 stream, starting, outputDesc->mDevice, stateChange);
4945 if (outputDesc->mRefCount[stream]) {
4946 int muteCount = 1;
4947 if (stateChange) {
4948 muteCount = outputDesc->mRefCount[stream];
4949 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004950 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004951 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4952 for (int i = 0; i < muteCount; i++) {
4953 setStreamMute(stream, starting, mPrimaryOutput);
4954 }
4955 } else {
4956 ALOGV("handleIncallSonification() high visibility");
4957 if (outputDesc->device() &
4958 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4959 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4960 for (int i = 0; i < muteCount; i++) {
4961 setStreamMute(stream, starting, mPrimaryOutput);
4962 }
4963 }
4964 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004965 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4966 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004967 } else {
4968 mpClientInterface->stopTone();
4969 }
4970 }
4971 }
4972 }
4973}
4974
Eric Laurente0720872014-03-11 09:30:41 -07004975bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004976{
4977 return isStateInCall(mPhoneState);
4978}
4979
Eric Laurente0720872014-03-11 09:30:41 -07004980bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004981 return ((state == AUDIO_MODE_IN_CALL) ||
4982 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004983}
4984
Eric Laurente0720872014-03-11 09:30:41 -07004985uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004986{
4987 return MAX_EFFECTS_CPU_LOAD;
4988}
4989
Eric Laurente0720872014-03-11 09:30:41 -07004990uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004991{
4992 return MAX_EFFECTS_MEMORY;
4993}
4994
Eric Laurent6a94d692014-05-20 11:18:06 -07004995
Eric Laurente552edb2014-03-10 17:42:56 -07004996// --- AudioOutputDescriptor class implementation
4997
Eric Laurente0720872014-03-11 09:30:41 -07004998AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004999 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005000 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005001 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005002 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5003{
5004 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005005 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005006 mRefCount[i] = 0;
5007 mCurVolume[i] = -1.0;
5008 mMuteCount[i] = 0;
5009 mStopTime[i] = 0;
5010 }
5011 for (int i = 0; i < NUM_STRATEGIES; i++) {
5012 mStrategyMutedByDevice[i] = false;
5013 }
5014 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005015 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07005016 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005017 mSamplingRate = profile->pickSamplingRate();
5018 mFormat = profile->pickFormat();
5019 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005020 if (profile->mGains.size() > 0) {
5021 profile->mGains[0]->getDefaultConfig(&mGain);
5022 }
Eric Laurente552edb2014-03-10 17:42:56 -07005023 }
5024}
5025
Eric Laurente0720872014-03-11 09:30:41 -07005026audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005027{
5028 if (isDuplicated()) {
5029 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5030 } else {
5031 return mDevice;
5032 }
5033}
5034
Eric Laurente0720872014-03-11 09:30:41 -07005035uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005036{
5037 if (isDuplicated()) {
5038 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5039 } else {
5040 return mLatency;
5041 }
5042}
5043
Eric Laurente0720872014-03-11 09:30:41 -07005044bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005045 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005046{
5047 if (isDuplicated()) {
5048 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5049 } else if (outputDesc->isDuplicated()){
5050 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5051 } else {
5052 return (mProfile->mModule == outputDesc->mProfile->mModule);
5053 }
5054}
5055
Eric Laurente0720872014-03-11 09:30:41 -07005056void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005057 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005058{
5059 // forward usage count change to attached outputs
5060 if (isDuplicated()) {
5061 mOutput1->changeRefCount(stream, delta);
5062 mOutput2->changeRefCount(stream, delta);
5063 }
5064 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005065 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5066 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005067 mRefCount[stream] = 0;
5068 return;
5069 }
5070 mRefCount[stream] += delta;
5071 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5072}
5073
Eric Laurente0720872014-03-11 09:30:41 -07005074audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005075{
5076 if (isDuplicated()) {
5077 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5078 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005079 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005080 }
5081}
5082
Eric Laurente0720872014-03-11 09:30:41 -07005083bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005084{
5085 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5086}
5087
Eric Laurente0720872014-03-11 09:30:41 -07005088bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005089 uint32_t inPastMs,
5090 nsecs_t sysTime) const
5091{
5092 if ((sysTime == 0) && (inPastMs != 0)) {
5093 sysTime = systemTime();
5094 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005095 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5096 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005097 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005098 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005099 return true;
5100 }
5101 }
5102 return false;
5103}
5104
Eric Laurente0720872014-03-11 09:30:41 -07005105bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005106 uint32_t inPastMs,
5107 nsecs_t sysTime) const
5108{
5109 if (mRefCount[stream] != 0) {
5110 return true;
5111 }
5112 if (inPastMs == 0) {
5113 return false;
5114 }
5115 if (sysTime == 0) {
5116 sysTime = systemTime();
5117 }
5118 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5119 return true;
5120 }
5121 return false;
5122}
5123
Eric Laurent1c333e22014-05-20 10:48:17 -07005124void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005125 struct audio_port_config *dstConfig,
5126 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005127{
Eric Laurent84c70242014-06-23 08:46:27 -07005128 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5129
Eric Laurent1f2f2232014-06-02 12:01:23 -07005130 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5131 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5132 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005133 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005134 }
5135 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5136
Eric Laurent6a94d692014-05-20 11:18:06 -07005137 dstConfig->id = mId;
5138 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5139 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005140 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5141 dstConfig->ext.mix.handle = mIoHandle;
5142 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005143}
5144
5145void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5146 struct audio_port *port) const
5147{
Eric Laurent84c70242014-06-23 08:46:27 -07005148 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005149 mProfile->toAudioPort(port);
5150 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005151 toAudioPortConfig(&port->active_config);
5152 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005153 port->ext.mix.handle = mIoHandle;
5154 port->ext.mix.latency_class =
5155 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5156}
Eric Laurente552edb2014-03-10 17:42:56 -07005157
Eric Laurente0720872014-03-11 09:30:41 -07005158status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005159{
5160 const size_t SIZE = 256;
5161 char buffer[SIZE];
5162 String8 result;
5163
5164 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5165 result.append(buffer);
5166 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5167 result.append(buffer);
5168 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5169 result.append(buffer);
5170 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5171 result.append(buffer);
5172 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5173 result.append(buffer);
5174 snprintf(buffer, SIZE, " Devices %08x\n", device());
5175 result.append(buffer);
5176 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5177 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005178 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5179 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5180 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005181 result.append(buffer);
5182 }
5183 write(fd, result.string(), result.size());
5184
5185 return NO_ERROR;
5186}
5187
5188// --- AudioInputDescriptor class implementation
5189
Eric Laurent1c333e22014-05-20 10:48:17 -07005190AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005191 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005192 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005193 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005194{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005195 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005196 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07005197 mSamplingRate = profile->pickSamplingRate();
5198 mFormat = profile->pickFormat();
5199 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005200 if (profile->mGains.size() > 0) {
5201 profile->mGains[0]->getDefaultConfig(&mGain);
5202 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005203 }
Eric Laurente552edb2014-03-10 17:42:56 -07005204}
5205
Eric Laurent1c333e22014-05-20 10:48:17 -07005206void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 struct audio_port_config *dstConfig,
5208 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005209{
Eric Laurent84c70242014-06-23 08:46:27 -07005210 ALOG_ASSERT(mProfile != 0,
5211 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005212 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5213 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5214 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005215 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005216 }
5217
5218 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5219
Eric Laurent6a94d692014-05-20 11:18:06 -07005220 dstConfig->id = mId;
5221 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5222 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005223 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5224 dstConfig->ext.mix.handle = mIoHandle;
5225 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005226}
5227
5228void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5229 struct audio_port *port) const
5230{
Eric Laurent84c70242014-06-23 08:46:27 -07005231 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5232
Eric Laurent1c333e22014-05-20 10:48:17 -07005233 mProfile->toAudioPort(port);
5234 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005235 toAudioPortConfig(&port->active_config);
5236 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005237 port->ext.mix.handle = mIoHandle;
5238 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5239}
5240
Eric Laurente0720872014-03-11 09:30:41 -07005241status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005242{
5243 const size_t SIZE = 256;
5244 char buffer[SIZE];
5245 String8 result;
5246
5247 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5248 result.append(buffer);
5249 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5250 result.append(buffer);
5251 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5252 result.append(buffer);
5253 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5254 result.append(buffer);
5255 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5256 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005257 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5258 result.append(buffer);
5259
Eric Laurente552edb2014-03-10 17:42:56 -07005260 write(fd, result.string(), result.size());
5261
5262 return NO_ERROR;
5263}
5264
5265// --- StreamDescriptor class implementation
5266
Eric Laurente0720872014-03-11 09:30:41 -07005267AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005268 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5269{
5270 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5271}
5272
Eric Laurente0720872014-03-11 09:30:41 -07005273int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005274{
Eric Laurente0720872014-03-11 09:30:41 -07005275 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005276 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5277 if (mIndexCur.indexOfKey(device) < 0) {
5278 device = AUDIO_DEVICE_OUT_DEFAULT;
5279 }
5280 return mIndexCur.valueFor(device);
5281}
5282
Eric Laurente0720872014-03-11 09:30:41 -07005283void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005284{
5285 const size_t SIZE = 256;
5286 char buffer[SIZE];
5287 String8 result;
5288
5289 snprintf(buffer, SIZE, "%s %02d %02d ",
5290 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5291 result.append(buffer);
5292 for (size_t i = 0; i < mIndexCur.size(); i++) {
5293 snprintf(buffer, SIZE, "%04x : %02d, ",
5294 mIndexCur.keyAt(i),
5295 mIndexCur.valueAt(i));
5296 result.append(buffer);
5297 }
5298 result.append("\n");
5299
5300 write(fd, result.string(), result.size());
5301}
5302
5303// --- EffectDescriptor class implementation
5304
Eric Laurente0720872014-03-11 09:30:41 -07005305status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005306{
5307 const size_t SIZE = 256;
5308 char buffer[SIZE];
5309 String8 result;
5310
5311 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5312 result.append(buffer);
5313 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5314 result.append(buffer);
5315 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5316 result.append(buffer);
5317 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5318 result.append(buffer);
5319 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5320 result.append(buffer);
5321 write(fd, result.string(), result.size());
5322
5323 return NO_ERROR;
5324}
5325
Eric Laurent1c333e22014-05-20 10:48:17 -07005326// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005327
Eric Laurente0720872014-03-11 09:30:41 -07005328AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005329 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5330 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005331{
5332}
5333
Eric Laurente0720872014-03-11 09:30:41 -07005334AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005335{
5336 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005337 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005338 }
5339 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005340 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005341 }
5342 free((void *)mName);
5343}
5344
Eric Laurent1afeecb2014-05-14 08:52:28 -07005345status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5346{
5347 cnode *node = root->first_child;
5348
5349 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5350
5351 while (node) {
5352 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5353 profile->loadSamplingRates((char *)node->value);
5354 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5355 profile->loadFormats((char *)node->value);
5356 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5357 profile->loadInChannels((char *)node->value);
5358 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5359 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5360 mDeclaredDevices);
5361 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5362 profile->loadGains(node);
5363 }
5364 node = node->next;
5365 }
5366 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5367 "loadInput() invalid supported devices");
5368 ALOGW_IF(profile->mChannelMasks.size() == 0,
5369 "loadInput() invalid supported channel masks");
5370 ALOGW_IF(profile->mSamplingRates.size() == 0,
5371 "loadInput() invalid supported sampling rates");
5372 ALOGW_IF(profile->mFormats.size() == 0,
5373 "loadInput() invalid supported formats");
5374 if (!profile->mSupportedDevices.isEmpty() &&
5375 (profile->mChannelMasks.size() != 0) &&
5376 (profile->mSamplingRates.size() != 0) &&
5377 (profile->mFormats.size() != 0)) {
5378
5379 ALOGV("loadInput() adding input Supported Devices %04x",
5380 profile->mSupportedDevices.types());
5381
5382 mInputProfiles.add(profile);
5383 return NO_ERROR;
5384 } else {
5385 return BAD_VALUE;
5386 }
5387}
5388
5389status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5390{
5391 cnode *node = root->first_child;
5392
5393 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5394
5395 while (node) {
5396 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5397 profile->loadSamplingRates((char *)node->value);
5398 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5399 profile->loadFormats((char *)node->value);
5400 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5401 profile->loadOutChannels((char *)node->value);
5402 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5403 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5404 mDeclaredDevices);
5405 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5406 profile->mFlags = parseFlagNames((char *)node->value);
5407 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5408 profile->loadGains(node);
5409 }
5410 node = node->next;
5411 }
5412 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5413 "loadOutput() invalid supported devices");
5414 ALOGW_IF(profile->mChannelMasks.size() == 0,
5415 "loadOutput() invalid supported channel masks");
5416 ALOGW_IF(profile->mSamplingRates.size() == 0,
5417 "loadOutput() invalid supported sampling rates");
5418 ALOGW_IF(profile->mFormats.size() == 0,
5419 "loadOutput() invalid supported formats");
5420 if (!profile->mSupportedDevices.isEmpty() &&
5421 (profile->mChannelMasks.size() != 0) &&
5422 (profile->mSamplingRates.size() != 0) &&
5423 (profile->mFormats.size() != 0)) {
5424
5425 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5426 profile->mSupportedDevices.types(), profile->mFlags);
5427
5428 mOutputProfiles.add(profile);
5429 return NO_ERROR;
5430 } else {
5431 return BAD_VALUE;
5432 }
5433}
5434
5435status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5436{
5437 cnode *node = root->first_child;
5438
5439 audio_devices_t type = AUDIO_DEVICE_NONE;
5440 while (node) {
5441 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5442 type = parseDeviceNames((char *)node->value);
5443 break;
5444 }
5445 node = node->next;
5446 }
5447 if (type == AUDIO_DEVICE_NONE ||
5448 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5449 ALOGW("loadDevice() bad type %08x", type);
5450 return BAD_VALUE;
5451 }
5452 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5453 deviceDesc->mModule = this;
5454
5455 node = root->first_child;
5456 while (node) {
5457 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5458 deviceDesc->mAddress = String8((char *)node->value);
5459 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5460 if (audio_is_input_device(type)) {
5461 deviceDesc->loadInChannels((char *)node->value);
5462 } else {
5463 deviceDesc->loadOutChannels((char *)node->value);
5464 }
5465 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5466 deviceDesc->loadGains(node);
5467 }
5468 node = node->next;
5469 }
5470
5471 ALOGV("loadDevice() adding device name %s type %08x address %s",
5472 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5473
5474 mDeclaredDevices.add(deviceDesc);
5475
5476 return NO_ERROR;
5477}
5478
Eric Laurente0720872014-03-11 09:30:41 -07005479void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005480{
5481 const size_t SIZE = 256;
5482 char buffer[SIZE];
5483 String8 result;
5484
5485 snprintf(buffer, SIZE, " - name: %s\n", mName);
5486 result.append(buffer);
5487 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5488 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005489 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5490 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005491 write(fd, result.string(), result.size());
5492 if (mOutputProfiles.size()) {
5493 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5494 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005495 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005496 write(fd, buffer, strlen(buffer));
5497 mOutputProfiles[i]->dump(fd);
5498 }
5499 }
5500 if (mInputProfiles.size()) {
5501 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5502 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005503 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005504 write(fd, buffer, strlen(buffer));
5505 mInputProfiles[i]->dump(fd);
5506 }
5507 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005508 if (mDeclaredDevices.size()) {
5509 write(fd, " - devices:\n", strlen(" - devices:\n"));
5510 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5511 mDeclaredDevices[i]->dump(fd, 4, i);
5512 }
5513 }
Eric Laurente552edb2014-03-10 17:42:56 -07005514}
5515
Eric Laurent1c333e22014-05-20 10:48:17 -07005516// --- AudioPort class implementation
5517
Eric Laurenta121f902014-06-03 13:32:54 -07005518
5519AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5520 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005521 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005522{
5523 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5524 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5525}
5526
Eric Laurent1c333e22014-05-20 10:48:17 -07005527void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5528{
5529 port->role = mRole;
5530 port->type = mType;
5531 unsigned int i;
5532 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5533 port->sample_rates[i] = mSamplingRates[i];
5534 }
5535 port->num_sample_rates = i;
5536 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5537 port->channel_masks[i] = mChannelMasks[i];
5538 }
5539 port->num_channel_masks = i;
5540 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5541 port->formats[i] = mFormats[i];
5542 }
5543 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005544
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005545 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005546
5547 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5548 port->gains[i] = mGains[i]->mGain;
5549 }
5550 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005551}
5552
5553
5554void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5555{
5556 char *str = strtok(name, "|");
5557
5558 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5559 // rates should be read from the output stream after it is opened for the first time
5560 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5561 mSamplingRates.add(0);
5562 return;
5563 }
5564
5565 while (str != NULL) {
5566 uint32_t rate = atoi(str);
5567 if (rate != 0) {
5568 ALOGV("loadSamplingRates() adding rate %d", rate);
5569 mSamplingRates.add(rate);
5570 }
5571 str = strtok(NULL, "|");
5572 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005573}
5574
5575void AudioPolicyManager::AudioPort::loadFormats(char *name)
5576{
5577 char *str = strtok(name, "|");
5578
5579 // by convention, "0' in the first entry in mFormats indicates the supported formats
5580 // should be read from the output stream after it is opened for the first time
5581 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5582 mFormats.add(AUDIO_FORMAT_DEFAULT);
5583 return;
5584 }
5585
5586 while (str != NULL) {
5587 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5588 ARRAY_SIZE(sFormatNameToEnumTable),
5589 str);
5590 if (format != AUDIO_FORMAT_DEFAULT) {
5591 mFormats.add(format);
5592 }
5593 str = strtok(NULL, "|");
5594 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005595}
5596
5597void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5598{
5599 const char *str = strtok(name, "|");
5600
5601 ALOGV("loadInChannels() %s", name);
5602
5603 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5604 mChannelMasks.add(0);
5605 return;
5606 }
5607
5608 while (str != NULL) {
5609 audio_channel_mask_t channelMask =
5610 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5611 ARRAY_SIZE(sInChannelsNameToEnumTable),
5612 str);
5613 if (channelMask != 0) {
5614 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5615 mChannelMasks.add(channelMask);
5616 }
5617 str = strtok(NULL, "|");
5618 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005619}
5620
5621void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5622{
5623 const char *str = strtok(name, "|");
5624
5625 ALOGV("loadOutChannels() %s", name);
5626
5627 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5628 // masks should be read from the output stream after it is opened for the first time
5629 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5630 mChannelMasks.add(0);
5631 return;
5632 }
5633
5634 while (str != NULL) {
5635 audio_channel_mask_t channelMask =
5636 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5637 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5638 str);
5639 if (channelMask != 0) {
5640 mChannelMasks.add(channelMask);
5641 }
5642 str = strtok(NULL, "|");
5643 }
5644 return;
5645}
5646
Eric Laurent1afeecb2014-05-14 08:52:28 -07005647audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5648{
5649 const char *str = strtok(name, "|");
5650
5651 ALOGV("loadGainMode() %s", name);
5652 audio_gain_mode_t mode = 0;
5653 while (str != NULL) {
5654 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5655 ARRAY_SIZE(sGainModeNameToEnumTable),
5656 str);
5657 str = strtok(NULL, "|");
5658 }
5659 return mode;
5660}
5661
Eric Laurenta121f902014-06-03 13:32:54 -07005662void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005663{
5664 cnode *node = root->first_child;
5665
Eric Laurenta121f902014-06-03 13:32:54 -07005666 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005667
5668 while (node) {
5669 if (strcmp(node->name, GAIN_MODE) == 0) {
5670 gain->mGain.mode = loadGainMode((char *)node->value);
5671 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005672 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005673 gain->mGain.channel_mask =
5674 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5675 ARRAY_SIZE(sInChannelsNameToEnumTable),
5676 (char *)node->value);
5677 } else {
5678 gain->mGain.channel_mask =
5679 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5680 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5681 (char *)node->value);
5682 }
5683 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5684 gain->mGain.min_value = atoi((char *)node->value);
5685 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5686 gain->mGain.max_value = atoi((char *)node->value);
5687 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5688 gain->mGain.default_value = atoi((char *)node->value);
5689 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5690 gain->mGain.step_value = atoi((char *)node->value);
5691 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5692 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5693 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5694 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5695 }
5696 node = node->next;
5697 }
5698
5699 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5700 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5701
5702 if (gain->mGain.mode == 0) {
5703 return;
5704 }
5705 mGains.add(gain);
5706}
5707
5708void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5709{
5710 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005711 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005712 while (node) {
5713 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005714 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005715 node = node->next;
5716 }
5717}
5718
Glenn Kastencbd48022014-07-24 13:46:44 -07005719status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005720{
5721 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5722 if (mSamplingRates[i] == samplingRate) {
5723 return NO_ERROR;
5724 }
5725 }
5726 return BAD_VALUE;
5727}
5728
Glenn Kastencbd48022014-07-24 13:46:44 -07005729status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5730 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005731{
Glenn Kastencbd48022014-07-24 13:46:44 -07005732 // Search for the closest supported sampling rate that is above (preferred)
5733 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5734 // The sampling rates do not need to be sorted in ascending order.
5735 ssize_t maxBelow = -1;
5736 ssize_t minAbove = -1;
5737 uint32_t candidate;
5738 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5739 candidate = mSamplingRates[i];
5740 if (candidate == samplingRate) {
5741 if (updatedSamplingRate != NULL) {
5742 *updatedSamplingRate = candidate;
5743 }
5744 return NO_ERROR;
5745 }
5746 // candidate < desired
5747 if (candidate < samplingRate) {
5748 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5749 maxBelow = i;
5750 }
5751 // candidate > desired
5752 } else {
5753 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5754 minAbove = i;
5755 }
5756 }
5757 }
5758 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5759 // TODO Move these assumptions out.
5760 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5761 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5762 // due to approximation by an int32_t of the
5763 // phase increments
5764 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5765 if (minAbove >= 0) {
5766 candidate = mSamplingRates[minAbove];
5767 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5768 if (updatedSamplingRate != NULL) {
5769 *updatedSamplingRate = candidate;
5770 }
5771 return NO_ERROR;
5772 }
5773 }
5774 // But if we have to up-sample from a lower sampling rate, that's OK.
5775 if (maxBelow >= 0) {
5776 candidate = mSamplingRates[maxBelow];
5777 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5778 if (updatedSamplingRate != NULL) {
5779 *updatedSamplingRate = candidate;
5780 }
5781 return NO_ERROR;
5782 }
5783 }
5784 // leave updatedSamplingRate unmodified
5785 return BAD_VALUE;
5786}
5787
5788status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5789{
5790 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005791 if (mChannelMasks[i] == channelMask) {
5792 return NO_ERROR;
5793 }
5794 }
5795 return BAD_VALUE;
5796}
5797
Glenn Kastencbd48022014-07-24 13:46:44 -07005798status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5799 const
5800{
5801 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5802 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5803 // FIXME Does not handle multi-channel automatic conversions yet
5804 audio_channel_mask_t supported = mChannelMasks[i];
5805 if (supported == channelMask) {
5806 return NO_ERROR;
5807 }
5808 if (isRecordThread) {
5809 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5810 // FIXME Abstract this out to a table.
5811 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5812 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5813 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5814 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5815 return NO_ERROR;
5816 }
5817 }
5818 }
5819 return BAD_VALUE;
5820}
5821
Eric Laurenta121f902014-06-03 13:32:54 -07005822status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5823{
5824 for (size_t i = 0; i < mFormats.size(); i ++) {
5825 if (mFormats[i] == format) {
5826 return NO_ERROR;
5827 }
5828 }
5829 return BAD_VALUE;
5830}
5831
Eric Laurent1e693b52014-07-09 15:03:28 -07005832
5833uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5834{
5835 // special case for uninitialized dynamic profile
5836 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5837 return 0;
5838 }
5839
5840 uint32_t samplingRate = 0;
5841 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5842
5843 // For mixed output and inputs, use max mixer sampling rates. Do not
5844 // limit sampling rate otherwise
5845 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5846 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5847 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5848 maxRate = UINT_MAX;
5849 }
5850 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5851 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5852 samplingRate = mSamplingRates[i];
5853 }
5854 }
5855 return samplingRate;
5856}
5857
5858audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5859{
5860 // special case for uninitialized dynamic profile
5861 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5862 return AUDIO_CHANNEL_NONE;
5863 }
5864
5865 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5866 uint32_t channelCount = 0;
5867 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5868
5869 // For mixed output and inputs, use max mixer channel count. Do not
5870 // limit channel count otherwise
5871 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5872 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5873 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5874 maxCount = UINT_MAX;
5875 }
5876 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5877 uint32_t cnlCount;
5878 if (mUseInChannelMask) {
5879 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5880 } else {
5881 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5882 }
5883 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5884 channelMask = mChannelMasks[i];
5885 }
5886 }
5887 return channelMask;
5888}
5889
Andy Hung9a605382014-07-28 16:16:31 -07005890/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07005891const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5892 AUDIO_FORMAT_DEFAULT,
5893 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005894 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005895 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005896 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07005897 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005898};
5899
5900int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5901 audio_format_t format2)
5902{
5903 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5904 // compressed format and better than any PCM format. This is by design of pickFormat()
5905 if (!audio_is_linear_pcm(format1)) {
5906 if (!audio_is_linear_pcm(format2)) {
5907 return 0;
5908 }
5909 return 1;
5910 }
5911 if (!audio_is_linear_pcm(format2)) {
5912 return -1;
5913 }
5914
5915 int index1 = -1, index2 = -1;
5916 for (size_t i = 0;
5917 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5918 i ++) {
5919 if (sPcmFormatCompareTable[i] == format1) {
5920 index1 = i;
5921 }
5922 if (sPcmFormatCompareTable[i] == format2) {
5923 index2 = i;
5924 }
5925 }
5926 // format1 not found => index1 < 0 => format2 > format1
5927 // format2 not found => index2 < 0 => format2 < format1
5928 return index1 - index2;
5929}
5930
5931audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5932{
5933 // special case for uninitialized dynamic profile
5934 if (mFormats.size() == 1 && mFormats[0] == 0) {
5935 return AUDIO_FORMAT_DEFAULT;
5936 }
5937
5938 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07005939 audio_format_t bestFormat =
5940 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5941 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07005942 // For mixed output and inputs, use best mixer output format. Do not
5943 // limit format otherwise
5944 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5945 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07005946 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005947 bestFormat = AUDIO_FORMAT_INVALID;
5948 }
5949
5950 for (size_t i = 0; i < mFormats.size(); i ++) {
5951 if ((compareFormats(mFormats[i], format) > 0) &&
5952 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5953 format = mFormats[i];
5954 }
5955 }
5956 return format;
5957}
5958
Eric Laurenta121f902014-06-03 13:32:54 -07005959status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5960 int index) const
5961{
5962 if (index < 0 || (size_t)index >= mGains.size()) {
5963 return BAD_VALUE;
5964 }
5965 return mGains[index]->checkConfig(gainConfig);
5966}
5967
Eric Laurent1afeecb2014-05-14 08:52:28 -07005968void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5969{
5970 const size_t SIZE = 256;
5971 char buffer[SIZE];
5972 String8 result;
5973
5974 if (mName.size() != 0) {
5975 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5976 result.append(buffer);
5977 }
5978
5979 if (mSamplingRates.size() != 0) {
5980 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5981 result.append(buffer);
5982 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005983 if (i == 0 && mSamplingRates[i] == 0) {
5984 snprintf(buffer, SIZE, "Dynamic");
5985 } else {
5986 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5987 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005988 result.append(buffer);
5989 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5990 }
5991 result.append("\n");
5992 }
5993
5994 if (mChannelMasks.size() != 0) {
5995 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5996 result.append(buffer);
5997 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005998 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5999
6000 if (i == 0 && mChannelMasks[i] == 0) {
6001 snprintf(buffer, SIZE, "Dynamic");
6002 } else {
6003 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6004 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006005 result.append(buffer);
6006 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6007 }
6008 result.append("\n");
6009 }
6010
6011 if (mFormats.size() != 0) {
6012 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6013 result.append(buffer);
6014 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006015 const char *formatStr = enumToString(sFormatNameToEnumTable,
6016 ARRAY_SIZE(sFormatNameToEnumTable),
6017 mFormats[i]);
6018 if (i == 0 && strcmp(formatStr, "") == 0) {
6019 snprintf(buffer, SIZE, "Dynamic");
6020 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006021 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006022 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006023 result.append(buffer);
6024 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6025 }
6026 result.append("\n");
6027 }
6028 write(fd, result.string(), result.size());
6029 if (mGains.size() != 0) {
6030 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6031 write(fd, buffer, strlen(buffer) + 1);
6032 result.append(buffer);
6033 for (size_t i = 0; i < mGains.size(); i++) {
6034 mGains[i]->dump(fd, spaces + 2, i);
6035 }
6036 }
6037}
6038
6039// --- AudioGain class implementation
6040
Eric Laurenta121f902014-06-03 13:32:54 -07006041AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006042{
Eric Laurenta121f902014-06-03 13:32:54 -07006043 mIndex = index;
6044 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006045 memset(&mGain, 0, sizeof(struct audio_gain));
6046}
6047
Eric Laurenta121f902014-06-03 13:32:54 -07006048void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6049{
6050 config->index = mIndex;
6051 config->mode = mGain.mode;
6052 config->channel_mask = mGain.channel_mask;
6053 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6054 config->values[0] = mGain.default_value;
6055 } else {
6056 uint32_t numValues;
6057 if (mUseInChannelMask) {
6058 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6059 } else {
6060 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6061 }
6062 for (size_t i = 0; i < numValues; i++) {
6063 config->values[i] = mGain.default_value;
6064 }
6065 }
6066 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6067 config->ramp_duration_ms = mGain.min_ramp_ms;
6068 }
6069}
6070
6071status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6072{
6073 if ((config->mode & ~mGain.mode) != 0) {
6074 return BAD_VALUE;
6075 }
6076 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6077 if ((config->values[0] < mGain.min_value) ||
6078 (config->values[0] > mGain.max_value)) {
6079 return BAD_VALUE;
6080 }
6081 } else {
6082 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6083 return BAD_VALUE;
6084 }
6085 uint32_t numValues;
6086 if (mUseInChannelMask) {
6087 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6088 } else {
6089 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6090 }
6091 for (size_t i = 0; i < numValues; i++) {
6092 if ((config->values[i] < mGain.min_value) ||
6093 (config->values[i] > mGain.max_value)) {
6094 return BAD_VALUE;
6095 }
6096 }
6097 }
6098 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6099 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6100 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6101 return BAD_VALUE;
6102 }
6103 }
6104 return NO_ERROR;
6105}
6106
Eric Laurent1afeecb2014-05-14 08:52:28 -07006107void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6108{
6109 const size_t SIZE = 256;
6110 char buffer[SIZE];
6111 String8 result;
6112
6113 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6114 result.append(buffer);
6115 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6116 result.append(buffer);
6117 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6118 result.append(buffer);
6119 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6120 result.append(buffer);
6121 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6122 result.append(buffer);
6123 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6124 result.append(buffer);
6125 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6126 result.append(buffer);
6127 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6128 result.append(buffer);
6129 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6130 result.append(buffer);
6131
6132 write(fd, result.string(), result.size());
6133}
6134
Eric Laurent1f2f2232014-06-02 12:01:23 -07006135// --- AudioPortConfig class implementation
6136
6137AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6138{
6139 mSamplingRate = 0;
6140 mChannelMask = AUDIO_CHANNEL_NONE;
6141 mFormat = AUDIO_FORMAT_INVALID;
6142 mGain.index = -1;
6143}
6144
Eric Laurenta121f902014-06-03 13:32:54 -07006145status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6146 const struct audio_port_config *config,
6147 struct audio_port_config *backupConfig)
6148{
6149 struct audio_port_config localBackupConfig;
6150 status_t status = NO_ERROR;
6151
6152 localBackupConfig.config_mask = config->config_mask;
6153 toAudioPortConfig(&localBackupConfig);
6154
6155 if (mAudioPort == 0) {
6156 status = NO_INIT;
6157 goto exit;
6158 }
6159 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07006160 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006161 if (status != NO_ERROR) {
6162 goto exit;
6163 }
6164 mSamplingRate = config->sample_rate;
6165 }
6166 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07006167 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006168 if (status != NO_ERROR) {
6169 goto exit;
6170 }
6171 mChannelMask = config->channel_mask;
6172 }
6173 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6174 status = mAudioPort->checkFormat(config->format);
6175 if (status != NO_ERROR) {
6176 goto exit;
6177 }
6178 mFormat = config->format;
6179 }
6180 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6181 status = mAudioPort->checkGain(&config->gain, config->gain.index);
6182 if (status != NO_ERROR) {
6183 goto exit;
6184 }
6185 mGain = config->gain;
6186 }
6187
6188exit:
6189 if (status != NO_ERROR) {
6190 applyAudioPortConfig(&localBackupConfig);
6191 }
6192 if (backupConfig != NULL) {
6193 *backupConfig = localBackupConfig;
6194 }
6195 return status;
6196}
6197
Eric Laurent1f2f2232014-06-02 12:01:23 -07006198void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6199 struct audio_port_config *dstConfig,
6200 const struct audio_port_config *srcConfig) const
6201{
6202 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6203 dstConfig->sample_rate = mSamplingRate;
6204 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6205 dstConfig->sample_rate = srcConfig->sample_rate;
6206 }
6207 } else {
6208 dstConfig->sample_rate = 0;
6209 }
6210 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6211 dstConfig->channel_mask = mChannelMask;
6212 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6213 dstConfig->channel_mask = srcConfig->channel_mask;
6214 }
6215 } else {
6216 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6217 }
6218 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6219 dstConfig->format = mFormat;
6220 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6221 dstConfig->format = srcConfig->format;
6222 }
6223 } else {
6224 dstConfig->format = AUDIO_FORMAT_INVALID;
6225 }
6226 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6227 dstConfig->gain = mGain;
6228 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6229 dstConfig->gain = srcConfig->gain;
6230 }
6231 } else {
6232 dstConfig->gain.index = -1;
6233 }
6234 if (dstConfig->gain.index != -1) {
6235 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6236 } else {
6237 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6238 }
6239}
6240
Eric Laurent1c333e22014-05-20 10:48:17 -07006241// --- IOProfile class implementation
6242
Eric Laurent1afeecb2014-05-14 08:52:28 -07006243AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006244 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006245 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006246{
6247}
6248
Eric Laurente0720872014-03-11 09:30:41 -07006249AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006250{
6251}
6252
6253// checks if the IO profile is compatible with specified parameters.
6254// Sampling rate, format and channel mask must be specified in order to
6255// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006256bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006257 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006258 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006259 audio_format_t format,
6260 audio_channel_mask_t channelMask,
6261 audio_output_flags_t flags) const
6262{
Glenn Kastencbd48022014-07-24 13:46:44 -07006263 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6264 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6265 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006266
Glenn Kastencbd48022014-07-24 13:46:44 -07006267 if ((mSupportedDevices.types() & device) != device) {
6268 return false;
6269 }
6270
6271 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006272 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006273 }
6274 uint32_t myUpdatedSamplingRate = samplingRate;
6275 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006276 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006277 }
6278 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6279 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006280 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006281 }
6282
6283 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6284 return false;
6285 }
6286
6287 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6288 checkExactChannelMask(channelMask) != NO_ERROR)) {
6289 return false;
6290 }
6291 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6292 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6293 return false;
6294 }
6295
6296 if (isPlaybackThread && (mFlags & flags) != flags) {
6297 return false;
6298 }
6299 // The only input flag that is allowed to be different is the fast flag.
6300 // An existing fast stream is compatible with a normal track request.
6301 // An existing normal stream is compatible with a fast track request,
6302 // but the fast request will be denied by AudioFlinger and converted to normal track.
6303 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6304 ~AUDIO_INPUT_FLAG_FAST)) {
6305 return false;
6306 }
6307
6308 if (updatedSamplingRate != NULL) {
6309 *updatedSamplingRate = myUpdatedSamplingRate;
6310 }
6311 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006312}
6313
Eric Laurente0720872014-03-11 09:30:41 -07006314void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006315{
6316 const size_t SIZE = 256;
6317 char buffer[SIZE];
6318 String8 result;
6319
Eric Laurent1afeecb2014-05-14 08:52:28 -07006320 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006321
Eric Laurente552edb2014-03-10 17:42:56 -07006322 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6323 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006324 snprintf(buffer, SIZE, " - devices:\n");
6325 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006326 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006327 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6328 mSupportedDevices[i]->dump(fd, 6, i);
6329 }
Eric Laurente552edb2014-03-10 17:42:56 -07006330}
6331
Eric Laurentd4692962014-05-05 18:13:44 -07006332void AudioPolicyManager::IOProfile::log()
6333{
6334 const size_t SIZE = 256;
6335 char buffer[SIZE];
6336 String8 result;
6337
6338 ALOGV(" - sampling rates: ");
6339 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6340 ALOGV(" %d", mSamplingRates[i]);
6341 }
6342
6343 ALOGV(" - channel masks: ");
6344 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6345 ALOGV(" 0x%04x", mChannelMasks[i]);
6346 }
6347
6348 ALOGV(" - formats: ");
6349 for (size_t i = 0; i < mFormats.size(); i++) {
6350 ALOGV(" 0x%08x", mFormats[i]);
6351 }
6352
6353 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6354 ALOGV(" - flags: 0x%04x\n", mFlags);
6355}
6356
6357
Eric Laurent3a4311c2014-03-17 12:00:47 -07006358// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006359
Eric Laurent1f2f2232014-06-02 12:01:23 -07006360
6361AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6362 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6363 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6364 AUDIO_PORT_ROLE_SOURCE,
6365 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006366 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006367{
6368 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07006369 if (mGains.size() > 0) {
6370 mGains[0]->getDefaultConfig(&mGain);
6371 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006372}
6373
Eric Laurent3a4311c2014-03-17 12:00:47 -07006374bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006375{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006376 // Devices are considered equal if they:
6377 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6378 // - have the same address or one device does not specify the address
6379 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006380 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006381 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006382 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006383 mChannelMask == other->mChannelMask);
6384}
6385
6386void AudioPolicyManager::DeviceVector::refreshTypes()
6387{
Eric Laurent1c333e22014-05-20 10:48:17 -07006388 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006389 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006390 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006391 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006392 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006393}
6394
6395ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6396{
6397 for(size_t i = 0; i < size(); i++) {
6398 if (item->equals(itemAt(i))) {
6399 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006400 }
6401 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006402 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006403}
6404
Eric Laurent3a4311c2014-03-17 12:00:47 -07006405ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006406{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006407 ssize_t ret = indexOf(item);
6408
6409 if (ret < 0) {
6410 ret = SortedVector::add(item);
6411 if (ret >= 0) {
6412 refreshTypes();
6413 }
6414 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006415 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006416 ret = -1;
6417 }
6418 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006419}
6420
Eric Laurent3a4311c2014-03-17 12:00:47 -07006421ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6422{
6423 size_t i;
6424 ssize_t ret = indexOf(item);
6425
6426 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006427 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006428 } else {
6429 ret = SortedVector::removeAt(ret);
6430 if (ret >= 0) {
6431 refreshTypes();
6432 }
6433 }
6434 return ret;
6435}
6436
6437void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6438{
6439 DeviceVector deviceList;
6440
6441 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6442 types &= ~role_bit;
6443
6444 while (types) {
6445 uint32_t i = 31 - __builtin_clz(types);
6446 uint32_t type = 1 << i;
6447 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006448 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006449 }
6450}
6451
Eric Laurent1afeecb2014-05-14 08:52:28 -07006452void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6453 const DeviceVector& declaredDevices)
6454{
6455 char *devName = strtok(name, "|");
6456 while (devName != NULL) {
6457 if (strlen(devName) != 0) {
6458 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6459 ARRAY_SIZE(sDeviceNameToEnumTable),
6460 devName);
6461 if (type != AUDIO_DEVICE_NONE) {
6462 add(new DeviceDescriptor(String8(""), type));
6463 } else {
6464 sp<DeviceDescriptor> deviceDesc =
6465 declaredDevices.getDeviceFromName(String8(devName));
6466 if (deviceDesc != 0) {
6467 add(deviceDesc);
6468 }
6469 }
6470 }
6471 devName = strtok(NULL, "|");
6472 }
6473}
6474
Eric Laurent1c333e22014-05-20 10:48:17 -07006475sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6476 audio_devices_t type, String8 address) const
6477{
6478 sp<DeviceDescriptor> device;
6479 for (size_t i = 0; i < size(); i++) {
6480 if (itemAt(i)->mDeviceType == type) {
6481 device = itemAt(i);
6482 if (itemAt(i)->mAddress = address) {
6483 break;
6484 }
6485 }
6486 }
6487 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6488 type, address.string(), device.get());
6489 return device;
6490}
6491
Eric Laurent6a94d692014-05-20 11:18:06 -07006492sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6493 audio_port_handle_t id) const
6494{
6495 sp<DeviceDescriptor> device;
6496 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006497 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006498 if (itemAt(i)->mId == id) {
6499 device = itemAt(i);
6500 break;
6501 }
6502 }
6503 return device;
6504}
6505
Eric Laurent1c333e22014-05-20 10:48:17 -07006506AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6507 audio_devices_t type) const
6508{
6509 DeviceVector devices;
6510 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6511 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6512 devices.add(itemAt(i));
6513 type &= ~itemAt(i)->mDeviceType;
6514 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6515 itemAt(i)->mDeviceType, itemAt(i).get());
6516 }
6517 }
6518 return devices;
6519}
6520
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006521AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6522 audio_devices_t type, String8 address) const
6523{
6524 DeviceVector devices;
6525 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6526 for (size_t i = 0; i < size(); i++) {
6527 //ALOGV(" at i=%d: device=%x, addr=%s",
6528 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6529 if (itemAt(i)->mDeviceType == type) {
6530 if (itemAt(i)->mAddress == address) {
6531 //ALOGV(" found matching address %s", address.string());
6532 devices.add(itemAt(i));
6533 }
6534 }
6535 }
6536 return devices;
6537}
6538
Eric Laurent1afeecb2014-05-14 08:52:28 -07006539sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6540 const String8& name) const
6541{
6542 sp<DeviceDescriptor> device;
6543 for (size_t i = 0; i < size(); i++) {
6544 if (itemAt(i)->mName == name) {
6545 device = itemAt(i);
6546 break;
6547 }
6548 }
6549 return device;
6550}
6551
Eric Laurent6a94d692014-05-20 11:18:06 -07006552void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6553 struct audio_port_config *dstConfig,
6554 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006555{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006556 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6557 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006558 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006559 }
6560
6561 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6562
Eric Laurent6a94d692014-05-20 11:18:06 -07006563 dstConfig->id = mId;
6564 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006565 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006566 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006567 dstConfig->ext.device.type = mDeviceType;
6568 dstConfig->ext.device.hw_module = mModule->mHandle;
6569 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006570}
6571
6572void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6573{
Eric Laurent83b88082014-06-20 18:31:16 -07006574 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006575 AudioPort::toAudioPort(port);
6576 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006577 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006578 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006579 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006580 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6581}
6582
Eric Laurent1afeecb2014-05-14 08:52:28 -07006583status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006584{
6585 const size_t SIZE = 256;
6586 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006587 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006588
Eric Laurent1afeecb2014-05-14 08:52:28 -07006589 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6590 result.append(buffer);
6591 if (mId != 0) {
6592 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6593 result.append(buffer);
6594 }
6595 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6596 enumToString(sDeviceNameToEnumTable,
6597 ARRAY_SIZE(sDeviceNameToEnumTable),
6598 mDeviceType));
6599 result.append(buffer);
6600 if (mAddress.size() != 0) {
6601 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6602 result.append(buffer);
6603 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006604 write(fd, result.string(), result.size());
6605 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006606
6607 return NO_ERROR;
6608}
6609
6610
6611// --- audio_policy.conf file parsing
6612
Eric Laurente0720872014-03-11 09:30:41 -07006613audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006614{
6615 uint32_t flag = 0;
6616
6617 // it is OK to cast name to non const here as we are not going to use it after
6618 // strtok() modifies it
6619 char *flagName = strtok(name, "|");
6620 while (flagName != NULL) {
6621 if (strlen(flagName) != 0) {
6622 flag |= stringToEnum(sFlagNameToEnumTable,
6623 ARRAY_SIZE(sFlagNameToEnumTable),
6624 flagName);
6625 }
6626 flagName = strtok(NULL, "|");
6627 }
6628 //force direct flag if offload flag is set: offloading implies a direct output stream
6629 // and all common behaviors are driven by checking only the direct flag
6630 // this should normally be set appropriately in the policy configuration file
6631 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6632 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6633 }
6634
6635 return (audio_output_flags_t)flag;
6636}
6637
Eric Laurente0720872014-03-11 09:30:41 -07006638audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006639{
6640 uint32_t device = 0;
6641
6642 char *devName = strtok(name, "|");
6643 while (devName != NULL) {
6644 if (strlen(devName) != 0) {
6645 device |= stringToEnum(sDeviceNameToEnumTable,
6646 ARRAY_SIZE(sDeviceNameToEnumTable),
6647 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006648 }
Eric Laurente552edb2014-03-10 17:42:56 -07006649 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006650 }
Eric Laurente552edb2014-03-10 17:42:56 -07006651 return device;
6652}
6653
Eric Laurente0720872014-03-11 09:30:41 -07006654void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006655{
Eric Laurente552edb2014-03-10 17:42:56 -07006656 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006657 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006658 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006659
Eric Laurent1afeecb2014-05-14 08:52:28 -07006660 node = config_find(root, DEVICES_TAG);
6661 if (node != NULL) {
6662 node = node->first_child;
6663 while (node) {
6664 ALOGV("loadHwModule() loading device %s", node->name);
6665 status_t tmpStatus = module->loadDevice(node);
6666 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6667 status = tmpStatus;
6668 }
6669 node = node->next;
6670 }
6671 }
6672 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006673 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006674 node = node->first_child;
6675 while (node) {
6676 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006677 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006678 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6679 status = tmpStatus;
6680 }
6681 node = node->next;
6682 }
6683 }
6684 node = config_find(root, INPUTS_TAG);
6685 if (node != NULL) {
6686 node = node->first_child;
6687 while (node) {
6688 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006689 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006690 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6691 status = tmpStatus;
6692 }
6693 node = node->next;
6694 }
6695 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006696 loadGlobalConfig(root, module);
6697
Eric Laurente552edb2014-03-10 17:42:56 -07006698 if (status == NO_ERROR) {
6699 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006700 }
6701}
6702
Eric Laurente0720872014-03-11 09:30:41 -07006703void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006704{
6705 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6706 if (node == NULL) {
6707 return;
6708 }
6709
6710 node = node->first_child;
6711 while (node) {
6712 ALOGV("loadHwModules() loading module %s", node->name);
6713 loadHwModule(node);
6714 node = node->next;
6715 }
6716}
6717
Eric Laurent1f2f2232014-06-02 12:01:23 -07006718void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006719{
6720 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006721
Eric Laurente552edb2014-03-10 17:42:56 -07006722 if (node == NULL) {
6723 return;
6724 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006725 DeviceVector declaredDevices;
6726 if (module != NULL) {
6727 declaredDevices = module->mDeclaredDevices;
6728 }
6729
Eric Laurente552edb2014-03-10 17:42:56 -07006730 node = node->first_child;
6731 while (node) {
6732 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006733 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6734 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006735 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6736 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006737 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006738 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006739 ARRAY_SIZE(sDeviceNameToEnumTable),
6740 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006741 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006742 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006743 } else {
6744 ALOGW("loadGlobalConfig() default device not specified");
6745 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006746 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006747 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006748 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6749 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006750 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006751 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6752 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6753 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006754 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6755 uint32_t major, minor;
6756 sscanf((char *)node->value, "%u.%u", &major, &minor);
6757 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6758 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6759 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006760 }
6761 node = node->next;
6762 }
6763}
6764
Eric Laurente0720872014-03-11 09:30:41 -07006765status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006766{
6767 cnode *root;
6768 char *data;
6769
6770 data = (char *)load_file(path, NULL);
6771 if (data == NULL) {
6772 return -ENODEV;
6773 }
6774 root = config_node("", "");
6775 config_load(root, data);
6776
Eric Laurente552edb2014-03-10 17:42:56 -07006777 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006778 // legacy audio_policy.conf files have one global_configuration section
6779 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006780 config_free(root);
6781 free(root);
6782 free(data);
6783
6784 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6785
6786 return NO_ERROR;
6787}
6788
Eric Laurente0720872014-03-11 09:30:41 -07006789void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006790{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006791 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006792 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006793 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6794 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006795 mAvailableOutputDevices.add(mDefaultOutputDevice);
6796 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006797
6798 module = new HwModule("primary");
6799
Eric Laurent1afeecb2014-05-14 08:52:28 -07006800 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006801 profile->mSamplingRates.add(44100);
6802 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6803 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006804 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006805 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6806 module->mOutputProfiles.add(profile);
6807
Eric Laurent1afeecb2014-05-14 08:52:28 -07006808 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006809 profile->mSamplingRates.add(8000);
6810 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6811 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006812 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006813 module->mInputProfiles.add(profile);
6814
6815 mHwModules.add(module);
6816}
6817
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006818audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6819{
6820 // flags to stream type mapping
6821 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6822 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6823 }
6824 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6825 return AUDIO_STREAM_BLUETOOTH_SCO;
6826 }
6827
6828 // usage to stream type mapping
6829 switch (attr->usage) {
6830 case AUDIO_USAGE_MEDIA:
6831 case AUDIO_USAGE_GAME:
6832 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6833 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6834 return AUDIO_STREAM_MUSIC;
6835 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6836 return AUDIO_STREAM_SYSTEM;
6837 case AUDIO_USAGE_VOICE_COMMUNICATION:
6838 return AUDIO_STREAM_VOICE_CALL;
6839
6840 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6841 return AUDIO_STREAM_DTMF;
6842
6843 case AUDIO_USAGE_ALARM:
6844 return AUDIO_STREAM_ALARM;
6845 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6846 return AUDIO_STREAM_RING;
6847
6848 case AUDIO_USAGE_NOTIFICATION:
6849 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6850 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6851 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6852 case AUDIO_USAGE_NOTIFICATION_EVENT:
6853 return AUDIO_STREAM_NOTIFICATION;
6854
6855 case AUDIO_USAGE_UNKNOWN:
6856 default:
6857 return AUDIO_STREAM_MUSIC;
6858 }
6859}
Eric Laurente552edb2014-03-10 17:42:56 -07006860}; // namespace android