blob: c5195939fb5411a1595aaebb061b7157c16fe473 [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 Laurent3a4311c2014-03-17 12:00:47 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
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();
306 for (size_t i = 0; i < mOutputs.size(); i++) {
307 // do not force device change on duplicated output because if device is 0, it will
308 // also force a device 0 for the two outputs it is duplicated to which may override
309 // a valid device selection on those outputs.
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700310 bool force = !mOutputs.valueAt(i)->isDuplicated()
311 && (!deviceDistinguishesOnAddress(device)
312 // always force when disconnecting (a non-duplicated device)
313 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurente552edb2014-03-10 17:42:56 -0700314 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700315 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700316 force, 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700317 }
318
Eric Laurent72aa32f2014-05-30 18:51:48 -0700319 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700320 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700321 } // end if is output device
322
Eric Laurente552edb2014-03-10 17:42:56 -0700323 // handle input devices
324 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700325 SortedVector <audio_io_handle_t> inputs;
326
Eric Laurent1afeecb2014-05-14 08:52:28 -0700327 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
328 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700329 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700330 switch (state)
331 {
332 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700333 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700334 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700335 ALOGW("setDeviceConnectionState() device already connected: %d", device);
336 return INVALID_OPERATION;
337 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700338 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700339 if (module == NULL) {
340 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
341 device);
342 return INVALID_OPERATION;
343 }
Eric Laurentd4692962014-05-05 18:13:44 -0700344 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
345 return INVALID_OPERATION;
346 }
347
Eric Laurent3a4311c2014-03-17 12:00:47 -0700348 index = mAvailableInputDevices.add(devDesc);
349 if (index >= 0) {
350 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700351 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700352 } else {
353 return NO_MEMORY;
354 }
Eric Laurentd4692962014-05-05 18:13:44 -0700355 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700356
357 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700358 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700360 ALOGW("setDeviceConnectionState() device not connected: %d", device);
361 return INVALID_OPERATION;
362 }
Eric Laurentd4692962014-05-05 18:13:44 -0700363 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700364 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700365 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700366
367 default:
368 ALOGE("setDeviceConnectionState() invalid state: %x", state);
369 return BAD_VALUE;
370 }
371
Eric Laurentd4692962014-05-05 18:13:44 -0700372 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700373
Eric Laurentb52c1522014-05-20 11:27:36 -0700374 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700375 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700376 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700377
378 ALOGW("setDeviceConnectionState() invalid device: %x", device);
379 return BAD_VALUE;
380}
381
Eric Laurente0720872014-03-11 09:30:41 -0700382audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700383 const char *device_address)
384{
Eric Laurent3b73df72014-03-11 09:06:29 -0700385 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700386 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700387 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 ssize_t index;
389 DeviceVector *deviceVector;
390
Eric Laurente552edb2014-03-10 17:42:56 -0700391 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700392 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700393 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700394 deviceVector = &mAvailableInputDevices;
395 } else {
396 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
397 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700398 }
399
Eric Laurent3a4311c2014-03-17 12:00:47 -0700400 index = deviceVector->indexOf(devDesc);
401 if (index >= 0) {
402 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
403 } else {
404 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
405 }
Eric Laurente552edb2014-03-10 17:42:56 -0700406}
407
Eric Laurente0720872014-03-11 09:30:41 -0700408void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700409{
410 ALOGV("setPhoneState() state %d", state);
411 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700412 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700413 ALOGW("setPhoneState() invalid state %d", state);
414 return;
415 }
416
417 if (state == mPhoneState ) {
418 ALOGW("setPhoneState() setting same state %d", state);
419 return;
420 }
421
422 // if leaving call state, handle special case of active streams
423 // pertaining to sonification strategy see handleIncallSonification()
424 if (isInCall()) {
425 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700426 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
427 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700428 }
429 }
430
431 // store previous phone state for management of sonification strategy below
432 int oldState = mPhoneState;
433 mPhoneState = state;
434 bool force = false;
435
436 // are we entering or starting a call
437 if (!isStateInCall(oldState) && isStateInCall(state)) {
438 ALOGV(" Entering call in setPhoneState()");
439 // force routing command to audio hardware when starting a call
440 // even if no device change is needed
441 force = true;
442 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
443 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
444 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
445 }
446 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
447 ALOGV(" Exiting call in setPhoneState()");
448 // force routing command to audio hardware when exiting a call
449 // even if no device change is needed
450 force = true;
451 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
452 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
453 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
454 }
455 } else if (isStateInCall(state) && (state != oldState)) {
456 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
457 // force routing command to audio hardware when switching between telephony and VoIP
458 // even if no device change is needed
459 force = true;
460 }
461
462 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700463 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700464 checkA2dpSuspend();
465 checkOutputForAllStrategies();
466 updateDevicesAndOutputs();
467
Eric Laurent1f2f2232014-06-02 12:01:23 -0700468 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700469
470 // force routing command to audio hardware when ending call
471 // even if no device change is needed
472 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
473 newDevice = hwOutputDesc->device();
474 }
475
476 int delayMs = 0;
477 if (isStateInCall(state)) {
478 nsecs_t sysTime = systemTime();
479 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700480 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700481 // mute media and sonification strategies and delay device switch by the largest
482 // latency of any output where either strategy is active.
483 // This avoid sending the ring tone or music tail into the earpiece or headset.
484 if ((desc->isStrategyActive(STRATEGY_MEDIA,
485 SONIFICATION_HEADSET_MUSIC_DELAY,
486 sysTime) ||
487 desc->isStrategyActive(STRATEGY_SONIFICATION,
488 SONIFICATION_HEADSET_MUSIC_DELAY,
489 sysTime)) &&
490 (delayMs < (int)desc->mLatency*2)) {
491 delayMs = desc->mLatency*2;
492 }
493 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
494 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
495 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
496 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
497 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
498 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
499 }
500 }
501
502 // change routing is necessary
503 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
504
505 // if entering in call state, handle special case of active streams
506 // pertaining to sonification strategy see handleIncallSonification()
507 if (isStateInCall(state)) {
508 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700509 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
510 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700511 }
512 }
513
514 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700515 if (state == AUDIO_MODE_RINGTONE &&
516 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700517 mLimitRingtoneVolume = true;
518 } else {
519 mLimitRingtoneVolume = false;
520 }
521}
522
Eric Laurente0720872014-03-11 09:30:41 -0700523void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700524 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700525{
526 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
527
528 bool forceVolumeReeval = false;
529 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700530 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
531 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
532 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700533 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
534 return;
535 }
536 forceVolumeReeval = true;
537 mForceUse[usage] = config;
538 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700539 case AUDIO_POLICY_FORCE_FOR_MEDIA:
540 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
541 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
542 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
543 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900544 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700545 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
546 return;
547 }
548 mForceUse[usage] = config;
549 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700550 case AUDIO_POLICY_FORCE_FOR_RECORD:
551 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
552 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700553 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
554 return;
555 }
556 mForceUse[usage] = config;
557 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700558 case AUDIO_POLICY_FORCE_FOR_DOCK:
559 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
560 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
561 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
562 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
563 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700564 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
565 }
566 forceVolumeReeval = true;
567 mForceUse[usage] = config;
568 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700569 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
570 if (config != AUDIO_POLICY_FORCE_NONE &&
571 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700572 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
573 }
574 forceVolumeReeval = true;
575 mForceUse[usage] = config;
576 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900577 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
578 if (config != AUDIO_POLICY_FORCE_NONE &&
579 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
580 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
581 }
582 mForceUse[usage] = config;
583 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700584 default:
585 ALOGW("setForceUse() invalid usage %d", usage);
586 break;
587 }
588
589 // check for device and output changes triggered by new force usage
590 checkA2dpSuspend();
591 checkOutputForAllStrategies();
592 updateDevicesAndOutputs();
593 for (size_t i = 0; i < mOutputs.size(); i++) {
594 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700595 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700596 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
597 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
598 applyStreamVolumes(output, newDevice, 0, true);
599 }
600 }
601
602 audio_io_handle_t activeInput = getActiveInput();
603 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700604 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700605 }
606
607}
608
Eric Laurente0720872014-03-11 09:30:41 -0700609audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700610{
611 return mForceUse[usage];
612}
613
Eric Laurente0720872014-03-11 09:30:41 -0700614void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700615{
616 ALOGV("setSystemProperty() property %s, value %s", property, value);
617}
618
619// Find a direct output profile compatible with the parameters passed, even if the input flags do
620// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700621sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700622 audio_devices_t device,
623 uint32_t samplingRate,
624 audio_format_t format,
625 audio_channel_mask_t channelMask,
626 audio_output_flags_t flags)
627{
628 for (size_t i = 0; i < mHwModules.size(); i++) {
629 if (mHwModules[i]->mHandle == 0) {
630 continue;
631 }
632 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700633 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700634 bool found = profile->isCompatibleProfile(device, samplingRate,
635 NULL /*updatedSamplingRate*/, format, channelMask,
636 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
637 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700638 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
639 return profile;
640 }
Eric Laurente552edb2014-03-10 17:42:56 -0700641 }
642 }
643 return 0;
644}
645
Eric Laurente0720872014-03-11 09:30:41 -0700646audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700647 uint32_t samplingRate,
648 audio_format_t format,
649 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700650 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700651 const audio_offload_info_t *offloadInfo)
652{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700653
Eric Laurent3b73df72014-03-11 09:06:29 -0700654 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700655 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
656 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
657 device, stream, samplingRate, format, channelMask, flags);
658
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700659 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
660 offloadInfo);
661}
662
663audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
664 uint32_t samplingRate,
665 audio_format_t format,
666 audio_channel_mask_t channelMask,
667 audio_output_flags_t flags,
668 const audio_offload_info_t *offloadInfo)
669{
670 if (attr == NULL) {
671 ALOGE("getOutputForAttr() called with NULL audio attributes");
672 return 0;
673 }
674 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
675 attr->usage, attr->content_type, attr->tags);
676
677 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
678 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
679 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
680 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
681 device, samplingRate, format, channelMask, flags);
682
683 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
684 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
685 offloadInfo);
686}
687
688audio_io_handle_t AudioPolicyManager::getOutputForDevice(
689 audio_devices_t device,
690 audio_stream_type_t stream,
691 uint32_t samplingRate,
692 audio_format_t format,
693 audio_channel_mask_t channelMask,
694 audio_output_flags_t flags,
695 const audio_offload_info_t *offloadInfo)
696{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700697 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700698 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700699 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700700
Eric Laurente552edb2014-03-10 17:42:56 -0700701#ifdef AUDIO_POLICY_TEST
702 if (mCurOutput != 0) {
703 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
704 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
705
706 if (mTestOutputs[mCurOutput] == 0) {
707 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700708 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700709 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700710 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700711 outputDesc->mFlags =
712 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700713 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700714 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
715 config.sample_rate = mTestSamplingRate;
716 config.channel_mask = mTestChannels;
717 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700718 if (offloadInfo != NULL) {
719 config.offload_info = *offloadInfo;
720 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700721 status = mpClientInterface->openOutput(0,
722 &mTestOutputs[mCurOutput],
723 &config,
724 &outputDesc->mDevice,
725 String8(""),
726 &outputDesc->mLatency,
727 outputDesc->mFlags);
728 if (status == NO_ERROR) {
729 outputDesc->mSamplingRate = config.sample_rate;
730 outputDesc->mFormat = config.format;
731 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700732 AudioParameter outputCmd = AudioParameter();
733 outputCmd.addInt(String8("set_id"),mCurOutput);
734 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
735 addOutput(mTestOutputs[mCurOutput], outputDesc);
736 }
737 }
738 return mTestOutputs[mCurOutput];
739 }
740#endif //AUDIO_POLICY_TEST
741
742 // open a direct output if required by specified parameters
743 //force direct flag if offload flag is set: offloading implies a direct output stream
744 // and all common behaviors are driven by checking only the direct flag
745 // this should normally be set appropriately in the policy configuration file
746 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700747 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700748 }
749
750 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
751 // creating an offloaded track and tearing it down immediately after start when audioflinger
752 // detects there is an active non offloadable effect.
753 // FIXME: We should check the audio session here but we do not have it in this context.
754 // This may prevent offloading in rare situations where effects are left active by apps
755 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700756 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700757 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
758 !isNonOffloadableEffectEnabled()) {
759 profile = getProfileForDirectOutput(device,
760 samplingRate,
761 format,
762 channelMask,
763 (audio_output_flags_t)flags);
764 }
765
Eric Laurent1c333e22014-05-20 10:48:17 -0700766 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700767 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700768
769 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700770 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700771 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
772 outputDesc = desc;
773 // reuse direct output if currently open and configured with same parameters
774 if ((samplingRate == outputDesc->mSamplingRate) &&
775 (format == outputDesc->mFormat) &&
776 (channelMask == outputDesc->mChannelMask)) {
777 outputDesc->mDirectOpenCount++;
778 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
779 return mOutputs.keyAt(i);
780 }
781 }
782 }
783 // close direct output if currently open and configured with different parameters
784 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700785 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700786 }
787 outputDesc = new AudioOutputDescriptor(profile);
788 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700789 outputDesc->mLatency = 0;
790 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700791 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
792 config.sample_rate = samplingRate;
793 config.channel_mask = channelMask;
794 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700795 if (offloadInfo != NULL) {
796 config.offload_info = *offloadInfo;
797 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700798 status = mpClientInterface->openOutput(profile->mModule->mHandle,
799 &output,
800 &config,
801 &outputDesc->mDevice,
802 String8(""),
803 &outputDesc->mLatency,
804 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700805
806 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700807 if (status != NO_ERROR ||
808 (samplingRate != 0 && samplingRate != config.sample_rate) ||
809 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
810 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700811 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
812 "format %d %d, channelMask %04x %04x", output, samplingRate,
813 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
814 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700815 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700816 mpClientInterface->closeOutput(output);
817 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700818 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700819 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700820 outputDesc->mSamplingRate = config.sample_rate;
821 outputDesc->mChannelMask = config.channel_mask;
822 outputDesc->mFormat = config.format;
823 outputDesc->mRefCount[stream] = 0;
824 outputDesc->mStopTime[stream] = 0;
825 outputDesc->mDirectOpenCount = 1;
826
Eric Laurente552edb2014-03-10 17:42:56 -0700827 audio_io_handle_t srcOutput = getOutputForEffect();
828 addOutput(output, outputDesc);
829 audio_io_handle_t dstOutput = getOutputForEffect();
830 if (dstOutput == output) {
831 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
832 }
833 mPreviousOutputs = mOutputs;
834 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700835 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700836 return output;
837 }
838
839 // ignoring channel mask due to downmix capability in mixer
840
841 // open a non direct output
842
843 // for non direct outputs, only PCM is supported
844 if (audio_is_linear_pcm(format)) {
845 // get which output is suitable for the specified stream. The actual
846 // routing change will happen when startOutput() will be called
847 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
848
849 output = selectOutput(outputs, flags);
850 }
851 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
852 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
853
854 ALOGV("getOutput() returns output %d", output);
855
856 return output;
857}
858
Eric Laurente0720872014-03-11 09:30:41 -0700859audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700860 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700861{
862 // select one output among several that provide a path to a particular device or set of
863 // devices (the list was previously build by getOutputsForDevice()).
864 // The priority is as follows:
865 // 1: the output with the highest number of requested policy flags
866 // 2: the primary output
867 // 3: the first output in the list
868
869 if (outputs.size() == 0) {
870 return 0;
871 }
872 if (outputs.size() == 1) {
873 return outputs[0];
874 }
875
876 int maxCommonFlags = 0;
877 audio_io_handle_t outputFlags = 0;
878 audio_io_handle_t outputPrimary = 0;
879
880 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700881 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700882 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700883 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700884 if (commonFlags > maxCommonFlags) {
885 outputFlags = outputs[i];
886 maxCommonFlags = commonFlags;
887 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
888 }
889 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
890 outputPrimary = outputs[i];
891 }
892 }
893 }
894
895 if (outputFlags != 0) {
896 return outputFlags;
897 }
898 if (outputPrimary != 0) {
899 return outputPrimary;
900 }
901
902 return outputs[0];
903}
904
Eric Laurente0720872014-03-11 09:30:41 -0700905status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700906 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700907 int session)
908{
909 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
910 ssize_t index = mOutputs.indexOfKey(output);
911 if (index < 0) {
912 ALOGW("startOutput() unknown output %d", output);
913 return BAD_VALUE;
914 }
915
Eric Laurent1f2f2232014-06-02 12:01:23 -0700916 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700917
918 // increment usage count for this stream on the requested output:
919 // NOTE that the usage count is the same for duplicated output and hardware output which is
920 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
921 outputDesc->changeRefCount(stream, 1);
922
923 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700924 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700925 routing_strategy strategy = getStrategy(stream);
926 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
927 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
928 uint32_t waitMs = 0;
929 bool force = false;
930 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700931 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700932 if (desc != outputDesc) {
933 // force a device change if any other output is managed by the same hw
934 // module and has a current device selection that differs from selected device.
935 // In this case, the audio HAL must receive the new device selection so that it can
936 // change the device currently selected by the other active output.
937 if (outputDesc->sharesHwModuleWith(desc) &&
938 desc->device() != newDevice) {
939 force = true;
940 }
941 // wait for audio on other active outputs to be presented when starting
942 // a notification so that audio focus effect can propagate.
943 uint32_t latency = desc->latency();
944 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
945 waitMs = latency;
946 }
947 }
948 }
949 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
950
951 // handle special case for sonification while in call
952 if (isInCall()) {
953 handleIncallSonification(stream, true, false);
954 }
955
956 // apply volume rules for current stream and device if necessary
957 checkAndSetVolume(stream,
958 mStreams[stream].getVolumeIndex(newDevice),
959 output,
960 newDevice);
961
962 // update the outputs if starting an output with a stream that can affect notification
963 // routing
964 handleNotificationRoutingForStream(stream);
965 if (waitMs > muteWaitMs) {
966 usleep((waitMs - muteWaitMs) * 2 * 1000);
967 }
968 }
969 return NO_ERROR;
970}
971
972
Eric Laurente0720872014-03-11 09:30:41 -0700973status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700974 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700975 int session)
976{
977 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
978 ssize_t index = mOutputs.indexOfKey(output);
979 if (index < 0) {
980 ALOGW("stopOutput() unknown output %d", output);
981 return BAD_VALUE;
982 }
983
Eric Laurent1f2f2232014-06-02 12:01:23 -0700984 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700985
986 // handle special case for sonification while in call
987 if (isInCall()) {
988 handleIncallSonification(stream, false, false);
989 }
990
991 if (outputDesc->mRefCount[stream] > 0) {
992 // decrement usage count of this stream on the output
993 outputDesc->changeRefCount(stream, -1);
994 // store time at which the stream was stopped - see isStreamActive()
995 if (outputDesc->mRefCount[stream] == 0) {
996 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700997 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700998 // delay the device switch by twice the latency because stopOutput() is executed when
999 // the track stop() command is received and at that time the audio track buffer can
1000 // still contain data that needs to be drained. The latency only covers the audio HAL
1001 // and kernel buffers. Also the latency does not always include additional delay in the
1002 // audio path (audio DSP, CODEC ...)
1003 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1004
1005 // force restoring the device selection on other active outputs if it differs from the
1006 // one being selected for this output
1007 for (size_t i = 0; i < mOutputs.size(); i++) {
1008 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001009 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001010 if (curOutput != output &&
1011 desc->isActive() &&
1012 outputDesc->sharesHwModuleWith(desc) &&
1013 (newDevice != desc->device())) {
1014 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001015 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001016 true,
1017 outputDesc->mLatency*2);
1018 }
1019 }
1020 // update the outputs if stopping one with a stream that can affect notification routing
1021 handleNotificationRoutingForStream(stream);
1022 }
1023 return NO_ERROR;
1024 } else {
1025 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1026 return INVALID_OPERATION;
1027 }
1028}
1029
Eric Laurente0720872014-03-11 09:30:41 -07001030void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001031{
1032 ALOGV("releaseOutput() %d", output);
1033 ssize_t index = mOutputs.indexOfKey(output);
1034 if (index < 0) {
1035 ALOGW("releaseOutput() releasing unknown output %d", output);
1036 return;
1037 }
1038
1039#ifdef AUDIO_POLICY_TEST
1040 int testIndex = testOutputIndex(output);
1041 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001042 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001043 if (outputDesc->isActive()) {
1044 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001045 mOutputs.removeItem(output);
1046 mTestOutputs[testIndex] = 0;
1047 }
1048 return;
1049 }
1050#endif //AUDIO_POLICY_TEST
1051
Eric Laurent1f2f2232014-06-02 12:01:23 -07001052 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001053 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001054 if (desc->mDirectOpenCount <= 0) {
1055 ALOGW("releaseOutput() invalid open count %d for output %d",
1056 desc->mDirectOpenCount, output);
1057 return;
1058 }
1059 if (--desc->mDirectOpenCount == 0) {
1060 closeOutput(output);
1061 // If effects where present on the output, audioflinger moved them to the primary
1062 // output by default: move them back to the appropriate output.
1063 audio_io_handle_t dstOutput = getOutputForEffect();
1064 if (dstOutput != mPrimaryOutput) {
1065 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1066 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001067 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001068 }
1069 }
1070}
1071
1072
Eric Laurente0720872014-03-11 09:30:41 -07001073audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001074 uint32_t samplingRate,
1075 audio_format_t format,
1076 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001077 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001078 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001079{
Eric Laurent4dc68062014-07-28 17:26:49 -07001080 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001081 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001082 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001083
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001084 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001085
1086 if (device == AUDIO_DEVICE_NONE) {
1087 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001088 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001089 }
1090
1091 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001092 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001093 case AUDIO_SOURCE_VOICE_UPLINK:
1094 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1095 break;
1096 case AUDIO_SOURCE_VOICE_DOWNLINK:
1097 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1098 break;
1099 case AUDIO_SOURCE_VOICE_CALL:
1100 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1101 break;
1102 default:
1103 break;
1104 }
1105
Eric Laurent1c333e22014-05-20 10:48:17 -07001106 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001107 samplingRate,
1108 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001109 channelMask,
1110 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001111 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001112 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1113 "channelMask 0x%X, flags %#x",
1114 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001115 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001116 }
1117
1118 if (profile->mModule->mHandle == 0) {
1119 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001120 return AUDIO_IO_HANDLE_NONE;
1121 }
1122
1123 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1124 config.sample_rate = samplingRate;
1125 config.channel_mask = channelMask;
1126 config.format = format;
1127 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001128
1129 bool isSoundTrigger = false;
1130 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1131 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1132 if (index >= 0) {
1133 input = mSoundTriggerSessions.valueFor(session);
1134 isSoundTrigger = true;
1135 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1136 }
1137 }
1138
Eric Laurentcf2c0212014-07-25 16:20:43 -07001139 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1140 &input,
1141 &config,
1142 &device,
1143 String8(""),
1144 inputSource,
1145 flags);
1146
1147 // only accept input with the exact requested set of parameters
1148 if (status != NO_ERROR ||
1149 (samplingRate != config.sample_rate) ||
1150 (format != config.format) ||
1151 (channelMask != config.channel_mask)) {
1152 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1153 samplingRate, format, channelMask);
1154 if (input != AUDIO_IO_HANDLE_NONE) {
1155 mpClientInterface->closeInput(input);
1156 }
1157 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001158 }
1159
Eric Laurent1f2f2232014-06-02 12:01:23 -07001160 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001161 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001162 inputDesc->mRefCount = 0;
1163 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001164 inputDesc->mSamplingRate = samplingRate;
1165 inputDesc->mFormat = format;
1166 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001167 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001168 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001169 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001170
Eric Laurentd4692962014-05-05 18:13:44 -07001171 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001172 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001173 return input;
1174}
1175
Eric Laurent4dc68062014-07-28 17:26:49 -07001176status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1177 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001178{
1179 ALOGV("startInput() input %d", input);
1180 ssize_t index = mInputs.indexOfKey(input);
1181 if (index < 0) {
1182 ALOGW("startInput() unknown input %d", input);
1183 return BAD_VALUE;
1184 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001185 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001186
Eric Laurent4dc68062014-07-28 17:26:49 -07001187 index = inputDesc->mSessions.indexOf(session);
1188 if (index < 0) {
1189 ALOGW("startInput() unknown session %d on input %d", session, input);
1190 return BAD_VALUE;
1191 }
1192
Glenn Kasten74a8e252014-07-24 14:09:55 -07001193 // virtual input devices are compatible with other input devices
1194 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1195
1196 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001197 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001198 if (activeInput != 0 && activeInput != input) {
1199
1200 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1201 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001202 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001203 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001204 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001205 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1206 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001207 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001208 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001209 return INVALID_OPERATION;
1210 }
1211 }
1212 }
1213
Glenn Kasten74a8e252014-07-24 14:09:55 -07001214 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001215 if (activeInputsCount() == 0) {
1216 SoundTrigger::setCaptureState(true);
1217 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001218 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001219
Glenn Kasten74a8e252014-07-24 14:09:55 -07001220 // Automatically enable the remote submix output when input is started.
1221 // For remote submix (a virtual device), we open only one input per capture request.
1222 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1223 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1224 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1225 }
Eric Laurente552edb2014-03-10 17:42:56 -07001226 }
1227
Eric Laurente552edb2014-03-10 17:42:56 -07001228 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1229
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001230 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001231 return NO_ERROR;
1232}
1233
Eric Laurent4dc68062014-07-28 17:26:49 -07001234status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1235 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001236{
1237 ALOGV("stopInput() input %d", input);
1238 ssize_t index = mInputs.indexOfKey(input);
1239 if (index < 0) {
1240 ALOGW("stopInput() unknown input %d", input);
1241 return BAD_VALUE;
1242 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001243 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001244
Eric Laurent4dc68062014-07-28 17:26:49 -07001245 index = inputDesc->mSessions.indexOf(session);
1246 if (index < 0) {
1247 ALOGW("stopInput() unknown session %d on input %d", session, input);
1248 return BAD_VALUE;
1249 }
1250
Eric Laurente552edb2014-03-10 17:42:56 -07001251 if (inputDesc->mRefCount == 0) {
1252 ALOGW("stopInput() input %d already stopped", input);
1253 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001254 }
1255
1256 inputDesc->mRefCount--;
1257 if (inputDesc->mRefCount == 0) {
1258
Eric Laurente552edb2014-03-10 17:42:56 -07001259 // automatically disable the remote submix output when input is stopped
1260 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1261 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001262 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001263 }
1264
Eric Laurent1c333e22014-05-20 10:48:17 -07001265 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001266
1267 if (activeInputsCount() == 0) {
1268 SoundTrigger::setCaptureState(false);
1269 }
Eric Laurente552edb2014-03-10 17:42:56 -07001270 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001271 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001272}
1273
Eric Laurent4dc68062014-07-28 17:26:49 -07001274void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1275 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001276{
1277 ALOGV("releaseInput() %d", input);
1278 ssize_t index = mInputs.indexOfKey(input);
1279 if (index < 0) {
1280 ALOGW("releaseInput() releasing unknown input %d", input);
1281 return;
1282 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001283 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1284 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001285
1286 index = inputDesc->mSessions.indexOf(session);
1287 if (index < 0) {
1288 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1289 return;
1290 }
1291 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001292 if (inputDesc->mOpenRefCount == 0) {
1293 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1294 return;
1295 }
1296 inputDesc->mOpenRefCount--;
1297 if (inputDesc->mOpenRefCount > 0) {
1298 ALOGV("releaseInput() exit > 0");
1299 return;
1300 }
1301
Eric Laurente552edb2014-03-10 17:42:56 -07001302 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001303 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001304 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001305 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001306 ALOGV("releaseInput() exit");
1307}
1308
Eric Laurentd4692962014-05-05 18:13:44 -07001309void AudioPolicyManager::closeAllInputs() {
1310 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1311 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1312 }
1313 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001314 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001315}
1316
Eric Laurente0720872014-03-11 09:30:41 -07001317void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001318 int indexMin,
1319 int indexMax)
1320{
1321 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1322 if (indexMin < 0 || indexMin >= indexMax) {
1323 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1324 return;
1325 }
1326 mStreams[stream].mIndexMin = indexMin;
1327 mStreams[stream].mIndexMax = indexMax;
1328}
1329
Eric Laurente0720872014-03-11 09:30:41 -07001330status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001331 int index,
1332 audio_devices_t device)
1333{
1334
1335 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1336 return BAD_VALUE;
1337 }
1338 if (!audio_is_output_device(device)) {
1339 return BAD_VALUE;
1340 }
1341
1342 // Force max volume if stream cannot be muted
1343 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1344
1345 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1346 stream, device, index);
1347
1348 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1349 // clear all device specific values
1350 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1351 mStreams[stream].mIndexCur.clear();
1352 }
1353 mStreams[stream].mIndexCur.add(device, index);
1354
1355 // compute and apply stream volume on all outputs according to connected device
1356 status_t status = NO_ERROR;
1357 for (size_t i = 0; i < mOutputs.size(); i++) {
1358 audio_devices_t curDevice =
1359 getDeviceForVolume(mOutputs.valueAt(i)->device());
1360 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1361 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1362 if (volStatus != NO_ERROR) {
1363 status = volStatus;
1364 }
1365 }
1366 }
1367 return status;
1368}
1369
Eric Laurente0720872014-03-11 09:30:41 -07001370status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001371 int *index,
1372 audio_devices_t device)
1373{
1374 if (index == NULL) {
1375 return BAD_VALUE;
1376 }
1377 if (!audio_is_output_device(device)) {
1378 return BAD_VALUE;
1379 }
1380 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1381 // the strategy the stream belongs to.
1382 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1383 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1384 }
1385 device = getDeviceForVolume(device);
1386
1387 *index = mStreams[stream].getVolumeIndex(device);
1388 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1389 return NO_ERROR;
1390}
1391
Eric Laurente0720872014-03-11 09:30:41 -07001392audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001393 const SortedVector<audio_io_handle_t>& outputs)
1394{
1395 // select one output among several suitable for global effects.
1396 // The priority is as follows:
1397 // 1: An offloaded output. If the effect ends up not being offloadable,
1398 // AudioFlinger will invalidate the track and the offloaded output
1399 // will be closed causing the effect to be moved to a PCM output.
1400 // 2: A deep buffer output
1401 // 3: the first output in the list
1402
1403 if (outputs.size() == 0) {
1404 return 0;
1405 }
1406
1407 audio_io_handle_t outputOffloaded = 0;
1408 audio_io_handle_t outputDeepBuffer = 0;
1409
1410 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001411 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001412 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001413 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1414 outputOffloaded = outputs[i];
1415 }
1416 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1417 outputDeepBuffer = outputs[i];
1418 }
1419 }
1420
1421 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1422 outputOffloaded, outputDeepBuffer);
1423 if (outputOffloaded != 0) {
1424 return outputOffloaded;
1425 }
1426 if (outputDeepBuffer != 0) {
1427 return outputDeepBuffer;
1428 }
1429
1430 return outputs[0];
1431}
1432
Eric Laurente0720872014-03-11 09:30:41 -07001433audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001434{
1435 // apply simple rule where global effects are attached to the same output as MUSIC streams
1436
Eric Laurent3b73df72014-03-11 09:06:29 -07001437 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001438 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1439 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1440
1441 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1442 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1443 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1444
1445 return output;
1446}
1447
Eric Laurente0720872014-03-11 09:30:41 -07001448status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001449 audio_io_handle_t io,
1450 uint32_t strategy,
1451 int session,
1452 int id)
1453{
1454 ssize_t index = mOutputs.indexOfKey(io);
1455 if (index < 0) {
1456 index = mInputs.indexOfKey(io);
1457 if (index < 0) {
1458 ALOGW("registerEffect() unknown io %d", io);
1459 return INVALID_OPERATION;
1460 }
1461 }
1462
1463 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1464 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1465 desc->name, desc->memoryUsage);
1466 return INVALID_OPERATION;
1467 }
1468 mTotalEffectsMemory += desc->memoryUsage;
1469 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1470 desc->name, io, strategy, session, id);
1471 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1472
Eric Laurent1f2f2232014-06-02 12:01:23 -07001473 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1474 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1475 effectDesc->mIo = io;
1476 effectDesc->mStrategy = (routing_strategy)strategy;
1477 effectDesc->mSession = session;
1478 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001479
Eric Laurent1f2f2232014-06-02 12:01:23 -07001480 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001481
1482 return NO_ERROR;
1483}
1484
Eric Laurente0720872014-03-11 09:30:41 -07001485status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001486{
1487 ssize_t index = mEffects.indexOfKey(id);
1488 if (index < 0) {
1489 ALOGW("unregisterEffect() unknown effect ID %d", id);
1490 return INVALID_OPERATION;
1491 }
1492
Eric Laurent1f2f2232014-06-02 12:01:23 -07001493 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001494
Eric Laurent1f2f2232014-06-02 12:01:23 -07001495 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001496
Eric Laurent1f2f2232014-06-02 12:01:23 -07001497 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001498 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001499 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1500 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001501 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001502 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001503 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001504 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001505
1506 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001507
1508 return NO_ERROR;
1509}
1510
Eric Laurente0720872014-03-11 09:30:41 -07001511status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001512{
1513 ssize_t index = mEffects.indexOfKey(id);
1514 if (index < 0) {
1515 ALOGW("unregisterEffect() unknown effect ID %d", id);
1516 return INVALID_OPERATION;
1517 }
1518
1519 return setEffectEnabled(mEffects.valueAt(index), enabled);
1520}
1521
Eric Laurent1f2f2232014-06-02 12:01:23 -07001522status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001523{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001524 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001525 ALOGV("setEffectEnabled(%s) effect already %s",
1526 enabled?"true":"false", enabled?"enabled":"disabled");
1527 return INVALID_OPERATION;
1528 }
1529
1530 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001531 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001532 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001533 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001534 return INVALID_OPERATION;
1535 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001536 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001537 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1538 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001539 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001540 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001541 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1542 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001543 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001544 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001545 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1546 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001547 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001548 return NO_ERROR;
1549}
1550
Eric Laurente0720872014-03-11 09:30:41 -07001551bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001552{
1553 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001554 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1555 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1556 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001557 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001558 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001559 return true;
1560 }
1561 }
1562 return false;
1563}
1564
Eric Laurente0720872014-03-11 09:30:41 -07001565bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001566{
1567 nsecs_t sysTime = systemTime();
1568 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001569 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001570 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001571 return true;
1572 }
1573 }
1574 return false;
1575}
1576
Eric Laurente0720872014-03-11 09:30:41 -07001577bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001578 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001579{
1580 nsecs_t sysTime = systemTime();
1581 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001582 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001583 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001584 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001585 return true;
1586 }
1587 }
1588 return false;
1589}
1590
Eric Laurente0720872014-03-11 09:30:41 -07001591bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001592{
1593 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001594 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001595 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001596 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001597 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1598 && (inputDescriptor->mRefCount > 0)) {
1599 return true;
1600 }
1601 }
1602 return false;
1603}
1604
1605
Eric Laurente0720872014-03-11 09:30:41 -07001606status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001607{
1608 const size_t SIZE = 256;
1609 char buffer[SIZE];
1610 String8 result;
1611
1612 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1613 result.append(buffer);
1614
1615 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1616 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001617 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1618 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001619 snprintf(buffer, SIZE, " Force use for communications %d\n",
1620 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001621 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001622 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001623 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001624 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001625 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001626 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001627 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001628 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001629 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001630 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1631 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1632 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001633
Eric Laurent3a4311c2014-03-17 12:00:47 -07001634 snprintf(buffer, SIZE, " Available output devices:\n");
1635 result.append(buffer);
1636 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001637 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001638 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001639 }
1640 snprintf(buffer, SIZE, "\n Available input devices:\n");
1641 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001642 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001643 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001644 }
Eric Laurente552edb2014-03-10 17:42:56 -07001645
1646 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1647 write(fd, buffer, strlen(buffer));
1648 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001649 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001650 write(fd, buffer, strlen(buffer));
1651 mHwModules[i]->dump(fd);
1652 }
1653
1654 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1655 write(fd, buffer, strlen(buffer));
1656 for (size_t i = 0; i < mOutputs.size(); i++) {
1657 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1658 write(fd, buffer, strlen(buffer));
1659 mOutputs.valueAt(i)->dump(fd);
1660 }
1661
1662 snprintf(buffer, SIZE, "\nInputs dump:\n");
1663 write(fd, buffer, strlen(buffer));
1664 for (size_t i = 0; i < mInputs.size(); i++) {
1665 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1666 write(fd, buffer, strlen(buffer));
1667 mInputs.valueAt(i)->dump(fd);
1668 }
1669
1670 snprintf(buffer, SIZE, "\nStreams dump:\n");
1671 write(fd, buffer, strlen(buffer));
1672 snprintf(buffer, SIZE,
1673 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1674 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001675 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001676 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001677 write(fd, buffer, strlen(buffer));
1678 mStreams[i].dump(fd);
1679 }
1680
1681 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1682 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1683 write(fd, buffer, strlen(buffer));
1684
1685 snprintf(buffer, SIZE, "Registered effects:\n");
1686 write(fd, buffer, strlen(buffer));
1687 for (size_t i = 0; i < mEffects.size(); i++) {
1688 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1689 write(fd, buffer, strlen(buffer));
1690 mEffects.valueAt(i)->dump(fd);
1691 }
1692
1693
1694 return NO_ERROR;
1695}
1696
1697// This function checks for the parameters which can be offloaded.
1698// This can be enhanced depending on the capability of the DSP and policy
1699// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001700bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001701{
1702 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001703 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001704 offloadInfo.sample_rate, offloadInfo.channel_mask,
1705 offloadInfo.format,
1706 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1707 offloadInfo.has_video);
1708
1709 // Check if offload has been disabled
1710 char propValue[PROPERTY_VALUE_MAX];
1711 if (property_get("audio.offload.disable", propValue, "0")) {
1712 if (atoi(propValue) != 0) {
1713 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1714 return false;
1715 }
1716 }
1717
1718 // Check if stream type is music, then only allow offload as of now.
1719 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1720 {
1721 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1722 return false;
1723 }
1724
1725 //TODO: enable audio offloading with video when ready
1726 if (offloadInfo.has_video)
1727 {
1728 ALOGV("isOffloadSupported: has_video == true, returning false");
1729 return false;
1730 }
1731
1732 //If duration is less than minimum value defined in property, return false
1733 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1734 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1735 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1736 return false;
1737 }
1738 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1739 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1740 return false;
1741 }
1742
1743 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1744 // creating an offloaded track and tearing it down immediately after start when audioflinger
1745 // detects there is an active non offloadable effect.
1746 // FIXME: We should check the audio session here but we do not have it in this context.
1747 // This may prevent offloading in rare situations where effects are left active by apps
1748 // in the background.
1749 if (isNonOffloadableEffectEnabled()) {
1750 return false;
1751 }
1752
1753 // See if there is a profile to support this.
1754 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001755 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001756 offloadInfo.sample_rate,
1757 offloadInfo.format,
1758 offloadInfo.channel_mask,
1759 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001760 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1761 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001762}
1763
Eric Laurent6a94d692014-05-20 11:18:06 -07001764status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1765 audio_port_type_t type,
1766 unsigned int *num_ports,
1767 struct audio_port *ports,
1768 unsigned int *generation)
1769{
1770 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1771 generation == NULL) {
1772 return BAD_VALUE;
1773 }
1774 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1775 if (ports == NULL) {
1776 *num_ports = 0;
1777 }
1778
1779 size_t portsWritten = 0;
1780 size_t portsMax = *num_ports;
1781 *num_ports = 0;
1782 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1783 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1784 for (size_t i = 0;
1785 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1786 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1787 }
1788 *num_ports += mAvailableOutputDevices.size();
1789 }
1790 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1791 for (size_t i = 0;
1792 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1793 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1794 }
1795 *num_ports += mAvailableInputDevices.size();
1796 }
1797 }
1798 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1799 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1800 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1801 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1802 }
1803 *num_ports += mInputs.size();
1804 }
1805 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001806 size_t numOutputs = 0;
1807 for (size_t i = 0; i < mOutputs.size(); i++) {
1808 if (!mOutputs[i]->isDuplicated()) {
1809 numOutputs++;
1810 if (portsWritten < portsMax) {
1811 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1812 }
1813 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001814 }
Eric Laurent84c70242014-06-23 08:46:27 -07001815 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001816 }
1817 }
1818 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001819 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001820 return NO_ERROR;
1821}
1822
1823status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1824{
1825 return NO_ERROR;
1826}
1827
Eric Laurent1f2f2232014-06-02 12:01:23 -07001828sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001829 audio_port_handle_t id) const
1830{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001831 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001832 for (size_t i = 0; i < mOutputs.size(); i++) {
1833 outputDesc = mOutputs.valueAt(i);
1834 if (outputDesc->mId == id) {
1835 break;
1836 }
1837 }
1838 return outputDesc;
1839}
1840
Eric Laurent1f2f2232014-06-02 12:01:23 -07001841sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001842 audio_port_handle_t id) const
1843{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001844 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001845 for (size_t i = 0; i < mInputs.size(); i++) {
1846 inputDesc = mInputs.valueAt(i);
1847 if (inputDesc->mId == id) {
1848 break;
1849 }
1850 }
1851 return inputDesc;
1852}
1853
Eric Laurent1f2f2232014-06-02 12:01:23 -07001854sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1855 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001856{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001857 sp <HwModule> module;
1858
Eric Laurent6a94d692014-05-20 11:18:06 -07001859 for (size_t i = 0; i < mHwModules.size(); i++) {
1860 if (mHwModules[i]->mHandle == 0) {
1861 continue;
1862 }
1863 if (audio_is_output_device(device)) {
1864 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1865 {
1866 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1867 return mHwModules[i];
1868 }
1869 }
1870 } else {
1871 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1872 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1873 device & ~AUDIO_DEVICE_BIT_IN) {
1874 return mHwModules[i];
1875 }
1876 }
1877 }
1878 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001879 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001880}
1881
Eric Laurent1f2f2232014-06-02 12:01:23 -07001882sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001883{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001884 sp <HwModule> module;
1885
Eric Laurent1afeecb2014-05-14 08:52:28 -07001886 for (size_t i = 0; i < mHwModules.size(); i++)
1887 {
1888 if (strcmp(mHwModules[i]->mName, name) == 0) {
1889 return mHwModules[i];
1890 }
1891 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001892 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001893}
1894
1895
Eric Laurent6a94d692014-05-20 11:18:06 -07001896status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1897 audio_patch_handle_t *handle,
1898 uid_t uid)
1899{
1900 ALOGV("createAudioPatch()");
1901
1902 if (handle == NULL || patch == NULL) {
1903 return BAD_VALUE;
1904 }
1905 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1906
1907 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1908 return INVALID_OPERATION;
1909 }
1910 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1911 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1912 return INVALID_OPERATION;
1913 }
1914
1915 sp<AudioPatch> patchDesc;
1916 ssize_t index = mAudioPatches.indexOfKey(*handle);
1917
1918 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1919 patch->sinks[0].type);
1920 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1921 patch->sources[0].role,
1922 patch->sources[0].type);
1923
1924 if (index >= 0) {
1925 patchDesc = mAudioPatches.valueAt(index);
1926 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1927 mUidCached, patchDesc->mUid, uid);
1928 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1929 return INVALID_OPERATION;
1930 }
1931 } else {
1932 *handle = 0;
1933 }
1934
1935 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1936 // TODO add support for mix to mix connection
1937 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1938 ALOGV("createAudioPatch() source mix sink not device");
1939 return BAD_VALUE;
1940 }
1941 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001942 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001943 if (outputDesc == NULL) {
1944 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1945 return BAD_VALUE;
1946 }
Eric Laurent84c70242014-06-23 08:46:27 -07001947 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1948 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001949 if (patchDesc != 0) {
1950 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1951 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1952 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1953 return BAD_VALUE;
1954 }
1955 }
1956 sp<DeviceDescriptor> devDesc =
1957 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1958 if (devDesc == 0) {
1959 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1960 return BAD_VALUE;
1961 }
1962
Eric Laurent84c70242014-06-23 08:46:27 -07001963 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001964 patch->sources[0].sample_rate,
Glenn Kastencbd48022014-07-24 13:46:44 -07001965 NULL, // updatedSamplingRate
Eric Laurent6a94d692014-05-20 11:18:06 -07001966 patch->sources[0].format,
1967 patch->sources[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001968 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Eric Laurent83b88082014-06-20 18:31:16 -07001969 ALOGV("createAudioPatch() profile not supported");
Eric Laurent6a94d692014-05-20 11:18:06 -07001970 return INVALID_OPERATION;
1971 }
1972 // TODO: reconfigure output format and channels here
1973 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001974 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001975 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001976 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001977 true,
1978 0,
1979 handle);
1980 index = mAudioPatches.indexOfKey(*handle);
1981 if (index >= 0) {
1982 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1983 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1984 }
1985 patchDesc = mAudioPatches.valueAt(index);
1986 patchDesc->mUid = uid;
1987 ALOGV("createAudioPatch() success");
1988 } else {
1989 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1990 return INVALID_OPERATION;
1991 }
1992 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1993 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1994 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001995 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001996 if (inputDesc == NULL) {
1997 return BAD_VALUE;
1998 }
1999 if (patchDesc != 0) {
2000 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2001 return BAD_VALUE;
2002 }
2003 }
2004 sp<DeviceDescriptor> devDesc =
2005 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2006 if (devDesc == 0) {
2007 return BAD_VALUE;
2008 }
2009
Eric Laurent84c70242014-06-23 08:46:27 -07002010 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002011 patch->sinks[0].sample_rate,
2012 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002013 patch->sinks[0].format,
2014 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002015 // FIXME for the parameter type,
2016 // and the NONE
2017 (audio_output_flags_t)
2018 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002019 return INVALID_OPERATION;
2020 }
2021 // TODO: reconfigure output format and channels here
2022 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002023 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002024 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07002025 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07002026 true,
2027 handle);
2028 index = mAudioPatches.indexOfKey(*handle);
2029 if (index >= 0) {
2030 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2031 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2032 }
2033 patchDesc = mAudioPatches.valueAt(index);
2034 patchDesc->mUid = uid;
2035 ALOGV("createAudioPatch() success");
2036 } else {
2037 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2038 return INVALID_OPERATION;
2039 }
2040 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2041 // device to device connection
2042 if (patchDesc != 0) {
2043 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
2044 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2045 return BAD_VALUE;
2046 }
2047 }
2048
2049 sp<DeviceDescriptor> srcDeviceDesc =
2050 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2051 sp<DeviceDescriptor> sinkDeviceDesc =
2052 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
2053 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
2054 return BAD_VALUE;
2055 }
2056 //update source and sink with our own data as the data passed in the patch may
2057 // be incomplete.
2058 struct audio_patch newPatch = *patch;
2059 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
2060 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
2061
Eric Laurent6a94d692014-05-20 11:18:06 -07002062 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
Eric Laurent83b88082014-06-20 18:31:16 -07002063 SortedVector<audio_io_handle_t> outputs =
2064 getOutputsForDevice(sinkDeviceDesc->mDeviceType, mOutputs);
2065 // if the sink device is reachable via an opened output stream, request to go via
2066 // this output stream by adding a second source to the patch description
2067 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2068 if (output != AUDIO_IO_HANDLE_NONE) {
2069 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2070 if (outputDesc->isDuplicated()) {
2071 return INVALID_OPERATION;
2072 }
2073 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2074 newPatch.num_sources = 2;
2075 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002076 }
2077 // TODO: check from routing capabilities in config file and other conflicting patches
2078
2079 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2080 if (index >= 0) {
2081 afPatchHandle = patchDesc->mAfPatchHandle;
2082 }
2083
2084 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2085 &afPatchHandle,
2086 0);
2087 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2088 status, afPatchHandle);
2089 if (status == NO_ERROR) {
2090 if (index < 0) {
2091 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2092 &newPatch, uid);
2093 addAudioPatch(patchDesc->mHandle, patchDesc);
2094 } else {
2095 patchDesc->mPatch = newPatch;
2096 }
2097 patchDesc->mAfPatchHandle = afPatchHandle;
2098 *handle = patchDesc->mHandle;
2099 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002100 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002101 } else {
2102 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2103 status);
2104 return INVALID_OPERATION;
2105 }
2106 } else {
2107 return BAD_VALUE;
2108 }
2109 } else {
2110 return BAD_VALUE;
2111 }
2112 return NO_ERROR;
2113}
2114
2115status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2116 uid_t uid)
2117{
2118 ALOGV("releaseAudioPatch() patch %d", handle);
2119
2120 ssize_t index = mAudioPatches.indexOfKey(handle);
2121
2122 if (index < 0) {
2123 return BAD_VALUE;
2124 }
2125 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2126 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2127 mUidCached, patchDesc->mUid, uid);
2128 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2129 return INVALID_OPERATION;
2130 }
2131
2132 struct audio_patch *patch = &patchDesc->mPatch;
2133 patchDesc->mUid = mUidCached;
2134 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002135 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002136 if (outputDesc == NULL) {
2137 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2138 return BAD_VALUE;
2139 }
2140
2141 setOutputDevice(outputDesc->mIoHandle,
2142 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2143 true,
2144 0,
2145 NULL);
2146 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2147 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002148 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002149 if (inputDesc == NULL) {
2150 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2151 return BAD_VALUE;
2152 }
2153 setInputDevice(inputDesc->mIoHandle,
2154 getNewInputDevice(inputDesc->mIoHandle),
2155 true,
2156 NULL);
2157 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2158 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2159 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2160 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2161 status, patchDesc->mAfPatchHandle);
2162 removeAudioPatch(patchDesc->mHandle);
2163 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002164 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002165 } else {
2166 return BAD_VALUE;
2167 }
2168 } else {
2169 return BAD_VALUE;
2170 }
2171 return NO_ERROR;
2172}
2173
2174status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2175 struct audio_patch *patches,
2176 unsigned int *generation)
2177{
2178 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2179 generation == NULL) {
2180 return BAD_VALUE;
2181 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002182 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002183 *num_patches, patches, mAudioPatches.size());
2184 if (patches == NULL) {
2185 *num_patches = 0;
2186 }
2187
2188 size_t patchesWritten = 0;
2189 size_t patchesMax = *num_patches;
2190 for (size_t i = 0;
2191 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2192 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2193 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002194 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002195 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2196 }
2197 *num_patches = mAudioPatches.size();
2198
2199 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002200 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002201 return NO_ERROR;
2202}
2203
Eric Laurente1715a42014-05-20 11:30:42 -07002204status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002205{
Eric Laurente1715a42014-05-20 11:30:42 -07002206 ALOGV("setAudioPortConfig()");
2207
2208 if (config == NULL) {
2209 return BAD_VALUE;
2210 }
2211 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2212 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002213 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2214 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002215 }
2216
Eric Laurenta121f902014-06-03 13:32:54 -07002217 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002218 if (config->type == AUDIO_PORT_TYPE_MIX) {
2219 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002220 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002221 if (outputDesc == NULL) {
2222 return BAD_VALUE;
2223 }
Eric Laurent84c70242014-06-23 08:46:27 -07002224 ALOG_ASSERT(!outputDesc->isDuplicated(),
2225 "setAudioPortConfig() called on duplicated output %d",
2226 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002227 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002228 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002229 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002230 if (inputDesc == NULL) {
2231 return BAD_VALUE;
2232 }
Eric Laurenta121f902014-06-03 13:32:54 -07002233 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002234 } else {
2235 return BAD_VALUE;
2236 }
2237 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2238 sp<DeviceDescriptor> deviceDesc;
2239 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2240 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2241 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2242 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2243 } else {
2244 return BAD_VALUE;
2245 }
2246 if (deviceDesc == NULL) {
2247 return BAD_VALUE;
2248 }
Eric Laurenta121f902014-06-03 13:32:54 -07002249 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002250 } else {
2251 return BAD_VALUE;
2252 }
2253
Eric Laurenta121f902014-06-03 13:32:54 -07002254 struct audio_port_config backupConfig;
2255 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2256 if (status == NO_ERROR) {
2257 struct audio_port_config newConfig;
2258 audioPortConfig->toAudioPortConfig(&newConfig, config);
2259 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002260 }
Eric Laurenta121f902014-06-03 13:32:54 -07002261 if (status != NO_ERROR) {
2262 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002263 }
Eric Laurente1715a42014-05-20 11:30:42 -07002264
2265 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002266}
2267
2268void AudioPolicyManager::clearAudioPatches(uid_t uid)
2269{
2270 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2271 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2272 if (patchDesc->mUid == uid) {
2273 // releaseAudioPatch() removes the patch from mAudioPatches
2274 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2275 i--;
2276 }
2277 }
2278 }
2279}
2280
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002281status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2282 audio_io_handle_t *ioHandle,
2283 audio_devices_t *device)
2284{
2285 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2286 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2287 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2288
2289 mSoundTriggerSessions.add(*session, *ioHandle);
2290
2291 return NO_ERROR;
2292}
2293
2294status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2295{
2296 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2297 if (index < 0) {
2298 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2299 return BAD_VALUE;
2300 }
2301
2302 mSoundTriggerSessions.removeItem(session);
2303 return NO_ERROR;
2304}
2305
Eric Laurent6a94d692014-05-20 11:18:06 -07002306status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2307 const sp<AudioPatch>& patch)
2308{
2309 ssize_t index = mAudioPatches.indexOfKey(handle);
2310
2311 if (index >= 0) {
2312 ALOGW("addAudioPatch() patch %d already in", handle);
2313 return ALREADY_EXISTS;
2314 }
2315 mAudioPatches.add(handle, patch);
2316 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2317 "sink handle %d",
2318 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2319 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2320 return NO_ERROR;
2321}
2322
2323status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2324{
2325 ssize_t index = mAudioPatches.indexOfKey(handle);
2326
2327 if (index < 0) {
2328 ALOGW("removeAudioPatch() patch %d not in", handle);
2329 return ALREADY_EXISTS;
2330 }
2331 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2332 mAudioPatches.valueAt(index)->mAfPatchHandle);
2333 mAudioPatches.removeItemsAt(index);
2334 return NO_ERROR;
2335}
2336
Eric Laurente552edb2014-03-10 17:42:56 -07002337// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002338// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002339// ----------------------------------------------------------------------------
2340
Eric Laurent3a4311c2014-03-17 12:00:47 -07002341uint32_t AudioPolicyManager::nextUniqueId()
2342{
2343 return android_atomic_inc(&mNextUniqueId);
2344}
2345
Eric Laurent6a94d692014-05-20 11:18:06 -07002346uint32_t AudioPolicyManager::nextAudioPortGeneration()
2347{
2348 return android_atomic_inc(&mAudioPortGeneration);
2349}
2350
Eric Laurente0720872014-03-11 09:30:41 -07002351AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002352 :
2353#ifdef AUDIO_POLICY_TEST
2354 Thread(false),
2355#endif //AUDIO_POLICY_TEST
2356 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002357 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002358 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2359 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002360 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002361 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2362 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002363{
Eric Laurent6a94d692014-05-20 11:18:06 -07002364 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002365 mpClientInterface = clientInterface;
2366
Eric Laurent3b73df72014-03-11 09:06:29 -07002367 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2368 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002369 }
2370
Eric Laurent1afeecb2014-05-14 08:52:28 -07002371 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002372 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2373 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2374 ALOGE("could not load audio policy configuration file, setting defaults");
2375 defaultAudioPolicyConfig();
2376 }
2377 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002378 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002379
2380 // must be done after reading the policy
2381 initializeVolumeCurves();
2382
2383 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002384 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2385 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002386 for (size_t i = 0; i < mHwModules.size(); i++) {
2387 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2388 if (mHwModules[i]->mHandle == 0) {
2389 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2390 continue;
2391 }
2392 // open all output streams needed to access attached devices
2393 // except for direct output streams that are only opened when they are actually
2394 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002395 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002396 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2397 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002398 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002399
Eric Laurent3a4311c2014-03-17 12:00:47 -07002400 if (outProfile->mSupportedDevices.isEmpty()) {
2401 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2402 continue;
2403 }
2404
Eric Laurent83b88082014-06-20 18:31:16 -07002405 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2406 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2407 profileType = mDefaultOutputDevice->mDeviceType;
2408 } else {
2409 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2410 }
2411 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002412 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002413 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002414
Eric Laurent83b88082014-06-20 18:31:16 -07002415 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002416 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2417 config.sample_rate = outputDesc->mSamplingRate;
2418 config.channel_mask = outputDesc->mChannelMask;
2419 config.format = outputDesc->mFormat;
2420 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2421 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2422 &output,
2423 &config,
2424 &outputDesc->mDevice,
2425 String8(""),
2426 &outputDesc->mLatency,
2427 outputDesc->mFlags);
2428
2429 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002430 ALOGW("Cannot open output stream for device %08x on hw module %s",
2431 outputDesc->mDevice,
2432 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002433 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002434 outputDesc->mSamplingRate = config.sample_rate;
2435 outputDesc->mChannelMask = config.channel_mask;
2436 outputDesc->mFormat = config.format;
2437
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002438 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002439 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002440 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002441 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002442 // give a valid ID to an attached device once confirmed it is reachable
2443 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2444 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002445 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002446 }
2447 }
Eric Laurente552edb2014-03-10 17:42:56 -07002448 if (mPrimaryOutput == 0 &&
2449 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2450 mPrimaryOutput = output;
2451 }
2452 addOutput(output, outputDesc);
2453 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002454 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002455 true);
2456 }
2457 }
2458 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002459 // open input streams needed to access attached devices to validate
2460 // mAvailableInputDevices list
2461 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2462 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002463 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002464
Eric Laurent3a4311c2014-03-17 12:00:47 -07002465 if (inProfile->mSupportedDevices.isEmpty()) {
2466 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2467 continue;
2468 }
2469
Eric Laurent83b88082014-06-20 18:31:16 -07002470 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2471 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002472 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002473
2474 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002475 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002476
Eric Laurentcf2c0212014-07-25 16:20:43 -07002477 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2478 config.sample_rate = inputDesc->mSamplingRate;
2479 config.channel_mask = inputDesc->mChannelMask;
2480 config.format = inputDesc->mFormat;
2481 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2482 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2483 &input,
2484 &config,
2485 &inputDesc->mDevice,
2486 String8(""),
2487 AUDIO_SOURCE_MIC,
2488 AUDIO_INPUT_FLAG_NONE);
2489
2490 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002491 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002492 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002493 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002494 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002495 // give a valid ID to an attached device once confirmed it is reachable
2496 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2497 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002498 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002499 }
2500 }
2501 mpClientInterface->closeInput(input);
2502 } else {
2503 ALOGW("Cannot open input stream for device %08x on hw module %s",
2504 inputDesc->mDevice,
2505 mHwModules[i]->mName);
2506 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002507 }
2508 }
2509 }
2510 // make sure all attached devices have been allocated a unique ID
2511 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2512 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002513 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002514 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2515 continue;
2516 }
2517 i++;
2518 }
2519 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2520 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002521 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002522 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2523 continue;
2524 }
2525 i++;
2526 }
2527 // make sure default device is reachable
2528 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002529 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002530 }
Eric Laurente552edb2014-03-10 17:42:56 -07002531
2532 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2533
2534 updateDevicesAndOutputs();
2535
2536#ifdef AUDIO_POLICY_TEST
2537 if (mPrimaryOutput != 0) {
2538 AudioParameter outputCmd = AudioParameter();
2539 outputCmd.addInt(String8("set_id"), 0);
2540 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2541
2542 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2543 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002544 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2545 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002546 mTestLatencyMs = 0;
2547 mCurOutput = 0;
2548 mDirectOutput = false;
2549 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2550 mTestOutputs[i] = 0;
2551 }
2552
2553 const size_t SIZE = 256;
2554 char buffer[SIZE];
2555 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2556 run(buffer, ANDROID_PRIORITY_AUDIO);
2557 }
2558#endif //AUDIO_POLICY_TEST
2559}
2560
Eric Laurente0720872014-03-11 09:30:41 -07002561AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002562{
2563#ifdef AUDIO_POLICY_TEST
2564 exit();
2565#endif //AUDIO_POLICY_TEST
2566 for (size_t i = 0; i < mOutputs.size(); i++) {
2567 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002568 }
2569 for (size_t i = 0; i < mInputs.size(); i++) {
2570 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002571 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002572 mAvailableOutputDevices.clear();
2573 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002574 mOutputs.clear();
2575 mInputs.clear();
2576 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002577}
2578
Eric Laurente0720872014-03-11 09:30:41 -07002579status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002580{
2581 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2582}
2583
2584#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002585bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002586{
2587 ALOGV("entering threadLoop()");
2588 while (!exitPending())
2589 {
2590 String8 command;
2591 int valueInt;
2592 String8 value;
2593
2594 Mutex::Autolock _l(mLock);
2595 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2596
2597 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2598 AudioParameter param = AudioParameter(command);
2599
2600 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2601 valueInt != 0) {
2602 ALOGV("Test command %s received", command.string());
2603 String8 target;
2604 if (param.get(String8("target"), target) != NO_ERROR) {
2605 target = "Manager";
2606 }
2607 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2608 param.remove(String8("test_cmd_policy_output"));
2609 mCurOutput = valueInt;
2610 }
2611 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2612 param.remove(String8("test_cmd_policy_direct"));
2613 if (value == "false") {
2614 mDirectOutput = false;
2615 } else if (value == "true") {
2616 mDirectOutput = true;
2617 }
2618 }
2619 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2620 param.remove(String8("test_cmd_policy_input"));
2621 mTestInput = valueInt;
2622 }
2623
2624 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2625 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002626 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002627 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002628 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002629 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002630 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002631 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002632 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002633 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002634 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002635 if (target == "Manager") {
2636 mTestFormat = format;
2637 } else if (mTestOutputs[mCurOutput] != 0) {
2638 AudioParameter outputParam = AudioParameter();
2639 outputParam.addInt(String8("format"), format);
2640 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2641 }
2642 }
2643 }
2644 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2645 param.remove(String8("test_cmd_policy_channels"));
2646 int channels = 0;
2647
2648 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002649 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002650 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002651 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002652 }
2653 if (channels != 0) {
2654 if (target == "Manager") {
2655 mTestChannels = channels;
2656 } else if (mTestOutputs[mCurOutput] != 0) {
2657 AudioParameter outputParam = AudioParameter();
2658 outputParam.addInt(String8("channels"), channels);
2659 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2660 }
2661 }
2662 }
2663 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2664 param.remove(String8("test_cmd_policy_sampleRate"));
2665 if (valueInt >= 0 && valueInt <= 96000) {
2666 int samplingRate = valueInt;
2667 if (target == "Manager") {
2668 mTestSamplingRate = samplingRate;
2669 } else if (mTestOutputs[mCurOutput] != 0) {
2670 AudioParameter outputParam = AudioParameter();
2671 outputParam.addInt(String8("sampling_rate"), samplingRate);
2672 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2673 }
2674 }
2675 }
2676
2677 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2678 param.remove(String8("test_cmd_policy_reopen"));
2679
Eric Laurent1f2f2232014-06-02 12:01:23 -07002680 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002681 mpClientInterface->closeOutput(mPrimaryOutput);
2682
2683 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2684
Eric Laurente552edb2014-03-10 17:42:56 -07002685 mOutputs.removeItem(mPrimaryOutput);
2686
Eric Laurent1f2f2232014-06-02 12:01:23 -07002687 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002688 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002689 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2690 config.sample_rate = outputDesc->mSamplingRate;
2691 config.channel_mask = outputDesc->mChannelMask;
2692 config.format = outputDesc->mFormat;
2693 status_t status = mpClientInterface->openOutput(moduleHandle,
2694 &mPrimaryOutput,
2695 &config,
2696 &outputDesc->mDevice,
2697 String8(""),
2698 &outputDesc->mLatency,
2699 outputDesc->mFlags);
2700 if (status != NO_ERROR) {
2701 ALOGE("Failed to reopen hardware output stream, "
2702 "samplingRate: %d, format %d, channels %d",
2703 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002704 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002705 outputDesc->mSamplingRate = config.sample_rate;
2706 outputDesc->mChannelMask = config.channel_mask;
2707 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002708 AudioParameter outputCmd = AudioParameter();
2709 outputCmd.addInt(String8("set_id"), 0);
2710 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2711 addOutput(mPrimaryOutput, outputDesc);
2712 }
2713 }
2714
2715
2716 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2717 }
2718 }
2719 return false;
2720}
2721
Eric Laurente0720872014-03-11 09:30:41 -07002722void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002723{
2724 {
2725 AutoMutex _l(mLock);
2726 requestExit();
2727 mWaitWorkCV.signal();
2728 }
2729 requestExitAndWait();
2730}
2731
Eric Laurente0720872014-03-11 09:30:41 -07002732int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002733{
2734 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2735 if (output == mTestOutputs[i]) return i;
2736 }
2737 return 0;
2738}
2739#endif //AUDIO_POLICY_TEST
2740
2741// ---
2742
Eric Laurent1f2f2232014-06-02 12:01:23 -07002743void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002744{
Eric Laurent1c333e22014-05-20 10:48:17 -07002745 outputDesc->mIoHandle = output;
2746 outputDesc->mId = nextUniqueId();
2747 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002748 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002749}
2750
Eric Laurent1f2f2232014-06-02 12:01:23 -07002751void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002752{
Eric Laurent1c333e22014-05-20 10:48:17 -07002753 inputDesc->mIoHandle = input;
2754 inputDesc->mId = nextUniqueId();
2755 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002756 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002757}
Eric Laurente552edb2014-03-10 17:42:56 -07002758
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002759void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2760 const String8 address /*in*/,
2761 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2762 // look for a match on the given address on the addresses of the outputs:
2763 // find the address by finding the patch that maps to this output
2764 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2765 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2766 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2767 if (patchIdx >= 0) {
2768 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2769 const int numSinks = patchDesc->mPatch.num_sinks;
2770 for (ssize_t j=0; j < numSinks; j++) {
2771 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2772 const char* patchAddr =
2773 patchDesc->mPatch.sinks[j].ext.device.address;
2774 if (strncmp(patchAddr,
2775 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2776 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2777 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2778 outputs.add(desc->mIoHandle);
2779 break;
2780 }
2781 }
2782 }
2783 }
2784}
2785
Eric Laurente0720872014-03-11 09:30:41 -07002786status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002787 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002788 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002789 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002790{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002791 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002792
Eric Laurent3b73df72014-03-11 09:06:29 -07002793 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002794 // first list already open outputs that can be routed to this device
2795 for (size_t i = 0; i < mOutputs.size(); i++) {
2796 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002797 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002798 if (!deviceDistinguishesOnAddress(device)) {
2799 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2800 outputs.add(mOutputs.keyAt(i));
2801 } else {
2802 ALOGV(" checking address match due to device 0x%x", device);
2803 findIoHandlesByAddress(desc, address, outputs);
2804 }
Eric Laurente552edb2014-03-10 17:42:56 -07002805 }
2806 }
2807 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002808 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002809 for (size_t i = 0; i < mHwModules.size(); i++)
2810 {
2811 if (mHwModules[i]->mHandle == 0) {
2812 continue;
2813 }
2814 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2815 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002816 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002817 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002818 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2819 }
2820 }
2821 }
2822
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002823 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
2824
Eric Laurente552edb2014-03-10 17:42:56 -07002825 if (profiles.isEmpty() && outputs.isEmpty()) {
2826 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2827 return BAD_VALUE;
2828 }
2829
2830 // open outputs for matching profiles if needed. Direct outputs are also opened to
2831 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2832 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002833 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002834
2835 // nothing to do if one output is already opened for this profile
2836 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002837 for (j = 0; j < outputs.size(); j++) {
2838 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07002839 if (!desc->isDuplicated() && desc->mProfile == profile) {
2840 break;
2841 }
2842 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002843 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002844 continue;
2845 }
2846
Eric Laurent83b88082014-06-20 18:31:16 -07002847 ALOGV("opening output for device %08x with params %s profile %p",
2848 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07002849 desc = new AudioOutputDescriptor(profile);
2850 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002851 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2852 config.sample_rate = desc->mSamplingRate;
2853 config.channel_mask = desc->mChannelMask;
2854 config.format = desc->mFormat;
2855 config.offload_info.sample_rate = desc->mSamplingRate;
2856 config.offload_info.channel_mask = desc->mChannelMask;
2857 config.offload_info.format = desc->mFormat;
2858 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2859 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
2860 &output,
2861 &config,
2862 &desc->mDevice,
2863 address,
2864 &desc->mLatency,
2865 desc->mFlags);
2866 if (status == NO_ERROR) {
2867 desc->mSamplingRate = config.sample_rate;
2868 desc->mChannelMask = config.channel_mask;
2869 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002870
Eric Laurentd4692962014-05-05 18:13:44 -07002871 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002872 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002873 char *param = audio_device_address_to_parameter(device, address);
2874 mpClientInterface->setParameters(output, String8(param));
2875 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07002876 }
2877
Eric Laurentd4692962014-05-05 18:13:44 -07002878 // Here is where we step through and resolve any "dynamic" fields
2879 String8 reply;
2880 char *value;
2881 if (profile->mSamplingRates[0] == 0) {
2882 reply = mpClientInterface->getParameters(output,
2883 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002884 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002885 reply.string());
2886 value = strpbrk((char *)reply.string(), "=");
2887 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002888 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002889 }
Eric Laurentd4692962014-05-05 18:13:44 -07002890 }
2891 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2892 reply = mpClientInterface->getParameters(output,
2893 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002894 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002895 reply.string());
2896 value = strpbrk((char *)reply.string(), "=");
2897 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002898 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002899 }
Eric Laurentd4692962014-05-05 18:13:44 -07002900 }
2901 if (profile->mChannelMasks[0] == 0) {
2902 reply = mpClientInterface->getParameters(output,
2903 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002904 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002905 reply.string());
2906 value = strpbrk((char *)reply.string(), "=");
2907 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002908 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002909 }
Eric Laurentd4692962014-05-05 18:13:44 -07002910 }
2911 if (((profile->mSamplingRates[0] == 0) &&
2912 (profile->mSamplingRates.size() < 2)) ||
2913 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2914 (profile->mFormats.size() < 2)) ||
2915 ((profile->mChannelMasks[0] == 0) &&
2916 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002917 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07002918 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002919 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07002920 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
2921 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002922 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002923 config.sample_rate = profile->pickSamplingRate();
2924 config.channel_mask = profile->pickChannelMask();
2925 config.format = profile->pickFormat();
2926 config.offload_info.sample_rate = config.sample_rate;
2927 config.offload_info.channel_mask = config.channel_mask;
2928 config.offload_info.format = config.format;
2929 status = mpClientInterface->openOutput(profile->mModule->mHandle,
2930 &output,
2931 &config,
2932 &desc->mDevice,
2933 address,
2934 &desc->mLatency,
2935 desc->mFlags);
2936 if (status == NO_ERROR) {
2937 desc->mSamplingRate = config.sample_rate;
2938 desc->mChannelMask = config.channel_mask;
2939 desc->mFormat = config.format;
2940 } else {
2941 output = AUDIO_IO_HANDLE_NONE;
2942 }
Eric Laurentd4692962014-05-05 18:13:44 -07002943 }
2944
Eric Laurentcf2c0212014-07-25 16:20:43 -07002945 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002946 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002947 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002948 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002949
Eric Laurentd4692962014-05-05 18:13:44 -07002950 // set initial stream volume for device
2951 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002952
Eric Laurentd4692962014-05-05 18:13:44 -07002953 //TODO: configure audio effect output stage here
2954
2955 // open a duplicating output thread for the new output and the primary output
2956 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2957 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002958 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07002959 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07002960 sp<AudioOutputDescriptor> dupOutputDesc =
2961 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002962 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2963 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2964 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2965 dupOutputDesc->mFormat = desc->mFormat;
2966 dupOutputDesc->mChannelMask = desc->mChannelMask;
2967 dupOutputDesc->mLatency = desc->mLatency;
2968 addOutput(duplicatedOutput, dupOutputDesc);
2969 applyStreamVolumes(duplicatedOutput, device, 0, true);
2970 } else {
2971 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2972 mPrimaryOutput, output);
2973 mpClientInterface->closeOutput(output);
2974 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002975 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002976 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07002977 }
Eric Laurente552edb2014-03-10 17:42:56 -07002978 }
2979 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002980 } else {
2981 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002982 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002983 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002984 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002985 profiles.removeAt(profile_index);
2986 profile_index--;
2987 } else {
2988 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002989 if (deviceDistinguishesOnAddress(device)) {
2990 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
2991 device, address.string());
2992 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
2993 NULL/*patch handle*/, address.string());
2994 }
Eric Laurente552edb2014-03-10 17:42:56 -07002995 ALOGV("checkOutputsForDevice(): adding output %d", output);
2996 }
2997 }
2998
2999 if (profiles.isEmpty()) {
3000 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3001 return BAD_VALUE;
3002 }
Eric Laurentd4692962014-05-05 18:13:44 -07003003 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003004 // check if one opened output is not needed any more after disconnecting one device
3005 for (size_t i = 0; i < mOutputs.size(); i++) {
3006 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003007 if (!desc->isDuplicated()) {
3008 if (!(desc->mProfile->mSupportedDevices.types()
3009 & mAvailableOutputDevices.types())) {
3010 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3011 mOutputs.keyAt(i));
3012 outputs.add(mOutputs.keyAt(i));
3013 } else if (deviceDistinguishesOnAddress(device) &&
3014 // exact match on device
3015 (desc->mProfile->mSupportedDevices.types() == device)) {
3016 findIoHandlesByAddress(desc, address, outputs);
3017 }
Eric Laurente552edb2014-03-10 17:42:56 -07003018 }
3019 }
Eric Laurentd4692962014-05-05 18:13:44 -07003020 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003021 for (size_t i = 0; i < mHwModules.size(); i++)
3022 {
3023 if (mHwModules[i]->mHandle == 0) {
3024 continue;
3025 }
3026 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3027 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003028 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003029 if (profile->mSupportedDevices.types() & device) {
3030 ALOGV("checkOutputsForDevice(): "
3031 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003032 if (profile->mSamplingRates[0] == 0) {
3033 profile->mSamplingRates.clear();
3034 profile->mSamplingRates.add(0);
3035 }
3036 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3037 profile->mFormats.clear();
3038 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3039 }
3040 if (profile->mChannelMasks[0] == 0) {
3041 profile->mChannelMasks.clear();
3042 profile->mChannelMasks.add(0);
3043 }
3044 }
3045 }
3046 }
3047 }
3048 return NO_ERROR;
3049}
3050
Eric Laurentd4692962014-05-05 18:13:44 -07003051status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3052 audio_policy_dev_state_t state,
3053 SortedVector<audio_io_handle_t>& inputs,
3054 const String8 address)
3055{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003056 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003057 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3058 // first list already open inputs that can be routed to this device
3059 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3060 desc = mInputs.valueAt(input_index);
3061 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3062 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3063 inputs.add(mInputs.keyAt(input_index));
3064 }
3065 }
3066
3067 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003068 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003069 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3070 {
3071 if (mHwModules[module_idx]->mHandle == 0) {
3072 continue;
3073 }
3074 for (size_t profile_index = 0;
3075 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3076 profile_index++)
3077 {
3078 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3079 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003080 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003081 profile_index, module_idx);
3082 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3083 }
3084 }
3085 }
3086
3087 if (profiles.isEmpty() && inputs.isEmpty()) {
3088 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3089 return BAD_VALUE;
3090 }
3091
3092 // open inputs for matching profiles if needed. Direct inputs are also opened to
3093 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3094 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3095
Eric Laurent1c333e22014-05-20 10:48:17 -07003096 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003097 // nothing to do if one input is already opened for this profile
3098 size_t input_index;
3099 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3100 desc = mInputs.valueAt(input_index);
3101 if (desc->mProfile == profile) {
3102 break;
3103 }
3104 }
3105 if (input_index != mInputs.size()) {
3106 continue;
3107 }
3108
3109 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3110 desc = new AudioInputDescriptor(profile);
3111 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003112 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3113 config.sample_rate = desc->mSamplingRate;
3114 config.channel_mask = desc->mChannelMask;
3115 config.format = desc->mFormat;
3116 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3117 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3118 &input,
3119 &config,
3120 &desc->mDevice,
3121 address,
3122 AUDIO_SOURCE_MIC,
3123 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003124
Eric Laurentcf2c0212014-07-25 16:20:43 -07003125 if (status == NO_ERROR) {
3126 desc->mSamplingRate = config.sample_rate;
3127 desc->mChannelMask = config.channel_mask;
3128 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003129
Eric Laurentd4692962014-05-05 18:13:44 -07003130 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003131 char *param = audio_device_address_to_parameter(device, address);
3132 mpClientInterface->setParameters(input, String8(param));
3133 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003134 }
3135
3136 // Here is where we step through and resolve any "dynamic" fields
3137 String8 reply;
3138 char *value;
3139 if (profile->mSamplingRates[0] == 0) {
3140 reply = mpClientInterface->getParameters(input,
3141 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3142 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3143 reply.string());
3144 value = strpbrk((char *)reply.string(), "=");
3145 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003146 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003147 }
3148 }
3149 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3150 reply = mpClientInterface->getParameters(input,
3151 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3152 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3153 value = strpbrk((char *)reply.string(), "=");
3154 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003155 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003156 }
3157 }
3158 if (profile->mChannelMasks[0] == 0) {
3159 reply = mpClientInterface->getParameters(input,
3160 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3161 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3162 reply.string());
3163 value = strpbrk((char *)reply.string(), "=");
3164 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003165 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003166 }
3167 }
3168 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3169 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3170 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3171 ALOGW("checkInputsForDevice() direct input missing param");
3172 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003173 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003174 }
3175
3176 if (input != 0) {
3177 addInput(input, desc);
3178 }
3179 } // endif input != 0
3180
Eric Laurentcf2c0212014-07-25 16:20:43 -07003181 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003182 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003183 profiles.removeAt(profile_index);
3184 profile_index--;
3185 } else {
3186 inputs.add(input);
3187 ALOGV("checkInputsForDevice(): adding input %d", input);
3188 }
3189 } // end scan profiles
3190
3191 if (profiles.isEmpty()) {
3192 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3193 return BAD_VALUE;
3194 }
3195 } else {
3196 // Disconnect
3197 // check if one opened input is not needed any more after disconnecting one device
3198 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3199 desc = mInputs.valueAt(input_index);
3200 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3201 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3202 mInputs.keyAt(input_index));
3203 inputs.add(mInputs.keyAt(input_index));
3204 }
3205 }
3206 // Clear any profiles associated with the disconnected device.
3207 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3208 if (mHwModules[module_index]->mHandle == 0) {
3209 continue;
3210 }
3211 for (size_t profile_index = 0;
3212 profile_index < mHwModules[module_index]->mInputProfiles.size();
3213 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003214 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003215 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003216 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003217 profile_index, module_index);
3218 if (profile->mSamplingRates[0] == 0) {
3219 profile->mSamplingRates.clear();
3220 profile->mSamplingRates.add(0);
3221 }
3222 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3223 profile->mFormats.clear();
3224 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3225 }
3226 if (profile->mChannelMasks[0] == 0) {
3227 profile->mChannelMasks.clear();
3228 profile->mChannelMasks.add(0);
3229 }
3230 }
3231 }
3232 }
3233 } // end disconnect
3234
3235 return NO_ERROR;
3236}
3237
3238
Eric Laurente0720872014-03-11 09:30:41 -07003239void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003240{
3241 ALOGV("closeOutput(%d)", output);
3242
Eric Laurent1f2f2232014-06-02 12:01:23 -07003243 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003244 if (outputDesc == NULL) {
3245 ALOGW("closeOutput() unknown output %d", output);
3246 return;
3247 }
3248
3249 // look for duplicated outputs connected to the output being removed.
3250 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003251 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003252 if (dupOutputDesc->isDuplicated() &&
3253 (dupOutputDesc->mOutput1 == outputDesc ||
3254 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003255 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003256 if (dupOutputDesc->mOutput1 == outputDesc) {
3257 outputDesc2 = dupOutputDesc->mOutput2;
3258 } else {
3259 outputDesc2 = dupOutputDesc->mOutput1;
3260 }
3261 // As all active tracks on duplicated output will be deleted,
3262 // and as they were also referenced on the other output, the reference
3263 // count for their stream type must be adjusted accordingly on
3264 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003265 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003266 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003267 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003268 }
3269 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3270 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3271
3272 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003273 mOutputs.removeItem(duplicatedOutput);
3274 }
3275 }
3276
3277 AudioParameter param;
3278 param.add(String8("closing"), String8("true"));
3279 mpClientInterface->setParameters(output, param.toString());
3280
3281 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003282 mOutputs.removeItem(output);
3283 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003284 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003285}
3286
Eric Laurente0720872014-03-11 09:30:41 -07003287SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003288 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003289{
3290 SortedVector<audio_io_handle_t> outputs;
3291
3292 ALOGVV("getOutputsForDevice() device %04x", device);
3293 for (size_t i = 0; i < openOutputs.size(); i++) {
3294 ALOGVV("output %d isDuplicated=%d device=%04x",
3295 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3296 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3297 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3298 outputs.add(openOutputs.keyAt(i));
3299 }
3300 }
3301 return outputs;
3302}
3303
Eric Laurente0720872014-03-11 09:30:41 -07003304bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003305 SortedVector<audio_io_handle_t>& outputs2)
3306{
3307 if (outputs1.size() != outputs2.size()) {
3308 return false;
3309 }
3310 for (size_t i = 0; i < outputs1.size(); i++) {
3311 if (outputs1[i] != outputs2[i]) {
3312 return false;
3313 }
3314 }
3315 return true;
3316}
3317
Eric Laurente0720872014-03-11 09:30:41 -07003318void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003319{
3320 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3321 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3322 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3323 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3324
3325 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3326 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3327 strategy, srcOutputs[0], dstOutputs[0]);
3328 // mute strategy while moving tracks from one output to another
3329 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003330 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003331 if (desc->isStrategyActive(strategy)) {
3332 setStrategyMute(strategy, true, srcOutputs[i]);
3333 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3334 }
3335 }
3336
3337 // Move effects associated to this strategy from previous output to new output
3338 if (strategy == STRATEGY_MEDIA) {
3339 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3340 SortedVector<audio_io_handle_t> moved;
3341 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003342 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3343 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3344 effectDesc->mIo != fxOutput) {
3345 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003346 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3347 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003348 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003349 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003350 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003351 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003352 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003353 }
3354 }
3355 }
3356 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003357 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3358 if (getStrategy((audio_stream_type_t)i) == strategy) {
3359 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003360 }
3361 }
3362 }
3363}
3364
Eric Laurente0720872014-03-11 09:30:41 -07003365void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003366{
3367 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3368 checkOutputForStrategy(STRATEGY_PHONE);
3369 checkOutputForStrategy(STRATEGY_SONIFICATION);
3370 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3371 checkOutputForStrategy(STRATEGY_MEDIA);
3372 checkOutputForStrategy(STRATEGY_DTMF);
3373}
3374
Eric Laurente0720872014-03-11 09:30:41 -07003375audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003376{
Eric Laurente552edb2014-03-10 17:42:56 -07003377 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003378 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003379 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3380 return mOutputs.keyAt(i);
3381 }
3382 }
3383
3384 return 0;
3385}
3386
Eric Laurente0720872014-03-11 09:30:41 -07003387void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003388{
Eric Laurente552edb2014-03-10 17:42:56 -07003389 audio_io_handle_t a2dpOutput = getA2dpOutput();
3390 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003391 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003392 return;
3393 }
3394
Eric Laurent3a4311c2014-03-17 12:00:47 -07003395 bool isScoConnected =
3396 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003397 // suspend A2DP output if:
3398 // (NOT already suspended) &&
3399 // ((SCO device is connected &&
3400 // (forced usage for communication || for record is SCO))) ||
3401 // (phone state is ringing || in call)
3402 //
3403 // restore A2DP output if:
3404 // (Already suspended) &&
3405 // ((SCO device is NOT connected ||
3406 // (forced usage NOT for communication && NOT for record is SCO))) &&
3407 // (phone state is NOT ringing && NOT in call)
3408 //
3409 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003410 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003411 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3412 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3413 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3414 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003415
3416 mpClientInterface->restoreOutput(a2dpOutput);
3417 mA2dpSuspended = false;
3418 }
3419 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003420 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003421 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3422 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3423 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3424 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003425
3426 mpClientInterface->suspendOutput(a2dpOutput);
3427 mA2dpSuspended = true;
3428 }
3429 }
3430}
3431
Eric Laurent1c333e22014-05-20 10:48:17 -07003432audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003433{
3434 audio_devices_t device = AUDIO_DEVICE_NONE;
3435
Eric Laurent1f2f2232014-06-02 12:01:23 -07003436 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003437
3438 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3439 if (index >= 0) {
3440 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3441 if (patchDesc->mUid != mUidCached) {
3442 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3443 outputDesc->device(), outputDesc->mPatchHandle);
3444 return outputDesc->device();
3445 }
3446 }
3447
Eric Laurente552edb2014-03-10 17:42:56 -07003448 // check the following by order of priority to request a routing change if necessary:
3449 // 1: the strategy enforced audible is active on the output:
3450 // use device for strategy enforced audible
3451 // 2: we are in call or the strategy phone is active on the output:
3452 // use device for strategy phone
3453 // 3: the strategy sonification is active on the output:
3454 // use device for strategy sonification
3455 // 4: the strategy "respectful" sonification is active on the output:
3456 // use device for strategy "respectful" sonification
3457 // 5: the strategy media is active on the output:
3458 // use device for strategy media
3459 // 6: the strategy DTMF is active on the output:
3460 // use device for strategy DTMF
3461 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3462 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3463 } else if (isInCall() ||
3464 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3465 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3466 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3467 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3468 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3469 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3470 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3471 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3472 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3473 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3474 }
3475
Eric Laurent1c333e22014-05-20 10:48:17 -07003476 ALOGV("getNewOutputDevice() selected device %x", device);
3477 return device;
3478}
3479
3480audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3481{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003482 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003483
3484 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3485 if (index >= 0) {
3486 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3487 if (patchDesc->mUid != mUidCached) {
3488 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3489 inputDesc->mDevice, inputDesc->mPatchHandle);
3490 return inputDesc->mDevice;
3491 }
3492 }
3493
Eric Laurent1c333e22014-05-20 10:48:17 -07003494 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3495
3496 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003497 return device;
3498}
3499
Eric Laurente0720872014-03-11 09:30:41 -07003500uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003501 return (uint32_t)getStrategy(stream);
3502}
3503
Eric Laurente0720872014-03-11 09:30:41 -07003504audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003505 // By checking the range of stream before calling getStrategy, we avoid
3506 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3507 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003508 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003509 return AUDIO_DEVICE_NONE;
3510 }
3511 audio_devices_t devices;
3512 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3513 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3514 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3515 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003516 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003517 if (outputDesc->isStrategyActive(strategy)) {
3518 devices = outputDesc->device();
3519 break;
3520 }
Eric Laurente552edb2014-03-10 17:42:56 -07003521 }
3522 return devices;
3523}
3524
Eric Laurente0720872014-03-11 09:30:41 -07003525AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003526 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003527 // stream to strategy mapping
3528 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003529 case AUDIO_STREAM_VOICE_CALL:
3530 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003531 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003532 case AUDIO_STREAM_RING:
3533 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003534 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003535 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003536 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003537 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003538 return STRATEGY_DTMF;
3539 default:
3540 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003541 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003542 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3543 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003544 case AUDIO_STREAM_TTS:
3545 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003546 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003547 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003548 return STRATEGY_ENFORCED_AUDIBLE;
3549 }
3550}
3551
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003552uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3553 // flags to strategy mapping
3554 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3555 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3556 }
3557
3558 // usage to strategy mapping
3559 switch (attr->usage) {
3560 case AUDIO_USAGE_MEDIA:
3561 case AUDIO_USAGE_GAME:
3562 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3563 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3564 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3565 return (uint32_t) STRATEGY_MEDIA;
3566
3567 case AUDIO_USAGE_VOICE_COMMUNICATION:
3568 return (uint32_t) STRATEGY_PHONE;
3569
3570 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3571 return (uint32_t) STRATEGY_DTMF;
3572
3573 case AUDIO_USAGE_ALARM:
3574 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3575 return (uint32_t) STRATEGY_SONIFICATION;
3576
3577 case AUDIO_USAGE_NOTIFICATION:
3578 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3579 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3580 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3581 case AUDIO_USAGE_NOTIFICATION_EVENT:
3582 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3583
3584 case AUDIO_USAGE_UNKNOWN:
3585 default:
3586 return (uint32_t) STRATEGY_MEDIA;
3587 }
3588}
3589
Eric Laurente0720872014-03-11 09:30:41 -07003590void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003591 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003592 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003593 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3594 updateDevicesAndOutputs();
3595 break;
3596 default:
3597 break;
3598 }
3599}
3600
Eric Laurente0720872014-03-11 09:30:41 -07003601audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003602 bool fromCache)
3603{
3604 uint32_t device = AUDIO_DEVICE_NONE;
3605
3606 if (fromCache) {
3607 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3608 strategy, mDeviceForStrategy[strategy]);
3609 return mDeviceForStrategy[strategy];
3610 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003611 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003612 switch (strategy) {
3613
3614 case STRATEGY_SONIFICATION_RESPECTFUL:
3615 if (isInCall()) {
3616 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003617 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003618 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3619 // while media is playing on a remote device, use the the sonification behavior.
3620 // Note that we test this usecase before testing if media is playing because
3621 // the isStreamActive() method only informs about the activity of a stream, not
3622 // if it's for local playback. Note also that we use the same delay between both tests
3623 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003624 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003625 // while media is playing (or has recently played), use the same device
3626 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3627 } else {
3628 // when media is not playing anymore, fall back on the sonification behavior
3629 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3630 }
3631
3632 break;
3633
3634 case STRATEGY_DTMF:
3635 if (!isInCall()) {
3636 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3637 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3638 break;
3639 }
3640 // when in call, DTMF and PHONE strategies follow the same rules
3641 // FALL THROUGH
3642
3643 case STRATEGY_PHONE:
3644 // for phone strategy, we first consider the forced use and then the available devices by order
3645 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003646 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3647 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003648 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003649 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003650 if (device) break;
3651 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003652 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003653 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003654 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003655 if (device) break;
3656 // if SCO device is requested but no SCO device is available, fall back to default case
3657 // FALL THROUGH
3658
3659 default: // FORCE_NONE
3660 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003661 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003662 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003663 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003664 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003665 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003666 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003667 if (device) break;
3668 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003669 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003670 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003671 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003672 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003673 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003674 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003675 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003676 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003677 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003678 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003679 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003680 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003681 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003682 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003683 if (device) break;
3684 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003685 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003686 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003687 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003688 if (device == AUDIO_DEVICE_NONE) {
3689 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3690 }
3691 break;
3692
Eric Laurent3b73df72014-03-11 09:06:29 -07003693 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003694 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3695 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003696 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003697 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003698 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003699 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003700 if (device) break;
3701 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003702 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003703 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003704 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003705 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003706 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003707 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003708 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003709 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003710 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003711 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003712 if (device) break;
3713 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003714 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3715 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003716 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003717 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003718 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003719 if (device == AUDIO_DEVICE_NONE) {
3720 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3721 }
3722 break;
3723 }
3724 break;
3725
3726 case STRATEGY_SONIFICATION:
3727
3728 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3729 // handleIncallSonification().
3730 if (isInCall()) {
3731 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3732 break;
3733 }
3734 // FALL THROUGH
3735
3736 case STRATEGY_ENFORCED_AUDIBLE:
3737 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3738 // except:
3739 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3740 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3741
3742 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003743 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003744 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003745 if (device == AUDIO_DEVICE_NONE) {
3746 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3747 }
3748 }
3749 // The second device used for sonification is the same as the device used by media strategy
3750 // FALL THROUGH
3751
3752 case STRATEGY_MEDIA: {
3753 uint32_t device2 = AUDIO_DEVICE_NONE;
3754 if (strategy != STRATEGY_SONIFICATION) {
3755 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003756 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003757 }
3758 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003759 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003760 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003761 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003762 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003763 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003764 }
3765 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003766 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003767 }
3768 }
3769 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003770 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003771 }
Jon Eklundac29afa2014-07-28 16:06:06 -05003772 if ((device2 == AUDIO_DEVICE_NONE)) {
3773 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3774 }
Eric Laurente552edb2014-03-10 17:42:56 -07003775 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003776 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003777 }
3778 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003779 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003780 }
3781 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003782 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003783 }
3784 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003785 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003786 }
3787 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3788 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003789 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003790 }
3791 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003792 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003793 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003794 }
3795 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003796 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003797 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003798 int device3 = AUDIO_DEVICE_NONE;
3799 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003800 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09003801 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3802 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003803 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003804 }
Eric Laurente552edb2014-03-10 17:42:56 -07003805
Jungshik Jang839e4f32014-06-26 17:23:40 +09003806 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003807 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3808 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3809 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003810
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003811 // If hdmi system audio mode is on, remove speaker out of output list.
3812 if ((strategy == STRATEGY_MEDIA) &&
3813 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3814 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3815 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3816 }
3817
Eric Laurente552edb2014-03-10 17:42:56 -07003818 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003819 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003820 if (device == AUDIO_DEVICE_NONE) {
3821 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3822 }
3823 } break;
3824
3825 default:
3826 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3827 break;
3828 }
3829
3830 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3831 return device;
3832}
3833
Eric Laurente0720872014-03-11 09:30:41 -07003834void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003835{
3836 for (int i = 0; i < NUM_STRATEGIES; i++) {
3837 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3838 }
3839 mPreviousOutputs = mOutputs;
3840}
3841
Eric Laurent1f2f2232014-06-02 12:01:23 -07003842uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003843 audio_devices_t prevDevice,
3844 uint32_t delayMs)
3845{
3846 // mute/unmute strategies using an incompatible device combination
3847 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3848 // if unmuting, unmute only after the specified delay
3849 if (outputDesc->isDuplicated()) {
3850 return 0;
3851 }
3852
3853 uint32_t muteWaitMs = 0;
3854 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003855 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003856
3857 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3858 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3859 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3860 bool doMute = false;
3861
3862 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3863 doMute = true;
3864 outputDesc->mStrategyMutedByDevice[i] = true;
3865 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3866 doMute = true;
3867 outputDesc->mStrategyMutedByDevice[i] = false;
3868 }
Eric Laurent99401132014-05-07 19:48:15 -07003869 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003870 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003871 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003872 // skip output if it does not share any device with current output
3873 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3874 == AUDIO_DEVICE_NONE) {
3875 continue;
3876 }
3877 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3878 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3879 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3880 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3881 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003882 if (mute) {
3883 // FIXME: should not need to double latency if volume could be applied
3884 // immediately by the audioflinger mixer. We must account for the delay
3885 // between now and the next time the audioflinger thread for this output
3886 // will process a buffer (which corresponds to one buffer size,
3887 // usually 1/2 or 1/4 of the latency).
3888 if (muteWaitMs < desc->latency() * 2) {
3889 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003890 }
3891 }
3892 }
3893 }
3894 }
3895 }
3896
Eric Laurent99401132014-05-07 19:48:15 -07003897 // temporary mute output if device selection changes to avoid volume bursts due to
3898 // different per device volumes
3899 if (outputDesc->isActive() && (device != prevDevice)) {
3900 if (muteWaitMs < outputDesc->latency() * 2) {
3901 muteWaitMs = outputDesc->latency() * 2;
3902 }
3903 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3904 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003905 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003906 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003907 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003908 muteWaitMs *2, device);
3909 }
3910 }
3911 }
3912
Eric Laurente552edb2014-03-10 17:42:56 -07003913 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3914 if (muteWaitMs > delayMs) {
3915 muteWaitMs -= delayMs;
3916 usleep(muteWaitMs * 1000);
3917 return muteWaitMs;
3918 }
3919 return 0;
3920}
3921
Eric Laurente0720872014-03-11 09:30:41 -07003922uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003923 audio_devices_t device,
3924 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003925 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003926 audio_patch_handle_t *patchHandle,
3927 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07003928{
3929 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003930 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003931 AudioParameter param;
3932 uint32_t muteWaitMs;
3933
3934 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003935 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3936 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003937 return muteWaitMs;
3938 }
3939 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3940 // output profile
3941 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003942 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003943 return 0;
3944 }
3945
3946 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003947 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003948
3949 audio_devices_t prevDevice = outputDesc->mDevice;
3950
3951 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3952
3953 if (device != AUDIO_DEVICE_NONE) {
3954 outputDesc->mDevice = device;
3955 }
3956 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3957
3958 // Do not change the routing if:
3959 // - the requested device is AUDIO_DEVICE_NONE
3960 // - the requested device is the same as current device and force is not specified.
3961 // Doing this check here allows the caller to call setOutputDevice() without conditions
3962 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3963 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3964 return muteWaitMs;
3965 }
3966
3967 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003968
Eric Laurente552edb2014-03-10 17:42:56 -07003969 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003970 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003971 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003972 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003973 DeviceVector deviceList = (address == NULL) ?
3974 mAvailableOutputDevices.getDevicesFromType(device)
3975 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07003976 if (!deviceList.isEmpty()) {
3977 struct audio_patch patch;
3978 outputDesc->toAudioPortConfig(&patch.sources[0]);
3979 patch.num_sources = 1;
3980 patch.num_sinks = 0;
3981 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3982 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003983 patch.num_sinks++;
3984 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003985 ssize_t index;
3986 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3987 index = mAudioPatches.indexOfKey(*patchHandle);
3988 } else {
3989 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3990 }
3991 sp< AudioPatch> patchDesc;
3992 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3993 if (index >= 0) {
3994 patchDesc = mAudioPatches.valueAt(index);
3995 afPatchHandle = patchDesc->mAfPatchHandle;
3996 }
3997
Eric Laurent1c333e22014-05-20 10:48:17 -07003998 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003999 &afPatchHandle,
4000 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004001 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4002 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004003 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004004 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004005 if (index < 0) {
4006 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4007 &patch, mUidCached);
4008 addAudioPatch(patchDesc->mHandle, patchDesc);
4009 } else {
4010 patchDesc->mPatch = patch;
4011 }
4012 patchDesc->mAfPatchHandle = afPatchHandle;
4013 patchDesc->mUid = mUidCached;
4014 if (patchHandle) {
4015 *patchHandle = patchDesc->mHandle;
4016 }
4017 outputDesc->mPatchHandle = patchDesc->mHandle;
4018 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004019 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004020 }
4021 }
4022 }
Eric Laurente552edb2014-03-10 17:42:56 -07004023
4024 // update stream volumes according to new device
4025 applyStreamVolumes(output, device, delayMs);
4026
4027 return muteWaitMs;
4028}
4029
Eric Laurent1c333e22014-05-20 10:48:17 -07004030status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004031 int delayMs,
4032 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004033{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004034 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004035 ssize_t index;
4036 if (patchHandle) {
4037 index = mAudioPatches.indexOfKey(*patchHandle);
4038 } else {
4039 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4040 }
4041 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004042 return INVALID_OPERATION;
4043 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004044 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4045 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004046 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4047 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004048 removeAudioPatch(patchDesc->mHandle);
4049 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004050 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004051 return status;
4052}
4053
4054status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4055 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004056 bool force,
4057 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004058{
4059 status_t status = NO_ERROR;
4060
Eric Laurent1f2f2232014-06-02 12:01:23 -07004061 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004062 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4063 inputDesc->mDevice = device;
4064
4065 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4066 if (!deviceList.isEmpty()) {
4067 struct audio_patch patch;
4068 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004069 // AUDIO_SOURCE_HOTWORD is for internal use only:
4070 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004071 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4072 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004073 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4074 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004075 patch.num_sinks = 1;
4076 //only one input device for now
4077 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004078 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004079 ssize_t index;
4080 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4081 index = mAudioPatches.indexOfKey(*patchHandle);
4082 } else {
4083 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4084 }
4085 sp< AudioPatch> patchDesc;
4086 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4087 if (index >= 0) {
4088 patchDesc = mAudioPatches.valueAt(index);
4089 afPatchHandle = patchDesc->mAfPatchHandle;
4090 }
4091
Eric Laurent1c333e22014-05-20 10:48:17 -07004092 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004093 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004094 0);
4095 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004096 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004097 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004098 if (index < 0) {
4099 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4100 &patch, mUidCached);
4101 addAudioPatch(patchDesc->mHandle, patchDesc);
4102 } else {
4103 patchDesc->mPatch = patch;
4104 }
4105 patchDesc->mAfPatchHandle = afPatchHandle;
4106 patchDesc->mUid = mUidCached;
4107 if (patchHandle) {
4108 *patchHandle = patchDesc->mHandle;
4109 }
4110 inputDesc->mPatchHandle = patchDesc->mHandle;
4111 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004112 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004113 }
4114 }
4115 }
4116 return status;
4117}
4118
Eric Laurent6a94d692014-05-20 11:18:06 -07004119status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4120 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004121{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004122 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004123 ssize_t index;
4124 if (patchHandle) {
4125 index = mAudioPatches.indexOfKey(*patchHandle);
4126 } else {
4127 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4128 }
4129 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004130 return INVALID_OPERATION;
4131 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004132 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4133 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004134 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4135 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004136 removeAudioPatch(patchDesc->mHandle);
4137 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004138 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004139 return status;
4140}
4141
4142sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004143 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004144 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004145 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004146 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004147{
4148 // Choose an input profile based on the requested capture parameters: select the first available
4149 // profile supporting all requested parameters.
4150
4151 for (size_t i = 0; i < mHwModules.size(); i++)
4152 {
4153 if (mHwModules[i]->mHandle == 0) {
4154 continue;
4155 }
4156 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4157 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004158 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004159 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004160 if (profile->isCompatibleProfile(device, samplingRate,
4161 &samplingRate /*updatedSamplingRate*/,
4162 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004163 return profile;
4164 }
4165 }
4166 }
4167 return NULL;
4168}
4169
Eric Laurente0720872014-03-11 09:30:41 -07004170audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004171{
4172 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004173 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4174 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004175 switch (inputSource) {
4176 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004177 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004178 device = AUDIO_DEVICE_IN_VOICE_CALL;
4179 break;
4180 }
4181 // FALL THROUGH
4182
4183 case AUDIO_SOURCE_DEFAULT:
4184 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004185 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4186 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
4187 break;
4188 }
4189 // FALL THROUGH
4190
Eric Laurente552edb2014-03-10 17:42:56 -07004191 case AUDIO_SOURCE_VOICE_RECOGNITION:
4192 case AUDIO_SOURCE_HOTWORD:
4193 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07004194 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004195 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004196 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004197 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004198 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004199 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4200 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004201 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004202 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4203 }
4204 break;
4205 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004206 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004207 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004208 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004209 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4210 }
4211 break;
4212 case AUDIO_SOURCE_VOICE_DOWNLINK:
4213 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004214 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004215 device = AUDIO_DEVICE_IN_VOICE_CALL;
4216 }
4217 break;
4218 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004219 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004220 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4221 }
4222 break;
4223 default:
4224 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4225 break;
4226 }
4227 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4228 return device;
4229}
4230
Eric Laurente0720872014-03-11 09:30:41 -07004231bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004232{
4233 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4234 device &= ~AUDIO_DEVICE_BIT_IN;
4235 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4236 return true;
4237 }
4238 return false;
4239}
4240
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004241bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4242 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4243}
4244
Eric Laurente0720872014-03-11 09:30:41 -07004245audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004246{
4247 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004248 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004249 if ((input_descriptor->mRefCount > 0)
4250 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4251 return mInputs.keyAt(i);
4252 }
4253 }
4254 return 0;
4255}
4256
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004257uint32_t AudioPolicyManager::activeInputsCount() const
4258{
4259 uint32_t count = 0;
4260 for (size_t i = 0; i < mInputs.size(); i++) {
4261 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4262 if (desc->mRefCount > 0) {
4263 return count++;
4264 }
4265 }
4266 return count;
4267}
4268
Eric Laurente552edb2014-03-10 17:42:56 -07004269
Eric Laurente0720872014-03-11 09:30:41 -07004270audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004271{
4272 if (device == AUDIO_DEVICE_NONE) {
4273 // this happens when forcing a route update and no track is active on an output.
4274 // In this case the returned category is not important.
4275 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004276 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004277 // Multiple device selection is either:
4278 // - speaker + one other device: give priority to speaker in this case.
4279 // - one A2DP device + another device: happens with duplicated output. In this case
4280 // retain the device on the A2DP output as the other must not correspond to an active
4281 // selection if not the speaker.
4282 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4283 device = AUDIO_DEVICE_OUT_SPEAKER;
4284 } else {
4285 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4286 }
4287 }
4288
Eric Laurent3b73df72014-03-11 09:06:29 -07004289 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004290 "getDeviceForVolume() invalid device combination: %08x",
4291 device);
4292
4293 return device;
4294}
4295
Eric Laurente0720872014-03-11 09:30:41 -07004296AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004297{
4298 switch(getDeviceForVolume(device)) {
4299 case AUDIO_DEVICE_OUT_EARPIECE:
4300 return DEVICE_CATEGORY_EARPIECE;
4301 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4302 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4303 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4304 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4305 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4306 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4307 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004308 case AUDIO_DEVICE_OUT_LINE:
4309 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4310 /*USB? Remote submix?*/
4311 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004312 case AUDIO_DEVICE_OUT_SPEAKER:
4313 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4314 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004315 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4316 case AUDIO_DEVICE_OUT_USB_DEVICE:
4317 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4318 default:
4319 return DEVICE_CATEGORY_SPEAKER;
4320 }
4321}
4322
Eric Laurente0720872014-03-11 09:30:41 -07004323float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004324 int indexInUi)
4325{
4326 device_category deviceCategory = getDeviceCategory(device);
4327 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4328
4329 // the volume index in the UI is relative to the min and max volume indices for this stream type
4330 int nbSteps = 1 + curve[VOLMAX].mIndex -
4331 curve[VOLMIN].mIndex;
4332 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4333 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4334
4335 // find what part of the curve this index volume belongs to, or if it's out of bounds
4336 int segment = 0;
4337 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4338 return 0.0f;
4339 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4340 segment = 0;
4341 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4342 segment = 1;
4343 } else if (volIdx <= curve[VOLMAX].mIndex) {
4344 segment = 2;
4345 } else { // out of bounds
4346 return 1.0f;
4347 }
4348
4349 // linear interpolation in the attenuation table in dB
4350 float decibels = curve[segment].mDBAttenuation +
4351 ((float)(volIdx - curve[segment].mIndex)) *
4352 ( (curve[segment+1].mDBAttenuation -
4353 curve[segment].mDBAttenuation) /
4354 ((float)(curve[segment+1].mIndex -
4355 curve[segment].mIndex)) );
4356
4357 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4358
4359 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4360 curve[segment].mIndex, volIdx,
4361 curve[segment+1].mIndex,
4362 curve[segment].mDBAttenuation,
4363 decibels,
4364 curve[segment+1].mDBAttenuation,
4365 amplification);
4366
4367 return amplification;
4368}
4369
Eric Laurente0720872014-03-11 09:30:41 -07004370const AudioPolicyManager::VolumeCurvePoint
4371 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004372 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4373};
4374
Eric Laurente0720872014-03-11 09:30:41 -07004375const AudioPolicyManager::VolumeCurvePoint
4376 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004377 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4378};
4379
Eric Laurente0720872014-03-11 09:30:41 -07004380const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004381 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4382 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4383};
4384
4385const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004386 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004387 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4388};
4389
Eric Laurente0720872014-03-11 09:30:41 -07004390const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004391 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004392 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004393};
4394
4395const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004396 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004397 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4398};
4399
Eric Laurente0720872014-03-11 09:30:41 -07004400const AudioPolicyManager::VolumeCurvePoint
4401 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004402 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4403};
4404
4405// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4406// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4407// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4408// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4409
Eric Laurente0720872014-03-11 09:30:41 -07004410const AudioPolicyManager::VolumeCurvePoint
4411 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004412 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4413};
4414
Eric Laurente0720872014-03-11 09:30:41 -07004415const AudioPolicyManager::VolumeCurvePoint
4416 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004417 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4418};
4419
Eric Laurente0720872014-03-11 09:30:41 -07004420const AudioPolicyManager::VolumeCurvePoint
4421 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004422 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4423};
4424
Eric Laurente0720872014-03-11 09:30:41 -07004425const AudioPolicyManager::VolumeCurvePoint
4426 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004427 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4428};
4429
Eric Laurente0720872014-03-11 09:30:41 -07004430const AudioPolicyManager::VolumeCurvePoint
4431 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004432 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4433};
4434
Eric Laurente0720872014-03-11 09:30:41 -07004435const AudioPolicyManager::VolumeCurvePoint
4436 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4437 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004438 { // AUDIO_STREAM_VOICE_CALL
4439 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4440 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004441 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4442 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004443 },
4444 { // AUDIO_STREAM_SYSTEM
4445 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4446 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004447 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4448 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004449 },
4450 { // AUDIO_STREAM_RING
4451 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4452 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004453 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4454 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004455 },
4456 { // AUDIO_STREAM_MUSIC
4457 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4458 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004459 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4460 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004461 },
4462 { // AUDIO_STREAM_ALARM
4463 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4464 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004465 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4466 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004467 },
4468 { // AUDIO_STREAM_NOTIFICATION
4469 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4470 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004471 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4472 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004473 },
4474 { // AUDIO_STREAM_BLUETOOTH_SCO
4475 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4476 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004477 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4478 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004479 },
4480 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4481 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4482 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004483 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4484 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004485 },
4486 { // AUDIO_STREAM_DTMF
4487 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4488 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004489 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4490 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004491 },
4492 { // AUDIO_STREAM_TTS
4493 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4494 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004495 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4496 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004497 },
4498};
4499
Eric Laurente0720872014-03-11 09:30:41 -07004500void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004501{
4502 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4503 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4504 mStreams[i].mVolumeCurve[j] =
4505 sVolumeProfiles[i][j];
4506 }
4507 }
4508
4509 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4510 if (mSpeakerDrcEnabled) {
4511 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4512 sDefaultSystemVolumeCurveDrc;
4513 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4514 sSpeakerSonificationVolumeCurveDrc;
4515 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4516 sSpeakerSonificationVolumeCurveDrc;
4517 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4518 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004519 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4520 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004521 }
4522}
4523
Eric Laurente0720872014-03-11 09:30:41 -07004524float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004525 int index,
4526 audio_io_handle_t output,
4527 audio_devices_t device)
4528{
4529 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004530 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004531 StreamDescriptor &streamDesc = mStreams[stream];
4532
4533 if (device == AUDIO_DEVICE_NONE) {
4534 device = outputDesc->device();
4535 }
4536
Eric Laurente552edb2014-03-10 17:42:56 -07004537 volume = volIndexToAmpl(device, streamDesc, index);
4538
4539 // if a headset is connected, apply the following rules to ring tones and notifications
4540 // to avoid sound level bursts in user's ears:
4541 // - always attenuate ring tones and notifications volume by 6dB
4542 // - if music is playing, always limit the volume to current music volume,
4543 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004544 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004545 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4546 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4547 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4548 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4549 ((stream_strategy == STRATEGY_SONIFICATION)
4550 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004551 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004552 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004553 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004554 streamDesc.mCanBeMuted) {
4555 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4556 // when the phone is ringing we must consider that music could have been paused just before
4557 // by the music application and behave as if music was active if the last music track was
4558 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004559 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004560 mLimitRingtoneVolume) {
4561 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004562 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4563 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004564 output,
4565 musicDevice);
4566 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4567 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4568 if (volume > minVol) {
4569 volume = minVol;
4570 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4571 }
4572 }
4573 }
4574
4575 return volume;
4576}
4577
Eric Laurente0720872014-03-11 09:30:41 -07004578status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004579 int index,
4580 audio_io_handle_t output,
4581 audio_devices_t device,
4582 int delayMs,
4583 bool force)
4584{
4585
4586 // do not change actual stream volume if the stream is muted
4587 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4588 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4589 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4590 return NO_ERROR;
4591 }
4592
4593 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004594 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4595 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4596 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4597 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004598 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004599 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004600 return INVALID_OPERATION;
4601 }
4602
4603 float volume = computeVolume(stream, index, output, device);
4604 // We actually change the volume if:
4605 // - the float value returned by computeVolume() changed
4606 // - the force flag is set
4607 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4608 force) {
4609 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4610 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4611 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4612 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004613 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4614 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004615 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004616 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004617 }
4618
Eric Laurent3b73df72014-03-11 09:06:29 -07004619 if (stream == AUDIO_STREAM_VOICE_CALL ||
4620 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004621 float voiceVolume;
4622 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004623 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004624 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4625 } else {
4626 voiceVolume = 1.0;
4627 }
4628
4629 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4630 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4631 mLastVoiceVolume = voiceVolume;
4632 }
4633 }
4634
4635 return NO_ERROR;
4636}
4637
Eric Laurente0720872014-03-11 09:30:41 -07004638void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004639 audio_devices_t device,
4640 int delayMs,
4641 bool force)
4642{
4643 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4644
Eric Laurent3b73df72014-03-11 09:06:29 -07004645 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4646 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004647 mStreams[stream].getVolumeIndex(device),
4648 output,
4649 device,
4650 delayMs,
4651 force);
4652 }
4653}
4654
Eric Laurente0720872014-03-11 09:30:41 -07004655void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004656 bool on,
4657 audio_io_handle_t output,
4658 int delayMs,
4659 audio_devices_t device)
4660{
4661 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004662 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4663 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4664 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004665 }
4666 }
4667}
4668
Eric Laurente0720872014-03-11 09:30:41 -07004669void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004670 bool on,
4671 audio_io_handle_t output,
4672 int delayMs,
4673 audio_devices_t device)
4674{
4675 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004676 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004677 if (device == AUDIO_DEVICE_NONE) {
4678 device = outputDesc->device();
4679 }
4680
4681 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4682 stream, on, output, outputDesc->mMuteCount[stream], device);
4683
4684 if (on) {
4685 if (outputDesc->mMuteCount[stream] == 0) {
4686 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004687 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4688 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004689 checkAndSetVolume(stream, 0, output, device, delayMs);
4690 }
4691 }
4692 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4693 outputDesc->mMuteCount[stream]++;
4694 } else {
4695 if (outputDesc->mMuteCount[stream] == 0) {
4696 ALOGV("setStreamMute() unmuting non muted stream!");
4697 return;
4698 }
4699 if (--outputDesc->mMuteCount[stream] == 0) {
4700 checkAndSetVolume(stream,
4701 streamDesc.getVolumeIndex(device),
4702 output,
4703 device,
4704 delayMs);
4705 }
4706 }
4707}
4708
Eric Laurente0720872014-03-11 09:30:41 -07004709void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004710 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004711{
4712 // if the stream pertains to sonification strategy and we are in call we must
4713 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4714 // in the device used for phone strategy and play the tone if the selected device does not
4715 // interfere with the device used for phone strategy
4716 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4717 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004718 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004719 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4720 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004721 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004722 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4723 stream, starting, outputDesc->mDevice, stateChange);
4724 if (outputDesc->mRefCount[stream]) {
4725 int muteCount = 1;
4726 if (stateChange) {
4727 muteCount = outputDesc->mRefCount[stream];
4728 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004729 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004730 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4731 for (int i = 0; i < muteCount; i++) {
4732 setStreamMute(stream, starting, mPrimaryOutput);
4733 }
4734 } else {
4735 ALOGV("handleIncallSonification() high visibility");
4736 if (outputDesc->device() &
4737 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4738 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4739 for (int i = 0; i < muteCount; i++) {
4740 setStreamMute(stream, starting, mPrimaryOutput);
4741 }
4742 }
4743 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004744 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4745 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004746 } else {
4747 mpClientInterface->stopTone();
4748 }
4749 }
4750 }
4751 }
4752}
4753
Eric Laurente0720872014-03-11 09:30:41 -07004754bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004755{
4756 return isStateInCall(mPhoneState);
4757}
4758
Eric Laurente0720872014-03-11 09:30:41 -07004759bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004760 return ((state == AUDIO_MODE_IN_CALL) ||
4761 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004762}
4763
Eric Laurente0720872014-03-11 09:30:41 -07004764uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004765{
4766 return MAX_EFFECTS_CPU_LOAD;
4767}
4768
Eric Laurente0720872014-03-11 09:30:41 -07004769uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004770{
4771 return MAX_EFFECTS_MEMORY;
4772}
4773
Eric Laurent6a94d692014-05-20 11:18:06 -07004774
Eric Laurente552edb2014-03-10 17:42:56 -07004775// --- AudioOutputDescriptor class implementation
4776
Eric Laurente0720872014-03-11 09:30:41 -07004777AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004778 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004779 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004780 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004781 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4782{
4783 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004784 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004785 mRefCount[i] = 0;
4786 mCurVolume[i] = -1.0;
4787 mMuteCount[i] = 0;
4788 mStopTime[i] = 0;
4789 }
4790 for (int i = 0; i < NUM_STRATEGIES; i++) {
4791 mStrategyMutedByDevice[i] = false;
4792 }
4793 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004794 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07004795 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07004796 mSamplingRate = profile->pickSamplingRate();
4797 mFormat = profile->pickFormat();
4798 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004799 if (profile->mGains.size() > 0) {
4800 profile->mGains[0]->getDefaultConfig(&mGain);
4801 }
Eric Laurente552edb2014-03-10 17:42:56 -07004802 }
4803}
4804
Eric Laurente0720872014-03-11 09:30:41 -07004805audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004806{
4807 if (isDuplicated()) {
4808 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4809 } else {
4810 return mDevice;
4811 }
4812}
4813
Eric Laurente0720872014-03-11 09:30:41 -07004814uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004815{
4816 if (isDuplicated()) {
4817 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4818 } else {
4819 return mLatency;
4820 }
4821}
4822
Eric Laurente0720872014-03-11 09:30:41 -07004823bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004824 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004825{
4826 if (isDuplicated()) {
4827 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4828 } else if (outputDesc->isDuplicated()){
4829 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4830 } else {
4831 return (mProfile->mModule == outputDesc->mProfile->mModule);
4832 }
4833}
4834
Eric Laurente0720872014-03-11 09:30:41 -07004835void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004836 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004837{
4838 // forward usage count change to attached outputs
4839 if (isDuplicated()) {
4840 mOutput1->changeRefCount(stream, delta);
4841 mOutput2->changeRefCount(stream, delta);
4842 }
4843 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004844 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4845 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004846 mRefCount[stream] = 0;
4847 return;
4848 }
4849 mRefCount[stream] += delta;
4850 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4851}
4852
Eric Laurente0720872014-03-11 09:30:41 -07004853audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004854{
4855 if (isDuplicated()) {
4856 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4857 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004858 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004859 }
4860}
4861
Eric Laurente0720872014-03-11 09:30:41 -07004862bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004863{
4864 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4865}
4866
Eric Laurente0720872014-03-11 09:30:41 -07004867bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004868 uint32_t inPastMs,
4869 nsecs_t sysTime) const
4870{
4871 if ((sysTime == 0) && (inPastMs != 0)) {
4872 sysTime = systemTime();
4873 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004874 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4875 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004876 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004877 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004878 return true;
4879 }
4880 }
4881 return false;
4882}
4883
Eric Laurente0720872014-03-11 09:30:41 -07004884bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004885 uint32_t inPastMs,
4886 nsecs_t sysTime) const
4887{
4888 if (mRefCount[stream] != 0) {
4889 return true;
4890 }
4891 if (inPastMs == 0) {
4892 return false;
4893 }
4894 if (sysTime == 0) {
4895 sysTime = systemTime();
4896 }
4897 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4898 return true;
4899 }
4900 return false;
4901}
4902
Eric Laurent1c333e22014-05-20 10:48:17 -07004903void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004904 struct audio_port_config *dstConfig,
4905 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004906{
Eric Laurent84c70242014-06-23 08:46:27 -07004907 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4908
Eric Laurent1f2f2232014-06-02 12:01:23 -07004909 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4910 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4911 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004912 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004913 }
4914 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4915
Eric Laurent6a94d692014-05-20 11:18:06 -07004916 dstConfig->id = mId;
4917 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4918 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004919 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4920 dstConfig->ext.mix.handle = mIoHandle;
4921 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004922}
4923
4924void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4925 struct audio_port *port) const
4926{
Eric Laurent84c70242014-06-23 08:46:27 -07004927 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004928 mProfile->toAudioPort(port);
4929 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 toAudioPortConfig(&port->active_config);
4931 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004932 port->ext.mix.handle = mIoHandle;
4933 port->ext.mix.latency_class =
4934 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4935}
Eric Laurente552edb2014-03-10 17:42:56 -07004936
Eric Laurente0720872014-03-11 09:30:41 -07004937status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004938{
4939 const size_t SIZE = 256;
4940 char buffer[SIZE];
4941 String8 result;
4942
4943 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4944 result.append(buffer);
4945 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4946 result.append(buffer);
4947 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4948 result.append(buffer);
4949 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4950 result.append(buffer);
4951 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4952 result.append(buffer);
4953 snprintf(buffer, SIZE, " Devices %08x\n", device());
4954 result.append(buffer);
4955 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4956 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004957 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4958 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4959 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004960 result.append(buffer);
4961 }
4962 write(fd, result.string(), result.size());
4963
4964 return NO_ERROR;
4965}
4966
4967// --- AudioInputDescriptor class implementation
4968
Eric Laurent1c333e22014-05-20 10:48:17 -07004969AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004970 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004971 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004972 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07004973{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004974 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004975 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07004976 mSamplingRate = profile->pickSamplingRate();
4977 mFormat = profile->pickFormat();
4978 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004979 if (profile->mGains.size() > 0) {
4980 profile->mGains[0]->getDefaultConfig(&mGain);
4981 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004982 }
Eric Laurente552edb2014-03-10 17:42:56 -07004983}
4984
Eric Laurent1c333e22014-05-20 10:48:17 -07004985void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 struct audio_port_config *dstConfig,
4987 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004988{
Eric Laurent84c70242014-06-23 08:46:27 -07004989 ALOG_ASSERT(mProfile != 0,
4990 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004991 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4992 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4993 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004994 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004995 }
4996
4997 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4998
Eric Laurent6a94d692014-05-20 11:18:06 -07004999 dstConfig->id = mId;
5000 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5001 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005002 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5003 dstConfig->ext.mix.handle = mIoHandle;
5004 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005005}
5006
5007void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5008 struct audio_port *port) const
5009{
Eric Laurent84c70242014-06-23 08:46:27 -07005010 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5011
Eric Laurent1c333e22014-05-20 10:48:17 -07005012 mProfile->toAudioPort(port);
5013 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005014 toAudioPortConfig(&port->active_config);
5015 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005016 port->ext.mix.handle = mIoHandle;
5017 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5018}
5019
Eric Laurente0720872014-03-11 09:30:41 -07005020status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005021{
5022 const size_t SIZE = 256;
5023 char buffer[SIZE];
5024 String8 result;
5025
5026 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5027 result.append(buffer);
5028 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5029 result.append(buffer);
5030 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5031 result.append(buffer);
5032 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5033 result.append(buffer);
5034 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5035 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005036 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5037 result.append(buffer);
5038
Eric Laurente552edb2014-03-10 17:42:56 -07005039 write(fd, result.string(), result.size());
5040
5041 return NO_ERROR;
5042}
5043
5044// --- StreamDescriptor class implementation
5045
Eric Laurente0720872014-03-11 09:30:41 -07005046AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005047 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5048{
5049 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5050}
5051
Eric Laurente0720872014-03-11 09:30:41 -07005052int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005053{
Eric Laurente0720872014-03-11 09:30:41 -07005054 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005055 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5056 if (mIndexCur.indexOfKey(device) < 0) {
5057 device = AUDIO_DEVICE_OUT_DEFAULT;
5058 }
5059 return mIndexCur.valueFor(device);
5060}
5061
Eric Laurente0720872014-03-11 09:30:41 -07005062void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005063{
5064 const size_t SIZE = 256;
5065 char buffer[SIZE];
5066 String8 result;
5067
5068 snprintf(buffer, SIZE, "%s %02d %02d ",
5069 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5070 result.append(buffer);
5071 for (size_t i = 0; i < mIndexCur.size(); i++) {
5072 snprintf(buffer, SIZE, "%04x : %02d, ",
5073 mIndexCur.keyAt(i),
5074 mIndexCur.valueAt(i));
5075 result.append(buffer);
5076 }
5077 result.append("\n");
5078
5079 write(fd, result.string(), result.size());
5080}
5081
5082// --- EffectDescriptor class implementation
5083
Eric Laurente0720872014-03-11 09:30:41 -07005084status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005085{
5086 const size_t SIZE = 256;
5087 char buffer[SIZE];
5088 String8 result;
5089
5090 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5091 result.append(buffer);
5092 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5093 result.append(buffer);
5094 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5095 result.append(buffer);
5096 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5097 result.append(buffer);
5098 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5099 result.append(buffer);
5100 write(fd, result.string(), result.size());
5101
5102 return NO_ERROR;
5103}
5104
Eric Laurent1c333e22014-05-20 10:48:17 -07005105// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005106
Eric Laurente0720872014-03-11 09:30:41 -07005107AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005108 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5109 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005110{
5111}
5112
Eric Laurente0720872014-03-11 09:30:41 -07005113AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005114{
5115 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005116 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005117 }
5118 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005119 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005120 }
5121 free((void *)mName);
5122}
5123
Eric Laurent1afeecb2014-05-14 08:52:28 -07005124status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5125{
5126 cnode *node = root->first_child;
5127
5128 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5129
5130 while (node) {
5131 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5132 profile->loadSamplingRates((char *)node->value);
5133 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5134 profile->loadFormats((char *)node->value);
5135 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5136 profile->loadInChannels((char *)node->value);
5137 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5138 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5139 mDeclaredDevices);
5140 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5141 profile->loadGains(node);
5142 }
5143 node = node->next;
5144 }
5145 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5146 "loadInput() invalid supported devices");
5147 ALOGW_IF(profile->mChannelMasks.size() == 0,
5148 "loadInput() invalid supported channel masks");
5149 ALOGW_IF(profile->mSamplingRates.size() == 0,
5150 "loadInput() invalid supported sampling rates");
5151 ALOGW_IF(profile->mFormats.size() == 0,
5152 "loadInput() invalid supported formats");
5153 if (!profile->mSupportedDevices.isEmpty() &&
5154 (profile->mChannelMasks.size() != 0) &&
5155 (profile->mSamplingRates.size() != 0) &&
5156 (profile->mFormats.size() != 0)) {
5157
5158 ALOGV("loadInput() adding input Supported Devices %04x",
5159 profile->mSupportedDevices.types());
5160
5161 mInputProfiles.add(profile);
5162 return NO_ERROR;
5163 } else {
5164 return BAD_VALUE;
5165 }
5166}
5167
5168status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5169{
5170 cnode *node = root->first_child;
5171
5172 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5173
5174 while (node) {
5175 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5176 profile->loadSamplingRates((char *)node->value);
5177 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5178 profile->loadFormats((char *)node->value);
5179 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5180 profile->loadOutChannels((char *)node->value);
5181 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5182 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5183 mDeclaredDevices);
5184 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5185 profile->mFlags = parseFlagNames((char *)node->value);
5186 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5187 profile->loadGains(node);
5188 }
5189 node = node->next;
5190 }
5191 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5192 "loadOutput() invalid supported devices");
5193 ALOGW_IF(profile->mChannelMasks.size() == 0,
5194 "loadOutput() invalid supported channel masks");
5195 ALOGW_IF(profile->mSamplingRates.size() == 0,
5196 "loadOutput() invalid supported sampling rates");
5197 ALOGW_IF(profile->mFormats.size() == 0,
5198 "loadOutput() invalid supported formats");
5199 if (!profile->mSupportedDevices.isEmpty() &&
5200 (profile->mChannelMasks.size() != 0) &&
5201 (profile->mSamplingRates.size() != 0) &&
5202 (profile->mFormats.size() != 0)) {
5203
5204 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5205 profile->mSupportedDevices.types(), profile->mFlags);
5206
5207 mOutputProfiles.add(profile);
5208 return NO_ERROR;
5209 } else {
5210 return BAD_VALUE;
5211 }
5212}
5213
5214status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5215{
5216 cnode *node = root->first_child;
5217
5218 audio_devices_t type = AUDIO_DEVICE_NONE;
5219 while (node) {
5220 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5221 type = parseDeviceNames((char *)node->value);
5222 break;
5223 }
5224 node = node->next;
5225 }
5226 if (type == AUDIO_DEVICE_NONE ||
5227 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5228 ALOGW("loadDevice() bad type %08x", type);
5229 return BAD_VALUE;
5230 }
5231 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5232 deviceDesc->mModule = this;
5233
5234 node = root->first_child;
5235 while (node) {
5236 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5237 deviceDesc->mAddress = String8((char *)node->value);
5238 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5239 if (audio_is_input_device(type)) {
5240 deviceDesc->loadInChannels((char *)node->value);
5241 } else {
5242 deviceDesc->loadOutChannels((char *)node->value);
5243 }
5244 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5245 deviceDesc->loadGains(node);
5246 }
5247 node = node->next;
5248 }
5249
5250 ALOGV("loadDevice() adding device name %s type %08x address %s",
5251 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5252
5253 mDeclaredDevices.add(deviceDesc);
5254
5255 return NO_ERROR;
5256}
5257
Eric Laurente0720872014-03-11 09:30:41 -07005258void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005259{
5260 const size_t SIZE = 256;
5261 char buffer[SIZE];
5262 String8 result;
5263
5264 snprintf(buffer, SIZE, " - name: %s\n", mName);
5265 result.append(buffer);
5266 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5267 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005268 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5269 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005270 write(fd, result.string(), result.size());
5271 if (mOutputProfiles.size()) {
5272 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5273 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005274 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005275 write(fd, buffer, strlen(buffer));
5276 mOutputProfiles[i]->dump(fd);
5277 }
5278 }
5279 if (mInputProfiles.size()) {
5280 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5281 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005282 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005283 write(fd, buffer, strlen(buffer));
5284 mInputProfiles[i]->dump(fd);
5285 }
5286 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005287 if (mDeclaredDevices.size()) {
5288 write(fd, " - devices:\n", strlen(" - devices:\n"));
5289 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5290 mDeclaredDevices[i]->dump(fd, 4, i);
5291 }
5292 }
Eric Laurente552edb2014-03-10 17:42:56 -07005293}
5294
Eric Laurent1c333e22014-05-20 10:48:17 -07005295// --- AudioPort class implementation
5296
Eric Laurenta121f902014-06-03 13:32:54 -07005297
5298AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5299 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005300 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005301{
5302 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5303 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5304}
5305
Eric Laurent1c333e22014-05-20 10:48:17 -07005306void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5307{
5308 port->role = mRole;
5309 port->type = mType;
5310 unsigned int i;
5311 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5312 port->sample_rates[i] = mSamplingRates[i];
5313 }
5314 port->num_sample_rates = i;
5315 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5316 port->channel_masks[i] = mChannelMasks[i];
5317 }
5318 port->num_channel_masks = i;
5319 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5320 port->formats[i] = mFormats[i];
5321 }
5322 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005323
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005324 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005325
5326 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5327 port->gains[i] = mGains[i]->mGain;
5328 }
5329 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005330}
5331
5332
5333void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5334{
5335 char *str = strtok(name, "|");
5336
5337 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5338 // rates should be read from the output stream after it is opened for the first time
5339 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5340 mSamplingRates.add(0);
5341 return;
5342 }
5343
5344 while (str != NULL) {
5345 uint32_t rate = atoi(str);
5346 if (rate != 0) {
5347 ALOGV("loadSamplingRates() adding rate %d", rate);
5348 mSamplingRates.add(rate);
5349 }
5350 str = strtok(NULL, "|");
5351 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005352}
5353
5354void AudioPolicyManager::AudioPort::loadFormats(char *name)
5355{
5356 char *str = strtok(name, "|");
5357
5358 // by convention, "0' in the first entry in mFormats indicates the supported formats
5359 // should be read from the output stream after it is opened for the first time
5360 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5361 mFormats.add(AUDIO_FORMAT_DEFAULT);
5362 return;
5363 }
5364
5365 while (str != NULL) {
5366 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5367 ARRAY_SIZE(sFormatNameToEnumTable),
5368 str);
5369 if (format != AUDIO_FORMAT_DEFAULT) {
5370 mFormats.add(format);
5371 }
5372 str = strtok(NULL, "|");
5373 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005374}
5375
5376void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5377{
5378 const char *str = strtok(name, "|");
5379
5380 ALOGV("loadInChannels() %s", name);
5381
5382 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5383 mChannelMasks.add(0);
5384 return;
5385 }
5386
5387 while (str != NULL) {
5388 audio_channel_mask_t channelMask =
5389 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5390 ARRAY_SIZE(sInChannelsNameToEnumTable),
5391 str);
5392 if (channelMask != 0) {
5393 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5394 mChannelMasks.add(channelMask);
5395 }
5396 str = strtok(NULL, "|");
5397 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005398}
5399
5400void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5401{
5402 const char *str = strtok(name, "|");
5403
5404 ALOGV("loadOutChannels() %s", name);
5405
5406 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5407 // masks should be read from the output stream after it is opened for the first time
5408 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5409 mChannelMasks.add(0);
5410 return;
5411 }
5412
5413 while (str != NULL) {
5414 audio_channel_mask_t channelMask =
5415 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5416 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5417 str);
5418 if (channelMask != 0) {
5419 mChannelMasks.add(channelMask);
5420 }
5421 str = strtok(NULL, "|");
5422 }
5423 return;
5424}
5425
Eric Laurent1afeecb2014-05-14 08:52:28 -07005426audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5427{
5428 const char *str = strtok(name, "|");
5429
5430 ALOGV("loadGainMode() %s", name);
5431 audio_gain_mode_t mode = 0;
5432 while (str != NULL) {
5433 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5434 ARRAY_SIZE(sGainModeNameToEnumTable),
5435 str);
5436 str = strtok(NULL, "|");
5437 }
5438 return mode;
5439}
5440
Eric Laurenta121f902014-06-03 13:32:54 -07005441void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005442{
5443 cnode *node = root->first_child;
5444
Eric Laurenta121f902014-06-03 13:32:54 -07005445 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005446
5447 while (node) {
5448 if (strcmp(node->name, GAIN_MODE) == 0) {
5449 gain->mGain.mode = loadGainMode((char *)node->value);
5450 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005451 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005452 gain->mGain.channel_mask =
5453 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5454 ARRAY_SIZE(sInChannelsNameToEnumTable),
5455 (char *)node->value);
5456 } else {
5457 gain->mGain.channel_mask =
5458 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5459 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5460 (char *)node->value);
5461 }
5462 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5463 gain->mGain.min_value = atoi((char *)node->value);
5464 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5465 gain->mGain.max_value = atoi((char *)node->value);
5466 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5467 gain->mGain.default_value = atoi((char *)node->value);
5468 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5469 gain->mGain.step_value = atoi((char *)node->value);
5470 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5471 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5472 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5473 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5474 }
5475 node = node->next;
5476 }
5477
5478 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5479 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5480
5481 if (gain->mGain.mode == 0) {
5482 return;
5483 }
5484 mGains.add(gain);
5485}
5486
5487void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5488{
5489 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005490 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005491 while (node) {
5492 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005493 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005494 node = node->next;
5495 }
5496}
5497
Glenn Kastencbd48022014-07-24 13:46:44 -07005498status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005499{
5500 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5501 if (mSamplingRates[i] == samplingRate) {
5502 return NO_ERROR;
5503 }
5504 }
5505 return BAD_VALUE;
5506}
5507
Glenn Kastencbd48022014-07-24 13:46:44 -07005508status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5509 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005510{
Glenn Kastencbd48022014-07-24 13:46:44 -07005511 // Search for the closest supported sampling rate that is above (preferred)
5512 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5513 // The sampling rates do not need to be sorted in ascending order.
5514 ssize_t maxBelow = -1;
5515 ssize_t minAbove = -1;
5516 uint32_t candidate;
5517 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5518 candidate = mSamplingRates[i];
5519 if (candidate == samplingRate) {
5520 if (updatedSamplingRate != NULL) {
5521 *updatedSamplingRate = candidate;
5522 }
5523 return NO_ERROR;
5524 }
5525 // candidate < desired
5526 if (candidate < samplingRate) {
5527 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5528 maxBelow = i;
5529 }
5530 // candidate > desired
5531 } else {
5532 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5533 minAbove = i;
5534 }
5535 }
5536 }
5537 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5538 // TODO Move these assumptions out.
5539 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5540 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5541 // due to approximation by an int32_t of the
5542 // phase increments
5543 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5544 if (minAbove >= 0) {
5545 candidate = mSamplingRates[minAbove];
5546 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5547 if (updatedSamplingRate != NULL) {
5548 *updatedSamplingRate = candidate;
5549 }
5550 return NO_ERROR;
5551 }
5552 }
5553 // But if we have to up-sample from a lower sampling rate, that's OK.
5554 if (maxBelow >= 0) {
5555 candidate = mSamplingRates[maxBelow];
5556 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5557 if (updatedSamplingRate != NULL) {
5558 *updatedSamplingRate = candidate;
5559 }
5560 return NO_ERROR;
5561 }
5562 }
5563 // leave updatedSamplingRate unmodified
5564 return BAD_VALUE;
5565}
5566
5567status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5568{
5569 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005570 if (mChannelMasks[i] == channelMask) {
5571 return NO_ERROR;
5572 }
5573 }
5574 return BAD_VALUE;
5575}
5576
Glenn Kastencbd48022014-07-24 13:46:44 -07005577status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5578 const
5579{
5580 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5581 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5582 // FIXME Does not handle multi-channel automatic conversions yet
5583 audio_channel_mask_t supported = mChannelMasks[i];
5584 if (supported == channelMask) {
5585 return NO_ERROR;
5586 }
5587 if (isRecordThread) {
5588 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5589 // FIXME Abstract this out to a table.
5590 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5591 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5592 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5593 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5594 return NO_ERROR;
5595 }
5596 }
5597 }
5598 return BAD_VALUE;
5599}
5600
Eric Laurenta121f902014-06-03 13:32:54 -07005601status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5602{
5603 for (size_t i = 0; i < mFormats.size(); i ++) {
5604 if (mFormats[i] == format) {
5605 return NO_ERROR;
5606 }
5607 }
5608 return BAD_VALUE;
5609}
5610
Eric Laurent1e693b52014-07-09 15:03:28 -07005611
5612uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5613{
5614 // special case for uninitialized dynamic profile
5615 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5616 return 0;
5617 }
5618
5619 uint32_t samplingRate = 0;
5620 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5621
5622 // For mixed output and inputs, use max mixer sampling rates. Do not
5623 // limit sampling rate otherwise
5624 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5625 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5626 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5627 maxRate = UINT_MAX;
5628 }
5629 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5630 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5631 samplingRate = mSamplingRates[i];
5632 }
5633 }
5634 return samplingRate;
5635}
5636
5637audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5638{
5639 // special case for uninitialized dynamic profile
5640 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5641 return AUDIO_CHANNEL_NONE;
5642 }
5643
5644 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5645 uint32_t channelCount = 0;
5646 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5647
5648 // For mixed output and inputs, use max mixer channel count. Do not
5649 // limit channel count otherwise
5650 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5651 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5652 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5653 maxCount = UINT_MAX;
5654 }
5655 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5656 uint32_t cnlCount;
5657 if (mUseInChannelMask) {
5658 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5659 } else {
5660 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5661 }
5662 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5663 channelMask = mChannelMasks[i];
5664 }
5665 }
5666 return channelMask;
5667}
5668
Andy Hung9a605382014-07-28 16:16:31 -07005669/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07005670const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5671 AUDIO_FORMAT_DEFAULT,
5672 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005673 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005674 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005675 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07005676 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005677};
5678
5679int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5680 audio_format_t format2)
5681{
5682 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5683 // compressed format and better than any PCM format. This is by design of pickFormat()
5684 if (!audio_is_linear_pcm(format1)) {
5685 if (!audio_is_linear_pcm(format2)) {
5686 return 0;
5687 }
5688 return 1;
5689 }
5690 if (!audio_is_linear_pcm(format2)) {
5691 return -1;
5692 }
5693
5694 int index1 = -1, index2 = -1;
5695 for (size_t i = 0;
5696 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5697 i ++) {
5698 if (sPcmFormatCompareTable[i] == format1) {
5699 index1 = i;
5700 }
5701 if (sPcmFormatCompareTable[i] == format2) {
5702 index2 = i;
5703 }
5704 }
5705 // format1 not found => index1 < 0 => format2 > format1
5706 // format2 not found => index2 < 0 => format2 < format1
5707 return index1 - index2;
5708}
5709
5710audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5711{
5712 // special case for uninitialized dynamic profile
5713 if (mFormats.size() == 1 && mFormats[0] == 0) {
5714 return AUDIO_FORMAT_DEFAULT;
5715 }
5716
5717 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07005718 audio_format_t bestFormat =
5719 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5720 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07005721 // For mixed output and inputs, use best mixer output format. Do not
5722 // limit format otherwise
5723 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5724 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07005725 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005726 bestFormat = AUDIO_FORMAT_INVALID;
5727 }
5728
5729 for (size_t i = 0; i < mFormats.size(); i ++) {
5730 if ((compareFormats(mFormats[i], format) > 0) &&
5731 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5732 format = mFormats[i];
5733 }
5734 }
5735 return format;
5736}
5737
Eric Laurenta121f902014-06-03 13:32:54 -07005738status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5739 int index) const
5740{
5741 if (index < 0 || (size_t)index >= mGains.size()) {
5742 return BAD_VALUE;
5743 }
5744 return mGains[index]->checkConfig(gainConfig);
5745}
5746
Eric Laurent1afeecb2014-05-14 08:52:28 -07005747void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5748{
5749 const size_t SIZE = 256;
5750 char buffer[SIZE];
5751 String8 result;
5752
5753 if (mName.size() != 0) {
5754 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5755 result.append(buffer);
5756 }
5757
5758 if (mSamplingRates.size() != 0) {
5759 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5760 result.append(buffer);
5761 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005762 if (i == 0 && mSamplingRates[i] == 0) {
5763 snprintf(buffer, SIZE, "Dynamic");
5764 } else {
5765 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5766 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005767 result.append(buffer);
5768 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5769 }
5770 result.append("\n");
5771 }
5772
5773 if (mChannelMasks.size() != 0) {
5774 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5775 result.append(buffer);
5776 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005777 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5778
5779 if (i == 0 && mChannelMasks[i] == 0) {
5780 snprintf(buffer, SIZE, "Dynamic");
5781 } else {
5782 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5783 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005784 result.append(buffer);
5785 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5786 }
5787 result.append("\n");
5788 }
5789
5790 if (mFormats.size() != 0) {
5791 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5792 result.append(buffer);
5793 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005794 const char *formatStr = enumToString(sFormatNameToEnumTable,
5795 ARRAY_SIZE(sFormatNameToEnumTable),
5796 mFormats[i]);
5797 if (i == 0 && strcmp(formatStr, "") == 0) {
5798 snprintf(buffer, SIZE, "Dynamic");
5799 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07005800 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07005801 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005802 result.append(buffer);
5803 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5804 }
5805 result.append("\n");
5806 }
5807 write(fd, result.string(), result.size());
5808 if (mGains.size() != 0) {
5809 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5810 write(fd, buffer, strlen(buffer) + 1);
5811 result.append(buffer);
5812 for (size_t i = 0; i < mGains.size(); i++) {
5813 mGains[i]->dump(fd, spaces + 2, i);
5814 }
5815 }
5816}
5817
5818// --- AudioGain class implementation
5819
Eric Laurenta121f902014-06-03 13:32:54 -07005820AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005821{
Eric Laurenta121f902014-06-03 13:32:54 -07005822 mIndex = index;
5823 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005824 memset(&mGain, 0, sizeof(struct audio_gain));
5825}
5826
Eric Laurenta121f902014-06-03 13:32:54 -07005827void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5828{
5829 config->index = mIndex;
5830 config->mode = mGain.mode;
5831 config->channel_mask = mGain.channel_mask;
5832 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5833 config->values[0] = mGain.default_value;
5834 } else {
5835 uint32_t numValues;
5836 if (mUseInChannelMask) {
5837 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5838 } else {
5839 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5840 }
5841 for (size_t i = 0; i < numValues; i++) {
5842 config->values[i] = mGain.default_value;
5843 }
5844 }
5845 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5846 config->ramp_duration_ms = mGain.min_ramp_ms;
5847 }
5848}
5849
5850status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5851{
5852 if ((config->mode & ~mGain.mode) != 0) {
5853 return BAD_VALUE;
5854 }
5855 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5856 if ((config->values[0] < mGain.min_value) ||
5857 (config->values[0] > mGain.max_value)) {
5858 return BAD_VALUE;
5859 }
5860 } else {
5861 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5862 return BAD_VALUE;
5863 }
5864 uint32_t numValues;
5865 if (mUseInChannelMask) {
5866 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5867 } else {
5868 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5869 }
5870 for (size_t i = 0; i < numValues; i++) {
5871 if ((config->values[i] < mGain.min_value) ||
5872 (config->values[i] > mGain.max_value)) {
5873 return BAD_VALUE;
5874 }
5875 }
5876 }
5877 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5878 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5879 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5880 return BAD_VALUE;
5881 }
5882 }
5883 return NO_ERROR;
5884}
5885
Eric Laurent1afeecb2014-05-14 08:52:28 -07005886void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5887{
5888 const size_t SIZE = 256;
5889 char buffer[SIZE];
5890 String8 result;
5891
5892 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5893 result.append(buffer);
5894 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5895 result.append(buffer);
5896 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5897 result.append(buffer);
5898 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5899 result.append(buffer);
5900 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5901 result.append(buffer);
5902 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5903 result.append(buffer);
5904 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5905 result.append(buffer);
5906 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5907 result.append(buffer);
5908 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5909 result.append(buffer);
5910
5911 write(fd, result.string(), result.size());
5912}
5913
Eric Laurent1f2f2232014-06-02 12:01:23 -07005914// --- AudioPortConfig class implementation
5915
5916AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5917{
5918 mSamplingRate = 0;
5919 mChannelMask = AUDIO_CHANNEL_NONE;
5920 mFormat = AUDIO_FORMAT_INVALID;
5921 mGain.index = -1;
5922}
5923
Eric Laurenta121f902014-06-03 13:32:54 -07005924status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5925 const struct audio_port_config *config,
5926 struct audio_port_config *backupConfig)
5927{
5928 struct audio_port_config localBackupConfig;
5929 status_t status = NO_ERROR;
5930
5931 localBackupConfig.config_mask = config->config_mask;
5932 toAudioPortConfig(&localBackupConfig);
5933
5934 if (mAudioPort == 0) {
5935 status = NO_INIT;
5936 goto exit;
5937 }
5938 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005939 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07005940 if (status != NO_ERROR) {
5941 goto exit;
5942 }
5943 mSamplingRate = config->sample_rate;
5944 }
5945 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005946 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07005947 if (status != NO_ERROR) {
5948 goto exit;
5949 }
5950 mChannelMask = config->channel_mask;
5951 }
5952 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5953 status = mAudioPort->checkFormat(config->format);
5954 if (status != NO_ERROR) {
5955 goto exit;
5956 }
5957 mFormat = config->format;
5958 }
5959 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5960 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5961 if (status != NO_ERROR) {
5962 goto exit;
5963 }
5964 mGain = config->gain;
5965 }
5966
5967exit:
5968 if (status != NO_ERROR) {
5969 applyAudioPortConfig(&localBackupConfig);
5970 }
5971 if (backupConfig != NULL) {
5972 *backupConfig = localBackupConfig;
5973 }
5974 return status;
5975}
5976
Eric Laurent1f2f2232014-06-02 12:01:23 -07005977void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5978 struct audio_port_config *dstConfig,
5979 const struct audio_port_config *srcConfig) const
5980{
5981 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5982 dstConfig->sample_rate = mSamplingRate;
5983 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5984 dstConfig->sample_rate = srcConfig->sample_rate;
5985 }
5986 } else {
5987 dstConfig->sample_rate = 0;
5988 }
5989 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5990 dstConfig->channel_mask = mChannelMask;
5991 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5992 dstConfig->channel_mask = srcConfig->channel_mask;
5993 }
5994 } else {
5995 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5996 }
5997 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5998 dstConfig->format = mFormat;
5999 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6000 dstConfig->format = srcConfig->format;
6001 }
6002 } else {
6003 dstConfig->format = AUDIO_FORMAT_INVALID;
6004 }
6005 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6006 dstConfig->gain = mGain;
6007 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6008 dstConfig->gain = srcConfig->gain;
6009 }
6010 } else {
6011 dstConfig->gain.index = -1;
6012 }
6013 if (dstConfig->gain.index != -1) {
6014 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6015 } else {
6016 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6017 }
6018}
6019
Eric Laurent1c333e22014-05-20 10:48:17 -07006020// --- IOProfile class implementation
6021
Eric Laurent1afeecb2014-05-14 08:52:28 -07006022AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006023 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006024 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006025{
6026}
6027
Eric Laurente0720872014-03-11 09:30:41 -07006028AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006029{
6030}
6031
6032// checks if the IO profile is compatible with specified parameters.
6033// Sampling rate, format and channel mask must be specified in order to
6034// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006035bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006036 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006037 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006038 audio_format_t format,
6039 audio_channel_mask_t channelMask,
6040 audio_output_flags_t flags) const
6041{
Glenn Kastencbd48022014-07-24 13:46:44 -07006042 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6043 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6044 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006045
Glenn Kastencbd48022014-07-24 13:46:44 -07006046 if ((mSupportedDevices.types() & device) != device) {
6047 return false;
6048 }
6049
6050 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006051 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006052 }
6053 uint32_t myUpdatedSamplingRate = samplingRate;
6054 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006055 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006056 }
6057 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6058 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006059 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006060 }
6061
6062 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6063 return false;
6064 }
6065
6066 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6067 checkExactChannelMask(channelMask) != NO_ERROR)) {
6068 return false;
6069 }
6070 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6071 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6072 return false;
6073 }
6074
6075 if (isPlaybackThread && (mFlags & flags) != flags) {
6076 return false;
6077 }
6078 // The only input flag that is allowed to be different is the fast flag.
6079 // An existing fast stream is compatible with a normal track request.
6080 // An existing normal stream is compatible with a fast track request,
6081 // but the fast request will be denied by AudioFlinger and converted to normal track.
6082 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6083 ~AUDIO_INPUT_FLAG_FAST)) {
6084 return false;
6085 }
6086
6087 if (updatedSamplingRate != NULL) {
6088 *updatedSamplingRate = myUpdatedSamplingRate;
6089 }
6090 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006091}
6092
Eric Laurente0720872014-03-11 09:30:41 -07006093void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006094{
6095 const size_t SIZE = 256;
6096 char buffer[SIZE];
6097 String8 result;
6098
Eric Laurent1afeecb2014-05-14 08:52:28 -07006099 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006100
Eric Laurente552edb2014-03-10 17:42:56 -07006101 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6102 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006103 snprintf(buffer, SIZE, " - devices:\n");
6104 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006105 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006106 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6107 mSupportedDevices[i]->dump(fd, 6, i);
6108 }
Eric Laurente552edb2014-03-10 17:42:56 -07006109}
6110
Eric Laurentd4692962014-05-05 18:13:44 -07006111void AudioPolicyManager::IOProfile::log()
6112{
6113 const size_t SIZE = 256;
6114 char buffer[SIZE];
6115 String8 result;
6116
6117 ALOGV(" - sampling rates: ");
6118 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6119 ALOGV(" %d", mSamplingRates[i]);
6120 }
6121
6122 ALOGV(" - channel masks: ");
6123 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6124 ALOGV(" 0x%04x", mChannelMasks[i]);
6125 }
6126
6127 ALOGV(" - formats: ");
6128 for (size_t i = 0; i < mFormats.size(); i++) {
6129 ALOGV(" 0x%08x", mFormats[i]);
6130 }
6131
6132 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6133 ALOGV(" - flags: 0x%04x\n", mFlags);
6134}
6135
6136
Eric Laurent3a4311c2014-03-17 12:00:47 -07006137// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006138
Eric Laurent1f2f2232014-06-02 12:01:23 -07006139
6140AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6141 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6142 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6143 AUDIO_PORT_ROLE_SOURCE,
6144 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006145 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006146{
6147 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07006148 if (mGains.size() > 0) {
6149 mGains[0]->getDefaultConfig(&mGain);
6150 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006151}
6152
Eric Laurent3a4311c2014-03-17 12:00:47 -07006153bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006154{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006155 // Devices are considered equal if they:
6156 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6157 // - have the same address or one device does not specify the address
6158 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006159 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006160 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006161 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006162 mChannelMask == other->mChannelMask);
6163}
6164
6165void AudioPolicyManager::DeviceVector::refreshTypes()
6166{
Eric Laurent1c333e22014-05-20 10:48:17 -07006167 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006168 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006169 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006170 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006171 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006172}
6173
6174ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6175{
6176 for(size_t i = 0; i < size(); i++) {
6177 if (item->equals(itemAt(i))) {
6178 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006179 }
6180 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006181 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006182}
6183
Eric Laurent3a4311c2014-03-17 12:00:47 -07006184ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006185{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006186 ssize_t ret = indexOf(item);
6187
6188 if (ret < 0) {
6189 ret = SortedVector::add(item);
6190 if (ret >= 0) {
6191 refreshTypes();
6192 }
6193 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006194 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006195 ret = -1;
6196 }
6197 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006198}
6199
Eric Laurent3a4311c2014-03-17 12:00:47 -07006200ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6201{
6202 size_t i;
6203 ssize_t ret = indexOf(item);
6204
6205 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006206 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006207 } else {
6208 ret = SortedVector::removeAt(ret);
6209 if (ret >= 0) {
6210 refreshTypes();
6211 }
6212 }
6213 return ret;
6214}
6215
6216void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6217{
6218 DeviceVector deviceList;
6219
6220 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6221 types &= ~role_bit;
6222
6223 while (types) {
6224 uint32_t i = 31 - __builtin_clz(types);
6225 uint32_t type = 1 << i;
6226 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006227 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006228 }
6229}
6230
Eric Laurent1afeecb2014-05-14 08:52:28 -07006231void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6232 const DeviceVector& declaredDevices)
6233{
6234 char *devName = strtok(name, "|");
6235 while (devName != NULL) {
6236 if (strlen(devName) != 0) {
6237 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6238 ARRAY_SIZE(sDeviceNameToEnumTable),
6239 devName);
6240 if (type != AUDIO_DEVICE_NONE) {
6241 add(new DeviceDescriptor(String8(""), type));
6242 } else {
6243 sp<DeviceDescriptor> deviceDesc =
6244 declaredDevices.getDeviceFromName(String8(devName));
6245 if (deviceDesc != 0) {
6246 add(deviceDesc);
6247 }
6248 }
6249 }
6250 devName = strtok(NULL, "|");
6251 }
6252}
6253
Eric Laurent1c333e22014-05-20 10:48:17 -07006254sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6255 audio_devices_t type, String8 address) const
6256{
6257 sp<DeviceDescriptor> device;
6258 for (size_t i = 0; i < size(); i++) {
6259 if (itemAt(i)->mDeviceType == type) {
6260 device = itemAt(i);
6261 if (itemAt(i)->mAddress = address) {
6262 break;
6263 }
6264 }
6265 }
6266 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6267 type, address.string(), device.get());
6268 return device;
6269}
6270
Eric Laurent6a94d692014-05-20 11:18:06 -07006271sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6272 audio_port_handle_t id) const
6273{
6274 sp<DeviceDescriptor> device;
6275 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006276 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006277 if (itemAt(i)->mId == id) {
6278 device = itemAt(i);
6279 break;
6280 }
6281 }
6282 return device;
6283}
6284
Eric Laurent1c333e22014-05-20 10:48:17 -07006285AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6286 audio_devices_t type) const
6287{
6288 DeviceVector devices;
6289 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6290 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6291 devices.add(itemAt(i));
6292 type &= ~itemAt(i)->mDeviceType;
6293 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6294 itemAt(i)->mDeviceType, itemAt(i).get());
6295 }
6296 }
6297 return devices;
6298}
6299
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006300AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6301 audio_devices_t type, String8 address) const
6302{
6303 DeviceVector devices;
6304 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6305 for (size_t i = 0; i < size(); i++) {
6306 //ALOGV(" at i=%d: device=%x, addr=%s",
6307 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6308 if (itemAt(i)->mDeviceType == type) {
6309 if (itemAt(i)->mAddress == address) {
6310 //ALOGV(" found matching address %s", address.string());
6311 devices.add(itemAt(i));
6312 }
6313 }
6314 }
6315 return devices;
6316}
6317
Eric Laurent1afeecb2014-05-14 08:52:28 -07006318sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6319 const String8& name) const
6320{
6321 sp<DeviceDescriptor> device;
6322 for (size_t i = 0; i < size(); i++) {
6323 if (itemAt(i)->mName == name) {
6324 device = itemAt(i);
6325 break;
6326 }
6327 }
6328 return device;
6329}
6330
Eric Laurent6a94d692014-05-20 11:18:06 -07006331void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6332 struct audio_port_config *dstConfig,
6333 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006334{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006335 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6336 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006337 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006338 }
6339
6340 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6341
Eric Laurent6a94d692014-05-20 11:18:06 -07006342 dstConfig->id = mId;
6343 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006344 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006345 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006346 dstConfig->ext.device.type = mDeviceType;
6347 dstConfig->ext.device.hw_module = mModule->mHandle;
6348 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006349}
6350
6351void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6352{
Eric Laurent83b88082014-06-20 18:31:16 -07006353 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006354 AudioPort::toAudioPort(port);
6355 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006356 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006357 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006358 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006359 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6360}
6361
Eric Laurent1afeecb2014-05-14 08:52:28 -07006362status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006363{
6364 const size_t SIZE = 256;
6365 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006366 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006367
Eric Laurent1afeecb2014-05-14 08:52:28 -07006368 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6369 result.append(buffer);
6370 if (mId != 0) {
6371 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6372 result.append(buffer);
6373 }
6374 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6375 enumToString(sDeviceNameToEnumTable,
6376 ARRAY_SIZE(sDeviceNameToEnumTable),
6377 mDeviceType));
6378 result.append(buffer);
6379 if (mAddress.size() != 0) {
6380 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6381 result.append(buffer);
6382 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006383 write(fd, result.string(), result.size());
6384 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006385
6386 return NO_ERROR;
6387}
6388
6389
6390// --- audio_policy.conf file parsing
6391
Eric Laurente0720872014-03-11 09:30:41 -07006392audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006393{
6394 uint32_t flag = 0;
6395
6396 // it is OK to cast name to non const here as we are not going to use it after
6397 // strtok() modifies it
6398 char *flagName = strtok(name, "|");
6399 while (flagName != NULL) {
6400 if (strlen(flagName) != 0) {
6401 flag |= stringToEnum(sFlagNameToEnumTable,
6402 ARRAY_SIZE(sFlagNameToEnumTable),
6403 flagName);
6404 }
6405 flagName = strtok(NULL, "|");
6406 }
6407 //force direct flag if offload flag is set: offloading implies a direct output stream
6408 // and all common behaviors are driven by checking only the direct flag
6409 // this should normally be set appropriately in the policy configuration file
6410 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6411 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6412 }
6413
6414 return (audio_output_flags_t)flag;
6415}
6416
Eric Laurente0720872014-03-11 09:30:41 -07006417audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006418{
6419 uint32_t device = 0;
6420
6421 char *devName = strtok(name, "|");
6422 while (devName != NULL) {
6423 if (strlen(devName) != 0) {
6424 device |= stringToEnum(sDeviceNameToEnumTable,
6425 ARRAY_SIZE(sDeviceNameToEnumTable),
6426 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006427 }
Eric Laurente552edb2014-03-10 17:42:56 -07006428 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006429 }
Eric Laurente552edb2014-03-10 17:42:56 -07006430 return device;
6431}
6432
Eric Laurente0720872014-03-11 09:30:41 -07006433void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006434{
Eric Laurente552edb2014-03-10 17:42:56 -07006435 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006436 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006437 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006438
Eric Laurent1afeecb2014-05-14 08:52:28 -07006439 node = config_find(root, DEVICES_TAG);
6440 if (node != NULL) {
6441 node = node->first_child;
6442 while (node) {
6443 ALOGV("loadHwModule() loading device %s", node->name);
6444 status_t tmpStatus = module->loadDevice(node);
6445 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6446 status = tmpStatus;
6447 }
6448 node = node->next;
6449 }
6450 }
6451 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006452 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006453 node = node->first_child;
6454 while (node) {
6455 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006456 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006457 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6458 status = tmpStatus;
6459 }
6460 node = node->next;
6461 }
6462 }
6463 node = config_find(root, INPUTS_TAG);
6464 if (node != NULL) {
6465 node = node->first_child;
6466 while (node) {
6467 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006468 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006469 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6470 status = tmpStatus;
6471 }
6472 node = node->next;
6473 }
6474 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006475 loadGlobalConfig(root, module);
6476
Eric Laurente552edb2014-03-10 17:42:56 -07006477 if (status == NO_ERROR) {
6478 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006479 }
6480}
6481
Eric Laurente0720872014-03-11 09:30:41 -07006482void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006483{
6484 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6485 if (node == NULL) {
6486 return;
6487 }
6488
6489 node = node->first_child;
6490 while (node) {
6491 ALOGV("loadHwModules() loading module %s", node->name);
6492 loadHwModule(node);
6493 node = node->next;
6494 }
6495}
6496
Eric Laurent1f2f2232014-06-02 12:01:23 -07006497void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006498{
6499 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006500
Eric Laurente552edb2014-03-10 17:42:56 -07006501 if (node == NULL) {
6502 return;
6503 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006504 DeviceVector declaredDevices;
6505 if (module != NULL) {
6506 declaredDevices = module->mDeclaredDevices;
6507 }
6508
Eric Laurente552edb2014-03-10 17:42:56 -07006509 node = node->first_child;
6510 while (node) {
6511 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006512 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6513 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006514 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6515 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006516 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006517 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006518 ARRAY_SIZE(sDeviceNameToEnumTable),
6519 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006520 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006521 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006522 } else {
6523 ALOGW("loadGlobalConfig() default device not specified");
6524 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006525 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006526 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006527 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6528 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006529 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006530 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6531 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6532 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006533 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6534 uint32_t major, minor;
6535 sscanf((char *)node->value, "%u.%u", &major, &minor);
6536 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6537 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6538 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006539 }
6540 node = node->next;
6541 }
6542}
6543
Eric Laurente0720872014-03-11 09:30:41 -07006544status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006545{
6546 cnode *root;
6547 char *data;
6548
6549 data = (char *)load_file(path, NULL);
6550 if (data == NULL) {
6551 return -ENODEV;
6552 }
6553 root = config_node("", "");
6554 config_load(root, data);
6555
Eric Laurente552edb2014-03-10 17:42:56 -07006556 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006557 // legacy audio_policy.conf files have one global_configuration section
6558 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006559 config_free(root);
6560 free(root);
6561 free(data);
6562
6563 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6564
6565 return NO_ERROR;
6566}
6567
Eric Laurente0720872014-03-11 09:30:41 -07006568void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006569{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006570 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006571 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006572 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6573 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006574 mAvailableOutputDevices.add(mDefaultOutputDevice);
6575 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006576
6577 module = new HwModule("primary");
6578
Eric Laurent1afeecb2014-05-14 08:52:28 -07006579 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006580 profile->mSamplingRates.add(44100);
6581 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6582 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006583 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006584 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6585 module->mOutputProfiles.add(profile);
6586
Eric Laurent1afeecb2014-05-14 08:52:28 -07006587 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006588 profile->mSamplingRates.add(8000);
6589 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6590 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006591 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006592 module->mInputProfiles.add(profile);
6593
6594 mHwModules.add(module);
6595}
6596
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006597audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6598{
6599 // flags to stream type mapping
6600 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6601 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6602 }
6603 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6604 return AUDIO_STREAM_BLUETOOTH_SCO;
6605 }
6606
6607 // usage to stream type mapping
6608 switch (attr->usage) {
6609 case AUDIO_USAGE_MEDIA:
6610 case AUDIO_USAGE_GAME:
6611 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6612 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6613 return AUDIO_STREAM_MUSIC;
6614 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6615 return AUDIO_STREAM_SYSTEM;
6616 case AUDIO_USAGE_VOICE_COMMUNICATION:
6617 return AUDIO_STREAM_VOICE_CALL;
6618
6619 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6620 return AUDIO_STREAM_DTMF;
6621
6622 case AUDIO_USAGE_ALARM:
6623 return AUDIO_STREAM_ALARM;
6624 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6625 return AUDIO_STREAM_RING;
6626
6627 case AUDIO_USAGE_NOTIFICATION:
6628 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6629 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6630 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6631 case AUDIO_USAGE_NOTIFICATION_EVENT:
6632 return AUDIO_STREAM_NOTIFICATION;
6633
6634 case AUDIO_USAGE_UNKNOWN:
6635 default:
6636 return AUDIO_STREAM_MUSIC;
6637 }
6638}
Eric Laurente552edb2014-03-10 17:42:56 -07006639}; // namespace android