blob: 440f5d0ed8a1b3ac2addcffc7fe6b99cca23f162 [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 Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070047#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070048
Eric Laurent3b73df72014-03-11 09:06:29 -070049namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070050
51// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070052// Definitions for audio_policy.conf file parsing
53// ----------------------------------------------------------------------------
54
55struct StringToEnum {
56 const char *name;
57 uint32_t value;
58};
59
60#define STRING_TO_ENUM(string) { #string, string }
61#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
62
63const StringToEnum sDeviceNameToEnumTable[] = {
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070077 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070078 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070084 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070089 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070090 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
91 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
92 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
93 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070095 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070096 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070097 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
99 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700103 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700104 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
107 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700108 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900109 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700110};
111
112const StringToEnum sFlagNameToEnumTable[] = {
113 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
114 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
115 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
119};
120
121const StringToEnum sFormatNameToEnumTable[] = {
122 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
123 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
124 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
125 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
127 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
128 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
129 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530130 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
131 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
132 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700140 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700141 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
142 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
143 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
144 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
145 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146};
147
148const StringToEnum sOutChannelsNameToEnumTable[] = {
149 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
150 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700151 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700152 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
153 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
154};
155
156const StringToEnum sInChannelsNameToEnumTable[] = {
157 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
158 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
159 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
160};
161
Eric Laurent1afeecb2014-05-14 08:52:28 -0700162const StringToEnum sGainModeNameToEnumTable[] = {
163 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
164 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
165 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
166};
167
Eric Laurent3a4311c2014-03-17 12:00:47 -0700168
169uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
170 size_t size,
171 const char *name)
172{
173 for (size_t i = 0; i < size; i++) {
174 if (strcmp(table[i].name, name) == 0) {
175 ALOGV("stringToEnum() found %s", table[i].name);
176 return table[i].value;
177 }
178 }
179 return 0;
180}
181
182const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
183 size_t size,
184 uint32_t value)
185{
186 for (size_t i = 0; i < size; i++) {
187 if (table[i].value == value) {
188 return table[i].name;
189 }
190 }
191 return "";
192}
193
194bool AudioPolicyManager::stringToBool(const char *value)
195{
196 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
197}
198
199
200// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700201// AudioPolicyInterface implementation
202// ----------------------------------------------------------------------------
203
204
Eric Laurente0720872014-03-11 09:30:41 -0700205status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700206 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700207 const char *device_address)
208{
Eric Laurent22226012014-08-01 17:00:54 -0700209 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700210
Eric Laurent22226012014-08-01 17:00:54 -0700211 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
212 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700213
214 // connect/disconnect only 1 device at a time
215 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
216
Eric Laurente552edb2014-03-10 17:42:56 -0700217 // handle output devices
218 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700219 SortedVector <audio_io_handle_t> outputs;
220
Eric Laurent1afeecb2014-05-14 08:52:28 -0700221 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
222 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700223 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
224
Eric Laurente552edb2014-03-10 17:42:56 -0700225 // save a copy of the opened output descriptors before any output is opened or closed
226 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
227 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700228 switch (state)
229 {
230 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700231 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700232 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700233 ALOGW("setDeviceConnectionState() device already connected: %x", device);
234 return INVALID_OPERATION;
235 }
236 ALOGV("setDeviceConnectionState() connecting device %x", device);
237
Eric Laurente552edb2014-03-10 17:42:56 -0700238 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700239 index = mAvailableOutputDevices.add(devDesc);
240 if (index >= 0) {
241 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700242 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700243 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
244 "could not find HW module for device %08x", device);
245 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700246 } else {
247 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700248 }
249
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700250 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
251 mAvailableOutputDevices.remove(devDesc);
252 return INVALID_OPERATION;
253 }
254 // outputs should never be empty here
255 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
256 "checkOutputsForDevice() returned no outputs but status OK");
257 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
258 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700259 break;
260 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700261 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700262 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700263 ALOGW("setDeviceConnectionState() device not connected: %x", device);
264 return INVALID_OPERATION;
265 }
266
267 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
268 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700269 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700270
Eric Laurent3a4311c2014-03-17 12:00:47 -0700271 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 } break;
273
274 default:
275 ALOGE("setDeviceConnectionState() invalid state: %x", state);
276 return BAD_VALUE;
277 }
278
Eric Laurent3a4311c2014-03-17 12:00:47 -0700279 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
280 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700281 checkA2dpSuspend();
282 checkOutputForAllStrategies();
283 // outputs must be closed after checkOutputForAllStrategies() is executed
284 if (!outputs.isEmpty()) {
285 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700286 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700287 // close unused outputs after device disconnection or direct outputs that have been
288 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700289 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700290 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
291 (desc->mDirectOpenCount == 0))) {
292 closeOutput(outputs[i]);
293 }
294 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700295 // check again after closing A2DP output to reset mA2dpSuspended if needed
296 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700297 }
298
299 updateDevicesAndOutputs();
300 for (size_t i = 0; i < mOutputs.size(); i++) {
301 // do not force device change on duplicated output because if device is 0, it will
302 // also force a device 0 for the two outputs it is duplicated to which may override
303 // a valid device selection on those outputs.
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700304 bool force = !mOutputs.valueAt(i)->isDuplicated()
305 && (!deviceDistinguishesOnAddress(device)
306 // always force when disconnecting (a non-duplicated device)
307 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurente552edb2014-03-10 17:42:56 -0700308 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700309 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700310 force, 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
312
Eric Laurent72aa32f2014-05-30 18:51:48 -0700313 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700314 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700315 } // end if is output device
316
Eric Laurente552edb2014-03-10 17:42:56 -0700317 // handle input devices
318 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700319 SortedVector <audio_io_handle_t> inputs;
320
Eric Laurent1afeecb2014-05-14 08:52:28 -0700321 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
322 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700323 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700324 switch (state)
325 {
326 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700327 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700328 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700329 ALOGW("setDeviceConnectionState() device already connected: %d", device);
330 return INVALID_OPERATION;
331 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700332 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700333 if (module == NULL) {
334 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
335 device);
336 return INVALID_OPERATION;
337 }
Eric Laurentd4692962014-05-05 18:13:44 -0700338 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
339 return INVALID_OPERATION;
340 }
341
Eric Laurent3a4311c2014-03-17 12:00:47 -0700342 index = mAvailableInputDevices.add(devDesc);
343 if (index >= 0) {
344 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700345 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700346 } else {
347 return NO_MEMORY;
348 }
Eric Laurentd4692962014-05-05 18:13:44 -0700349 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700350
351 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700352 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700354 ALOGW("setDeviceConnectionState() device not connected: %d", device);
355 return INVALID_OPERATION;
356 }
Eric Laurentd4692962014-05-05 18:13:44 -0700357 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700358 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700359 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700360
361 default:
362 ALOGE("setDeviceConnectionState() invalid state: %x", state);
363 return BAD_VALUE;
364 }
365
Eric Laurentd4692962014-05-05 18:13:44 -0700366 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700367
Eric Laurentb52c1522014-05-20 11:27:36 -0700368 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700369 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700370 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700371
372 ALOGW("setDeviceConnectionState() invalid device: %x", device);
373 return BAD_VALUE;
374}
375
Eric Laurente0720872014-03-11 09:30:41 -0700376audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700377 const char *device_address)
378{
Eric Laurent3b73df72014-03-11 09:06:29 -0700379 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700380 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700381 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700382 ssize_t index;
383 DeviceVector *deviceVector;
384
Eric Laurente552edb2014-03-10 17:42:56 -0700385 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700386 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700387 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 deviceVector = &mAvailableInputDevices;
389 } else {
390 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
391 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700392 }
393
Eric Laurent3a4311c2014-03-17 12:00:47 -0700394 index = deviceVector->indexOf(devDesc);
395 if (index >= 0) {
396 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
397 } else {
398 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
399 }
Eric Laurente552edb2014-03-10 17:42:56 -0700400}
401
Eric Laurente0720872014-03-11 09:30:41 -0700402void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700403{
404 ALOGV("setPhoneState() state %d", state);
405 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700406 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700407 ALOGW("setPhoneState() invalid state %d", state);
408 return;
409 }
410
411 if (state == mPhoneState ) {
412 ALOGW("setPhoneState() setting same state %d", state);
413 return;
414 }
415
416 // if leaving call state, handle special case of active streams
417 // pertaining to sonification strategy see handleIncallSonification()
418 if (isInCall()) {
419 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700420 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
421 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700422 }
423 }
424
425 // store previous phone state for management of sonification strategy below
426 int oldState = mPhoneState;
427 mPhoneState = state;
428 bool force = false;
429
430 // are we entering or starting a call
431 if (!isStateInCall(oldState) && isStateInCall(state)) {
432 ALOGV(" Entering call in setPhoneState()");
433 // force routing command to audio hardware when starting a call
434 // even if no device change is needed
435 force = true;
436 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
437 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
438 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
439 }
440 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
441 ALOGV(" Exiting call in setPhoneState()");
442 // force routing command to audio hardware when exiting a call
443 // even if no device change is needed
444 force = true;
445 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
446 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
447 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
448 }
449 } else if (isStateInCall(state) && (state != oldState)) {
450 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
451 // force routing command to audio hardware when switching between telephony and VoIP
452 // even if no device change is needed
453 force = true;
454 }
455
456 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700457 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700458 checkA2dpSuspend();
459 checkOutputForAllStrategies();
460 updateDevicesAndOutputs();
461
Eric Laurent1f2f2232014-06-02 12:01:23 -0700462 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700463
464 // force routing command to audio hardware when ending call
465 // even if no device change is needed
466 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
467 newDevice = hwOutputDesc->device();
468 }
469
470 int delayMs = 0;
471 if (isStateInCall(state)) {
472 nsecs_t sysTime = systemTime();
473 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700474 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700475 // mute media and sonification strategies and delay device switch by the largest
476 // latency of any output where either strategy is active.
477 // This avoid sending the ring tone or music tail into the earpiece or headset.
478 if ((desc->isStrategyActive(STRATEGY_MEDIA,
479 SONIFICATION_HEADSET_MUSIC_DELAY,
480 sysTime) ||
481 desc->isStrategyActive(STRATEGY_SONIFICATION,
482 SONIFICATION_HEADSET_MUSIC_DELAY,
483 sysTime)) &&
484 (delayMs < (int)desc->mLatency*2)) {
485 delayMs = desc->mLatency*2;
486 }
487 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
488 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
489 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
490 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
491 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
492 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
493 }
494 }
495
496 // change routing is necessary
497 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
498
499 // if entering in call state, handle special case of active streams
500 // pertaining to sonification strategy see handleIncallSonification()
501 if (isStateInCall(state)) {
502 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700503 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
504 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700505 }
506 }
507
508 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700509 if (state == AUDIO_MODE_RINGTONE &&
510 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700511 mLimitRingtoneVolume = true;
512 } else {
513 mLimitRingtoneVolume = false;
514 }
515}
516
Eric Laurente0720872014-03-11 09:30:41 -0700517void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700518 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700519{
520 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
521
522 bool forceVolumeReeval = false;
523 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700524 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
525 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
526 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700527 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
528 return;
529 }
530 forceVolumeReeval = true;
531 mForceUse[usage] = config;
532 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700533 case AUDIO_POLICY_FORCE_FOR_MEDIA:
534 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
535 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
536 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
537 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900538 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700539 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
540 return;
541 }
542 mForceUse[usage] = config;
543 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700544 case AUDIO_POLICY_FORCE_FOR_RECORD:
545 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
546 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700547 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
548 return;
549 }
550 mForceUse[usage] = config;
551 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700552 case AUDIO_POLICY_FORCE_FOR_DOCK:
553 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
554 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
555 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
556 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
557 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700558 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
559 }
560 forceVolumeReeval = true;
561 mForceUse[usage] = config;
562 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700563 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
564 if (config != AUDIO_POLICY_FORCE_NONE &&
565 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700566 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
567 }
568 forceVolumeReeval = true;
569 mForceUse[usage] = config;
570 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900571 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
572 if (config != AUDIO_POLICY_FORCE_NONE &&
573 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
574 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
575 }
576 mForceUse[usage] = config;
577 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700578 default:
579 ALOGW("setForceUse() invalid usage %d", usage);
580 break;
581 }
582
583 // check for device and output changes triggered by new force usage
584 checkA2dpSuspend();
585 checkOutputForAllStrategies();
586 updateDevicesAndOutputs();
587 for (size_t i = 0; i < mOutputs.size(); i++) {
588 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700589 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700590 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
591 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
592 applyStreamVolumes(output, newDevice, 0, true);
593 }
594 }
595
596 audio_io_handle_t activeInput = getActiveInput();
597 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700598 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700599 }
600
601}
602
Eric Laurente0720872014-03-11 09:30:41 -0700603audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700604{
605 return mForceUse[usage];
606}
607
Eric Laurente0720872014-03-11 09:30:41 -0700608void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700609{
610 ALOGV("setSystemProperty() property %s, value %s", property, value);
611}
612
613// Find a direct output profile compatible with the parameters passed, even if the input flags do
614// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700615sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700616 audio_devices_t device,
617 uint32_t samplingRate,
618 audio_format_t format,
619 audio_channel_mask_t channelMask,
620 audio_output_flags_t flags)
621{
622 for (size_t i = 0; i < mHwModules.size(); i++) {
623 if (mHwModules[i]->mHandle == 0) {
624 continue;
625 }
626 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700627 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700628 bool found = profile->isCompatibleProfile(device, samplingRate,
629 NULL /*updatedSamplingRate*/, format, channelMask,
630 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
631 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700632 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
633 return profile;
634 }
Eric Laurente552edb2014-03-10 17:42:56 -0700635 }
636 }
637 return 0;
638}
639
Eric Laurente0720872014-03-11 09:30:41 -0700640audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700641 uint32_t samplingRate,
642 audio_format_t format,
643 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700644 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700645 const audio_offload_info_t *offloadInfo)
646{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700647
Eric Laurent3b73df72014-03-11 09:06:29 -0700648 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700649 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
650 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
651 device, stream, samplingRate, format, channelMask, flags);
652
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700653 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
654 offloadInfo);
655}
656
657audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
658 uint32_t samplingRate,
659 audio_format_t format,
660 audio_channel_mask_t channelMask,
661 audio_output_flags_t flags,
662 const audio_offload_info_t *offloadInfo)
663{
664 if (attr == NULL) {
665 ALOGE("getOutputForAttr() called with NULL audio attributes");
666 return 0;
667 }
668 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
669 attr->usage, attr->content_type, attr->tags);
670
671 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
672 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
673 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
674 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
675 device, samplingRate, format, channelMask, flags);
676
677 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
678 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
679 offloadInfo);
680}
681
682audio_io_handle_t AudioPolicyManager::getOutputForDevice(
683 audio_devices_t device,
684 audio_stream_type_t stream,
685 uint32_t samplingRate,
686 audio_format_t format,
687 audio_channel_mask_t channelMask,
688 audio_output_flags_t flags,
689 const audio_offload_info_t *offloadInfo)
690{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700691 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700692 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700693 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700694
Eric Laurente552edb2014-03-10 17:42:56 -0700695#ifdef AUDIO_POLICY_TEST
696 if (mCurOutput != 0) {
697 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
698 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
699
700 if (mTestOutputs[mCurOutput] == 0) {
701 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700702 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700703 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700704 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700705 outputDesc->mFlags =
706 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700707 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700708 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
709 config.sample_rate = mTestSamplingRate;
710 config.channel_mask = mTestChannels;
711 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700712 if (offloadInfo != NULL) {
713 config.offload_info = *offloadInfo;
714 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700715 status = mpClientInterface->openOutput(0,
716 &mTestOutputs[mCurOutput],
717 &config,
718 &outputDesc->mDevice,
719 String8(""),
720 &outputDesc->mLatency,
721 outputDesc->mFlags);
722 if (status == NO_ERROR) {
723 outputDesc->mSamplingRate = config.sample_rate;
724 outputDesc->mFormat = config.format;
725 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700726 AudioParameter outputCmd = AudioParameter();
727 outputCmd.addInt(String8("set_id"),mCurOutput);
728 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
729 addOutput(mTestOutputs[mCurOutput], outputDesc);
730 }
731 }
732 return mTestOutputs[mCurOutput];
733 }
734#endif //AUDIO_POLICY_TEST
735
736 // open a direct output if required by specified parameters
737 //force direct flag if offload flag is set: offloading implies a direct output stream
738 // and all common behaviors are driven by checking only the direct flag
739 // this should normally be set appropriately in the policy configuration file
740 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700741 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700742 }
743
744 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
745 // creating an offloaded track and tearing it down immediately after start when audioflinger
746 // detects there is an active non offloadable effect.
747 // FIXME: We should check the audio session here but we do not have it in this context.
748 // This may prevent offloading in rare situations where effects are left active by apps
749 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700750 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700751 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
752 !isNonOffloadableEffectEnabled()) {
753 profile = getProfileForDirectOutput(device,
754 samplingRate,
755 format,
756 channelMask,
757 (audio_output_flags_t)flags);
758 }
759
Eric Laurent1c333e22014-05-20 10:48:17 -0700760 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700761 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700762
763 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700764 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700765 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
766 outputDesc = desc;
767 // reuse direct output if currently open and configured with same parameters
768 if ((samplingRate == outputDesc->mSamplingRate) &&
769 (format == outputDesc->mFormat) &&
770 (channelMask == outputDesc->mChannelMask)) {
771 outputDesc->mDirectOpenCount++;
772 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
773 return mOutputs.keyAt(i);
774 }
775 }
776 }
777 // close direct output if currently open and configured with different parameters
778 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700779 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700780 }
781 outputDesc = new AudioOutputDescriptor(profile);
782 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700783 outputDesc->mLatency = 0;
784 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700785 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
786 config.sample_rate = samplingRate;
787 config.channel_mask = channelMask;
788 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700789 if (offloadInfo != NULL) {
790 config.offload_info = *offloadInfo;
791 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700792 status = mpClientInterface->openOutput(profile->mModule->mHandle,
793 &output,
794 &config,
795 &outputDesc->mDevice,
796 String8(""),
797 &outputDesc->mLatency,
798 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700799
800 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700801 if (status != NO_ERROR ||
802 (samplingRate != 0 && samplingRate != config.sample_rate) ||
803 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
804 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700805 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
806 "format %d %d, channelMask %04x %04x", output, samplingRate,
807 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
808 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700809 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700810 mpClientInterface->closeOutput(output);
811 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700812 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700813 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700814 outputDesc->mSamplingRate = config.sample_rate;
815 outputDesc->mChannelMask = config.channel_mask;
816 outputDesc->mFormat = config.format;
817 outputDesc->mRefCount[stream] = 0;
818 outputDesc->mStopTime[stream] = 0;
819 outputDesc->mDirectOpenCount = 1;
820
Eric Laurente552edb2014-03-10 17:42:56 -0700821 audio_io_handle_t srcOutput = getOutputForEffect();
822 addOutput(output, outputDesc);
823 audio_io_handle_t dstOutput = getOutputForEffect();
824 if (dstOutput == output) {
825 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
826 }
827 mPreviousOutputs = mOutputs;
828 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700829 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700830 return output;
831 }
832
833 // ignoring channel mask due to downmix capability in mixer
834
835 // open a non direct output
836
837 // for non direct outputs, only PCM is supported
838 if (audio_is_linear_pcm(format)) {
839 // get which output is suitable for the specified stream. The actual
840 // routing change will happen when startOutput() will be called
841 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
842
843 output = selectOutput(outputs, flags);
844 }
845 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
846 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
847
848 ALOGV("getOutput() returns output %d", output);
849
850 return output;
851}
852
Eric Laurente0720872014-03-11 09:30:41 -0700853audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700854 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700855{
856 // select one output among several that provide a path to a particular device or set of
857 // devices (the list was previously build by getOutputsForDevice()).
858 // The priority is as follows:
859 // 1: the output with the highest number of requested policy flags
860 // 2: the primary output
861 // 3: the first output in the list
862
863 if (outputs.size() == 0) {
864 return 0;
865 }
866 if (outputs.size() == 1) {
867 return outputs[0];
868 }
869
870 int maxCommonFlags = 0;
871 audio_io_handle_t outputFlags = 0;
872 audio_io_handle_t outputPrimary = 0;
873
874 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700875 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700876 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700877 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700878 if (commonFlags > maxCommonFlags) {
879 outputFlags = outputs[i];
880 maxCommonFlags = commonFlags;
881 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
882 }
883 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
884 outputPrimary = outputs[i];
885 }
886 }
887 }
888
889 if (outputFlags != 0) {
890 return outputFlags;
891 }
892 if (outputPrimary != 0) {
893 return outputPrimary;
894 }
895
896 return outputs[0];
897}
898
Eric Laurente0720872014-03-11 09:30:41 -0700899status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700900 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700901 int session)
902{
903 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
904 ssize_t index = mOutputs.indexOfKey(output);
905 if (index < 0) {
906 ALOGW("startOutput() unknown output %d", output);
907 return BAD_VALUE;
908 }
909
Eric Laurent1f2f2232014-06-02 12:01:23 -0700910 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700911
912 // increment usage count for this stream on the requested output:
913 // NOTE that the usage count is the same for duplicated output and hardware output which is
914 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
915 outputDesc->changeRefCount(stream, 1);
916
917 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700918 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700919 routing_strategy strategy = getStrategy(stream);
920 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
921 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
922 uint32_t waitMs = 0;
923 bool force = false;
924 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700925 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700926 if (desc != outputDesc) {
927 // force a device change if any other output is managed by the same hw
928 // module and has a current device selection that differs from selected device.
929 // In this case, the audio HAL must receive the new device selection so that it can
930 // change the device currently selected by the other active output.
931 if (outputDesc->sharesHwModuleWith(desc) &&
932 desc->device() != newDevice) {
933 force = true;
934 }
935 // wait for audio on other active outputs to be presented when starting
936 // a notification so that audio focus effect can propagate.
937 uint32_t latency = desc->latency();
938 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
939 waitMs = latency;
940 }
941 }
942 }
943 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
944
945 // handle special case for sonification while in call
946 if (isInCall()) {
947 handleIncallSonification(stream, true, false);
948 }
949
950 // apply volume rules for current stream and device if necessary
951 checkAndSetVolume(stream,
952 mStreams[stream].getVolumeIndex(newDevice),
953 output,
954 newDevice);
955
956 // update the outputs if starting an output with a stream that can affect notification
957 // routing
958 handleNotificationRoutingForStream(stream);
959 if (waitMs > muteWaitMs) {
960 usleep((waitMs - muteWaitMs) * 2 * 1000);
961 }
962 }
963 return NO_ERROR;
964}
965
966
Eric Laurente0720872014-03-11 09:30:41 -0700967status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700968 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700969 int session)
970{
971 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
972 ssize_t index = mOutputs.indexOfKey(output);
973 if (index < 0) {
974 ALOGW("stopOutput() unknown output %d", output);
975 return BAD_VALUE;
976 }
977
Eric Laurent1f2f2232014-06-02 12:01:23 -0700978 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700979
980 // handle special case for sonification while in call
981 if (isInCall()) {
982 handleIncallSonification(stream, false, false);
983 }
984
985 if (outputDesc->mRefCount[stream] > 0) {
986 // decrement usage count of this stream on the output
987 outputDesc->changeRefCount(stream, -1);
988 // store time at which the stream was stopped - see isStreamActive()
989 if (outputDesc->mRefCount[stream] == 0) {
990 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700991 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700992 // delay the device switch by twice the latency because stopOutput() is executed when
993 // the track stop() command is received and at that time the audio track buffer can
994 // still contain data that needs to be drained. The latency only covers the audio HAL
995 // and kernel buffers. Also the latency does not always include additional delay in the
996 // audio path (audio DSP, CODEC ...)
997 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
998
999 // force restoring the device selection on other active outputs if it differs from the
1000 // one being selected for this output
1001 for (size_t i = 0; i < mOutputs.size(); i++) {
1002 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001003 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001004 if (curOutput != output &&
1005 desc->isActive() &&
1006 outputDesc->sharesHwModuleWith(desc) &&
1007 (newDevice != desc->device())) {
1008 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001009 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001010 true,
1011 outputDesc->mLatency*2);
1012 }
1013 }
1014 // update the outputs if stopping one with a stream that can affect notification routing
1015 handleNotificationRoutingForStream(stream);
1016 }
1017 return NO_ERROR;
1018 } else {
1019 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1020 return INVALID_OPERATION;
1021 }
1022}
1023
Eric Laurente0720872014-03-11 09:30:41 -07001024void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001025{
1026 ALOGV("releaseOutput() %d", output);
1027 ssize_t index = mOutputs.indexOfKey(output);
1028 if (index < 0) {
1029 ALOGW("releaseOutput() releasing unknown output %d", output);
1030 return;
1031 }
1032
1033#ifdef AUDIO_POLICY_TEST
1034 int testIndex = testOutputIndex(output);
1035 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001036 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001037 if (outputDesc->isActive()) {
1038 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001039 mOutputs.removeItem(output);
1040 mTestOutputs[testIndex] = 0;
1041 }
1042 return;
1043 }
1044#endif //AUDIO_POLICY_TEST
1045
Eric Laurent1f2f2232014-06-02 12:01:23 -07001046 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001047 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001048 if (desc->mDirectOpenCount <= 0) {
1049 ALOGW("releaseOutput() invalid open count %d for output %d",
1050 desc->mDirectOpenCount, output);
1051 return;
1052 }
1053 if (--desc->mDirectOpenCount == 0) {
1054 closeOutput(output);
1055 // If effects where present on the output, audioflinger moved them to the primary
1056 // output by default: move them back to the appropriate output.
1057 audio_io_handle_t dstOutput = getOutputForEffect();
1058 if (dstOutput != mPrimaryOutput) {
1059 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1060 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001061 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001062 }
1063 }
1064}
1065
1066
Eric Laurente0720872014-03-11 09:30:41 -07001067audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001068 uint32_t samplingRate,
1069 audio_format_t format,
1070 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001071 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001072 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001073{
Eric Laurent4dc68062014-07-28 17:26:49 -07001074 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001075 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001076 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001077
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001078 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001079
1080 if (device == AUDIO_DEVICE_NONE) {
1081 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001082 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001083 }
1084
1085 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001086 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001087 case AUDIO_SOURCE_VOICE_UPLINK:
1088 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1089 break;
1090 case AUDIO_SOURCE_VOICE_DOWNLINK:
1091 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1092 break;
1093 case AUDIO_SOURCE_VOICE_CALL:
1094 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1095 break;
1096 default:
1097 break;
1098 }
1099
Eric Laurent1c333e22014-05-20 10:48:17 -07001100 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001101 samplingRate,
1102 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001103 channelMask,
1104 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001105 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001106 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1107 "channelMask 0x%X, flags %#x",
1108 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001109 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001110 }
1111
1112 if (profile->mModule->mHandle == 0) {
1113 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001114 return AUDIO_IO_HANDLE_NONE;
1115 }
1116
1117 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1118 config.sample_rate = samplingRate;
1119 config.channel_mask = channelMask;
1120 config.format = format;
1121 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1122 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1123 &input,
1124 &config,
1125 &device,
1126 String8(""),
1127 inputSource,
1128 flags);
1129
1130 // only accept input with the exact requested set of parameters
1131 if (status != NO_ERROR ||
1132 (samplingRate != config.sample_rate) ||
1133 (format != config.format) ||
1134 (channelMask != config.channel_mask)) {
1135 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1136 samplingRate, format, channelMask);
1137 if (input != AUDIO_IO_HANDLE_NONE) {
1138 mpClientInterface->closeInput(input);
1139 }
1140 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001141 }
1142
Eric Laurent1f2f2232014-06-02 12:01:23 -07001143 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001144 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001145 inputDesc->mRefCount = 0;
1146 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001147 inputDesc->mSamplingRate = samplingRate;
1148 inputDesc->mFormat = format;
1149 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001150 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001151 inputDesc->mSessions.add(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001152
Eric Laurentd4692962014-05-05 18:13:44 -07001153 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001154 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001155 return input;
1156}
1157
Eric Laurent4dc68062014-07-28 17:26:49 -07001158status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1159 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001160{
1161 ALOGV("startInput() input %d", input);
1162 ssize_t index = mInputs.indexOfKey(input);
1163 if (index < 0) {
1164 ALOGW("startInput() unknown input %d", input);
1165 return BAD_VALUE;
1166 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001167 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001168
Eric Laurent4dc68062014-07-28 17:26:49 -07001169 index = inputDesc->mSessions.indexOf(session);
1170 if (index < 0) {
1171 ALOGW("startInput() unknown session %d on input %d", session, input);
1172 return BAD_VALUE;
1173 }
1174
Glenn Kasten74a8e252014-07-24 14:09:55 -07001175 // virtual input devices are compatible with other input devices
1176 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1177
1178 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001179 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001180 if (activeInput != 0 && activeInput != input) {
1181
1182 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1183 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001184 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001185 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001186 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001187 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1188 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001189 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001190 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001191 return INVALID_OPERATION;
1192 }
1193 }
1194 }
1195
Glenn Kasten74a8e252014-07-24 14:09:55 -07001196 if (inputDesc->mRefCount == 0) {
1197 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001198
Glenn Kasten74a8e252014-07-24 14:09:55 -07001199 // Automatically enable the remote submix output when input is started.
1200 // For remote submix (a virtual device), we open only one input per capture request.
1201 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1202 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1203 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1204 }
Eric Laurente552edb2014-03-10 17:42:56 -07001205 }
1206
Eric Laurente552edb2014-03-10 17:42:56 -07001207 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1208
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001209 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001210 return NO_ERROR;
1211}
1212
Eric Laurent4dc68062014-07-28 17:26:49 -07001213status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1214 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001215{
1216 ALOGV("stopInput() input %d", input);
1217 ssize_t index = mInputs.indexOfKey(input);
1218 if (index < 0) {
1219 ALOGW("stopInput() unknown input %d", input);
1220 return BAD_VALUE;
1221 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001222 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001223
Eric Laurent4dc68062014-07-28 17:26:49 -07001224 index = inputDesc->mSessions.indexOf(session);
1225 if (index < 0) {
1226 ALOGW("stopInput() unknown session %d on input %d", session, input);
1227 return BAD_VALUE;
1228 }
1229
Eric Laurente552edb2014-03-10 17:42:56 -07001230 if (inputDesc->mRefCount == 0) {
1231 ALOGW("stopInput() input %d already stopped", input);
1232 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001233 }
1234
1235 inputDesc->mRefCount--;
1236 if (inputDesc->mRefCount == 0) {
1237
Eric Laurente552edb2014-03-10 17:42:56 -07001238 // automatically disable the remote submix output when input is stopped
1239 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1240 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001241 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001242 }
1243
Eric Laurent1c333e22014-05-20 10:48:17 -07001244 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001245 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001246 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001247}
1248
Eric Laurent4dc68062014-07-28 17:26:49 -07001249void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1250 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001251{
1252 ALOGV("releaseInput() %d", input);
1253 ssize_t index = mInputs.indexOfKey(input);
1254 if (index < 0) {
1255 ALOGW("releaseInput() releasing unknown input %d", input);
1256 return;
1257 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001258 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1259 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001260
1261 index = inputDesc->mSessions.indexOf(session);
1262 if (index < 0) {
1263 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1264 return;
1265 }
1266 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001267 if (inputDesc->mOpenRefCount == 0) {
1268 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1269 return;
1270 }
1271 inputDesc->mOpenRefCount--;
1272 if (inputDesc->mOpenRefCount > 0) {
1273 ALOGV("releaseInput() exit > 0");
1274 return;
1275 }
1276
Eric Laurente552edb2014-03-10 17:42:56 -07001277 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001278 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001279 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001280 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001281 ALOGV("releaseInput() exit");
1282}
1283
Eric Laurentd4692962014-05-05 18:13:44 -07001284void AudioPolicyManager::closeAllInputs() {
1285 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1286 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1287 }
1288 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001289 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001290}
1291
Eric Laurente0720872014-03-11 09:30:41 -07001292void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001293 int indexMin,
1294 int indexMax)
1295{
1296 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1297 if (indexMin < 0 || indexMin >= indexMax) {
1298 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1299 return;
1300 }
1301 mStreams[stream].mIndexMin = indexMin;
1302 mStreams[stream].mIndexMax = indexMax;
1303}
1304
Eric Laurente0720872014-03-11 09:30:41 -07001305status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001306 int index,
1307 audio_devices_t device)
1308{
1309
1310 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1311 return BAD_VALUE;
1312 }
1313 if (!audio_is_output_device(device)) {
1314 return BAD_VALUE;
1315 }
1316
1317 // Force max volume if stream cannot be muted
1318 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1319
1320 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1321 stream, device, index);
1322
1323 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1324 // clear all device specific values
1325 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1326 mStreams[stream].mIndexCur.clear();
1327 }
1328 mStreams[stream].mIndexCur.add(device, index);
1329
1330 // compute and apply stream volume on all outputs according to connected device
1331 status_t status = NO_ERROR;
1332 for (size_t i = 0; i < mOutputs.size(); i++) {
1333 audio_devices_t curDevice =
1334 getDeviceForVolume(mOutputs.valueAt(i)->device());
1335 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1336 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1337 if (volStatus != NO_ERROR) {
1338 status = volStatus;
1339 }
1340 }
1341 }
1342 return status;
1343}
1344
Eric Laurente0720872014-03-11 09:30:41 -07001345status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001346 int *index,
1347 audio_devices_t device)
1348{
1349 if (index == NULL) {
1350 return BAD_VALUE;
1351 }
1352 if (!audio_is_output_device(device)) {
1353 return BAD_VALUE;
1354 }
1355 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1356 // the strategy the stream belongs to.
1357 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1358 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1359 }
1360 device = getDeviceForVolume(device);
1361
1362 *index = mStreams[stream].getVolumeIndex(device);
1363 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1364 return NO_ERROR;
1365}
1366
Eric Laurente0720872014-03-11 09:30:41 -07001367audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001368 const SortedVector<audio_io_handle_t>& outputs)
1369{
1370 // select one output among several suitable for global effects.
1371 // The priority is as follows:
1372 // 1: An offloaded output. If the effect ends up not being offloadable,
1373 // AudioFlinger will invalidate the track and the offloaded output
1374 // will be closed causing the effect to be moved to a PCM output.
1375 // 2: A deep buffer output
1376 // 3: the first output in the list
1377
1378 if (outputs.size() == 0) {
1379 return 0;
1380 }
1381
1382 audio_io_handle_t outputOffloaded = 0;
1383 audio_io_handle_t outputDeepBuffer = 0;
1384
1385 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001386 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001387 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001388 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1389 outputOffloaded = outputs[i];
1390 }
1391 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1392 outputDeepBuffer = outputs[i];
1393 }
1394 }
1395
1396 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1397 outputOffloaded, outputDeepBuffer);
1398 if (outputOffloaded != 0) {
1399 return outputOffloaded;
1400 }
1401 if (outputDeepBuffer != 0) {
1402 return outputDeepBuffer;
1403 }
1404
1405 return outputs[0];
1406}
1407
Eric Laurente0720872014-03-11 09:30:41 -07001408audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001409{
1410 // apply simple rule where global effects are attached to the same output as MUSIC streams
1411
Eric Laurent3b73df72014-03-11 09:06:29 -07001412 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001413 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1414 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1415
1416 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1417 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1418 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1419
1420 return output;
1421}
1422
Eric Laurente0720872014-03-11 09:30:41 -07001423status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001424 audio_io_handle_t io,
1425 uint32_t strategy,
1426 int session,
1427 int id)
1428{
1429 ssize_t index = mOutputs.indexOfKey(io);
1430 if (index < 0) {
1431 index = mInputs.indexOfKey(io);
1432 if (index < 0) {
1433 ALOGW("registerEffect() unknown io %d", io);
1434 return INVALID_OPERATION;
1435 }
1436 }
1437
1438 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1439 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1440 desc->name, desc->memoryUsage);
1441 return INVALID_OPERATION;
1442 }
1443 mTotalEffectsMemory += desc->memoryUsage;
1444 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1445 desc->name, io, strategy, session, id);
1446 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1447
Eric Laurent1f2f2232014-06-02 12:01:23 -07001448 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1449 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1450 effectDesc->mIo = io;
1451 effectDesc->mStrategy = (routing_strategy)strategy;
1452 effectDesc->mSession = session;
1453 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001454
Eric Laurent1f2f2232014-06-02 12:01:23 -07001455 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001456
1457 return NO_ERROR;
1458}
1459
Eric Laurente0720872014-03-11 09:30:41 -07001460status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001461{
1462 ssize_t index = mEffects.indexOfKey(id);
1463 if (index < 0) {
1464 ALOGW("unregisterEffect() unknown effect ID %d", id);
1465 return INVALID_OPERATION;
1466 }
1467
Eric Laurent1f2f2232014-06-02 12:01:23 -07001468 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001469
Eric Laurent1f2f2232014-06-02 12:01:23 -07001470 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001471
Eric Laurent1f2f2232014-06-02 12:01:23 -07001472 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001473 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001474 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1475 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001476 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001477 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001478 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001479 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001480
1481 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001482
1483 return NO_ERROR;
1484}
1485
Eric Laurente0720872014-03-11 09:30:41 -07001486status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001487{
1488 ssize_t index = mEffects.indexOfKey(id);
1489 if (index < 0) {
1490 ALOGW("unregisterEffect() unknown effect ID %d", id);
1491 return INVALID_OPERATION;
1492 }
1493
1494 return setEffectEnabled(mEffects.valueAt(index), enabled);
1495}
1496
Eric Laurent1f2f2232014-06-02 12:01:23 -07001497status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001498{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001499 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001500 ALOGV("setEffectEnabled(%s) effect already %s",
1501 enabled?"true":"false", enabled?"enabled":"disabled");
1502 return INVALID_OPERATION;
1503 }
1504
1505 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001506 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001507 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001508 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001509 return INVALID_OPERATION;
1510 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001511 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001512 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1513 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001514 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001515 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001516 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1517 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001518 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001519 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001520 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1521 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001522 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001523 return NO_ERROR;
1524}
1525
Eric Laurente0720872014-03-11 09:30:41 -07001526bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001527{
1528 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001529 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1530 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1531 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001532 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001533 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001534 return true;
1535 }
1536 }
1537 return false;
1538}
1539
Eric Laurente0720872014-03-11 09:30:41 -07001540bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001541{
1542 nsecs_t sysTime = systemTime();
1543 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001544 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001545 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001546 return true;
1547 }
1548 }
1549 return false;
1550}
1551
Eric Laurente0720872014-03-11 09:30:41 -07001552bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001553 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001554{
1555 nsecs_t sysTime = systemTime();
1556 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001557 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001558 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001559 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001560 return true;
1561 }
1562 }
1563 return false;
1564}
1565
Eric Laurente0720872014-03-11 09:30:41 -07001566bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001567{
1568 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001569 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001570 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001571 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001572 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1573 && (inputDescriptor->mRefCount > 0)) {
1574 return true;
1575 }
1576 }
1577 return false;
1578}
1579
1580
Eric Laurente0720872014-03-11 09:30:41 -07001581status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001582{
1583 const size_t SIZE = 256;
1584 char buffer[SIZE];
1585 String8 result;
1586
1587 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1588 result.append(buffer);
1589
1590 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1591 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001592 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1593 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001594 snprintf(buffer, SIZE, " Force use for communications %d\n",
1595 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001596 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001597 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001598 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001599 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001600 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001601 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001602 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001603 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001604 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001605 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1606 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1607 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001608
Eric Laurent3a4311c2014-03-17 12:00:47 -07001609 snprintf(buffer, SIZE, " Available output devices:\n");
1610 result.append(buffer);
1611 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001612 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001613 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001614 }
1615 snprintf(buffer, SIZE, "\n Available input devices:\n");
1616 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001617 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001618 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001619 }
Eric Laurente552edb2014-03-10 17:42:56 -07001620
1621 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1622 write(fd, buffer, strlen(buffer));
1623 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001624 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001625 write(fd, buffer, strlen(buffer));
1626 mHwModules[i]->dump(fd);
1627 }
1628
1629 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1630 write(fd, buffer, strlen(buffer));
1631 for (size_t i = 0; i < mOutputs.size(); i++) {
1632 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1633 write(fd, buffer, strlen(buffer));
1634 mOutputs.valueAt(i)->dump(fd);
1635 }
1636
1637 snprintf(buffer, SIZE, "\nInputs dump:\n");
1638 write(fd, buffer, strlen(buffer));
1639 for (size_t i = 0; i < mInputs.size(); i++) {
1640 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1641 write(fd, buffer, strlen(buffer));
1642 mInputs.valueAt(i)->dump(fd);
1643 }
1644
1645 snprintf(buffer, SIZE, "\nStreams dump:\n");
1646 write(fd, buffer, strlen(buffer));
1647 snprintf(buffer, SIZE,
1648 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1649 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001650 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001651 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001652 write(fd, buffer, strlen(buffer));
1653 mStreams[i].dump(fd);
1654 }
1655
1656 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1657 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1658 write(fd, buffer, strlen(buffer));
1659
1660 snprintf(buffer, SIZE, "Registered effects:\n");
1661 write(fd, buffer, strlen(buffer));
1662 for (size_t i = 0; i < mEffects.size(); i++) {
1663 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1664 write(fd, buffer, strlen(buffer));
1665 mEffects.valueAt(i)->dump(fd);
1666 }
1667
1668
1669 return NO_ERROR;
1670}
1671
1672// This function checks for the parameters which can be offloaded.
1673// This can be enhanced depending on the capability of the DSP and policy
1674// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001675bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001676{
1677 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001678 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001679 offloadInfo.sample_rate, offloadInfo.channel_mask,
1680 offloadInfo.format,
1681 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1682 offloadInfo.has_video);
1683
1684 // Check if offload has been disabled
1685 char propValue[PROPERTY_VALUE_MAX];
1686 if (property_get("audio.offload.disable", propValue, "0")) {
1687 if (atoi(propValue) != 0) {
1688 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1689 return false;
1690 }
1691 }
1692
1693 // Check if stream type is music, then only allow offload as of now.
1694 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1695 {
1696 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1697 return false;
1698 }
1699
1700 //TODO: enable audio offloading with video when ready
1701 if (offloadInfo.has_video)
1702 {
1703 ALOGV("isOffloadSupported: has_video == true, returning false");
1704 return false;
1705 }
1706
1707 //If duration is less than minimum value defined in property, return false
1708 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1709 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1710 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1711 return false;
1712 }
1713 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1714 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1715 return false;
1716 }
1717
1718 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1719 // creating an offloaded track and tearing it down immediately after start when audioflinger
1720 // detects there is an active non offloadable effect.
1721 // FIXME: We should check the audio session here but we do not have it in this context.
1722 // This may prevent offloading in rare situations where effects are left active by apps
1723 // in the background.
1724 if (isNonOffloadableEffectEnabled()) {
1725 return false;
1726 }
1727
1728 // See if there is a profile to support this.
1729 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001730 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001731 offloadInfo.sample_rate,
1732 offloadInfo.format,
1733 offloadInfo.channel_mask,
1734 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001735 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1736 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001737}
1738
Eric Laurent6a94d692014-05-20 11:18:06 -07001739status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1740 audio_port_type_t type,
1741 unsigned int *num_ports,
1742 struct audio_port *ports,
1743 unsigned int *generation)
1744{
1745 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1746 generation == NULL) {
1747 return BAD_VALUE;
1748 }
1749 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1750 if (ports == NULL) {
1751 *num_ports = 0;
1752 }
1753
1754 size_t portsWritten = 0;
1755 size_t portsMax = *num_ports;
1756 *num_ports = 0;
1757 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1758 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1759 for (size_t i = 0;
1760 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1761 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1762 }
1763 *num_ports += mAvailableOutputDevices.size();
1764 }
1765 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1766 for (size_t i = 0;
1767 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1768 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1769 }
1770 *num_ports += mAvailableInputDevices.size();
1771 }
1772 }
1773 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1774 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1775 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1776 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1777 }
1778 *num_ports += mInputs.size();
1779 }
1780 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001781 size_t numOutputs = 0;
1782 for (size_t i = 0; i < mOutputs.size(); i++) {
1783 if (!mOutputs[i]->isDuplicated()) {
1784 numOutputs++;
1785 if (portsWritten < portsMax) {
1786 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1787 }
1788 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001789 }
Eric Laurent84c70242014-06-23 08:46:27 -07001790 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001791 }
1792 }
1793 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001794 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001795 return NO_ERROR;
1796}
1797
1798status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1799{
1800 return NO_ERROR;
1801}
1802
Eric Laurent1f2f2232014-06-02 12:01:23 -07001803sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001804 audio_port_handle_t id) const
1805{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001806 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001807 for (size_t i = 0; i < mOutputs.size(); i++) {
1808 outputDesc = mOutputs.valueAt(i);
1809 if (outputDesc->mId == id) {
1810 break;
1811 }
1812 }
1813 return outputDesc;
1814}
1815
Eric Laurent1f2f2232014-06-02 12:01:23 -07001816sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001817 audio_port_handle_t id) const
1818{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001819 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001820 for (size_t i = 0; i < mInputs.size(); i++) {
1821 inputDesc = mInputs.valueAt(i);
1822 if (inputDesc->mId == id) {
1823 break;
1824 }
1825 }
1826 return inputDesc;
1827}
1828
Eric Laurent1f2f2232014-06-02 12:01:23 -07001829sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1830 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001831{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001832 sp <HwModule> module;
1833
Eric Laurent6a94d692014-05-20 11:18:06 -07001834 for (size_t i = 0; i < mHwModules.size(); i++) {
1835 if (mHwModules[i]->mHandle == 0) {
1836 continue;
1837 }
1838 if (audio_is_output_device(device)) {
1839 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1840 {
1841 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1842 return mHwModules[i];
1843 }
1844 }
1845 } else {
1846 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1847 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1848 device & ~AUDIO_DEVICE_BIT_IN) {
1849 return mHwModules[i];
1850 }
1851 }
1852 }
1853 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001854 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001855}
1856
Eric Laurent1f2f2232014-06-02 12:01:23 -07001857sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001858{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001859 sp <HwModule> module;
1860
Eric Laurent1afeecb2014-05-14 08:52:28 -07001861 for (size_t i = 0; i < mHwModules.size(); i++)
1862 {
1863 if (strcmp(mHwModules[i]->mName, name) == 0) {
1864 return mHwModules[i];
1865 }
1866 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001867 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001868}
1869
1870
Eric Laurent6a94d692014-05-20 11:18:06 -07001871status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1872 audio_patch_handle_t *handle,
1873 uid_t uid)
1874{
1875 ALOGV("createAudioPatch()");
1876
1877 if (handle == NULL || patch == NULL) {
1878 return BAD_VALUE;
1879 }
1880 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1881
1882 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1883 return INVALID_OPERATION;
1884 }
1885 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1886 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1887 return INVALID_OPERATION;
1888 }
1889
1890 sp<AudioPatch> patchDesc;
1891 ssize_t index = mAudioPatches.indexOfKey(*handle);
1892
1893 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1894 patch->sinks[0].type);
1895 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1896 patch->sources[0].role,
1897 patch->sources[0].type);
1898
1899 if (index >= 0) {
1900 patchDesc = mAudioPatches.valueAt(index);
1901 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1902 mUidCached, patchDesc->mUid, uid);
1903 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1904 return INVALID_OPERATION;
1905 }
1906 } else {
1907 *handle = 0;
1908 }
1909
1910 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1911 // TODO add support for mix to mix connection
1912 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1913 ALOGV("createAudioPatch() source mix sink not device");
1914 return BAD_VALUE;
1915 }
1916 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001917 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001918 if (outputDesc == NULL) {
1919 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1920 return BAD_VALUE;
1921 }
Eric Laurent84c70242014-06-23 08:46:27 -07001922 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1923 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001924 if (patchDesc != 0) {
1925 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1926 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1927 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1928 return BAD_VALUE;
1929 }
1930 }
1931 sp<DeviceDescriptor> devDesc =
1932 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1933 if (devDesc == 0) {
1934 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1935 return BAD_VALUE;
1936 }
1937
Eric Laurent84c70242014-06-23 08:46:27 -07001938 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001939 patch->sources[0].sample_rate,
Glenn Kastencbd48022014-07-24 13:46:44 -07001940 NULL, // updatedSamplingRate
Eric Laurent6a94d692014-05-20 11:18:06 -07001941 patch->sources[0].format,
1942 patch->sources[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001943 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Eric Laurent83b88082014-06-20 18:31:16 -07001944 ALOGV("createAudioPatch() profile not supported");
Eric Laurent6a94d692014-05-20 11:18:06 -07001945 return INVALID_OPERATION;
1946 }
1947 // TODO: reconfigure output format and channels here
1948 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001949 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001950 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001951 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001952 true,
1953 0,
1954 handle);
1955 index = mAudioPatches.indexOfKey(*handle);
1956 if (index >= 0) {
1957 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1958 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1959 }
1960 patchDesc = mAudioPatches.valueAt(index);
1961 patchDesc->mUid = uid;
1962 ALOGV("createAudioPatch() success");
1963 } else {
1964 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1965 return INVALID_OPERATION;
1966 }
1967 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1968 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1969 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001970 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001971 if (inputDesc == NULL) {
1972 return BAD_VALUE;
1973 }
1974 if (patchDesc != 0) {
1975 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1976 return BAD_VALUE;
1977 }
1978 }
1979 sp<DeviceDescriptor> devDesc =
1980 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1981 if (devDesc == 0) {
1982 return BAD_VALUE;
1983 }
1984
Eric Laurent84c70242014-06-23 08:46:27 -07001985 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07001986 patch->sinks[0].sample_rate,
1987 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07001988 patch->sinks[0].format,
1989 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001990 // FIXME for the parameter type,
1991 // and the NONE
1992 (audio_output_flags_t)
1993 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07001994 return INVALID_OPERATION;
1995 }
1996 // TODO: reconfigure output format and channels here
1997 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001998 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001999 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07002000 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07002001 true,
2002 handle);
2003 index = mAudioPatches.indexOfKey(*handle);
2004 if (index >= 0) {
2005 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2006 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2007 }
2008 patchDesc = mAudioPatches.valueAt(index);
2009 patchDesc->mUid = uid;
2010 ALOGV("createAudioPatch() success");
2011 } else {
2012 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2013 return INVALID_OPERATION;
2014 }
2015 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2016 // device to device connection
2017 if (patchDesc != 0) {
2018 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
2019 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2020 return BAD_VALUE;
2021 }
2022 }
2023
2024 sp<DeviceDescriptor> srcDeviceDesc =
2025 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2026 sp<DeviceDescriptor> sinkDeviceDesc =
2027 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
2028 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
2029 return BAD_VALUE;
2030 }
2031 //update source and sink with our own data as the data passed in the patch may
2032 // be incomplete.
2033 struct audio_patch newPatch = *patch;
2034 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
2035 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
2036
Eric Laurent6a94d692014-05-20 11:18:06 -07002037 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
Eric Laurent83b88082014-06-20 18:31:16 -07002038 SortedVector<audio_io_handle_t> outputs =
2039 getOutputsForDevice(sinkDeviceDesc->mDeviceType, mOutputs);
2040 // if the sink device is reachable via an opened output stream, request to go via
2041 // this output stream by adding a second source to the patch description
2042 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2043 if (output != AUDIO_IO_HANDLE_NONE) {
2044 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2045 if (outputDesc->isDuplicated()) {
2046 return INVALID_OPERATION;
2047 }
2048 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2049 newPatch.num_sources = 2;
2050 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002051 }
2052 // TODO: check from routing capabilities in config file and other conflicting patches
2053
2054 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2055 if (index >= 0) {
2056 afPatchHandle = patchDesc->mAfPatchHandle;
2057 }
2058
2059 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2060 &afPatchHandle,
2061 0);
2062 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2063 status, afPatchHandle);
2064 if (status == NO_ERROR) {
2065 if (index < 0) {
2066 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2067 &newPatch, uid);
2068 addAudioPatch(patchDesc->mHandle, patchDesc);
2069 } else {
2070 patchDesc->mPatch = newPatch;
2071 }
2072 patchDesc->mAfPatchHandle = afPatchHandle;
2073 *handle = patchDesc->mHandle;
2074 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002075 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002076 } else {
2077 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2078 status);
2079 return INVALID_OPERATION;
2080 }
2081 } else {
2082 return BAD_VALUE;
2083 }
2084 } else {
2085 return BAD_VALUE;
2086 }
2087 return NO_ERROR;
2088}
2089
2090status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2091 uid_t uid)
2092{
2093 ALOGV("releaseAudioPatch() patch %d", handle);
2094
2095 ssize_t index = mAudioPatches.indexOfKey(handle);
2096
2097 if (index < 0) {
2098 return BAD_VALUE;
2099 }
2100 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2101 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2102 mUidCached, patchDesc->mUid, uid);
2103 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2104 return INVALID_OPERATION;
2105 }
2106
2107 struct audio_patch *patch = &patchDesc->mPatch;
2108 patchDesc->mUid = mUidCached;
2109 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002110 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002111 if (outputDesc == NULL) {
2112 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2113 return BAD_VALUE;
2114 }
2115
2116 setOutputDevice(outputDesc->mIoHandle,
2117 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2118 true,
2119 0,
2120 NULL);
2121 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2122 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002123 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002124 if (inputDesc == NULL) {
2125 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2126 return BAD_VALUE;
2127 }
2128 setInputDevice(inputDesc->mIoHandle,
2129 getNewInputDevice(inputDesc->mIoHandle),
2130 true,
2131 NULL);
2132 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2133 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2134 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2135 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2136 status, patchDesc->mAfPatchHandle);
2137 removeAudioPatch(patchDesc->mHandle);
2138 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002139 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002140 } else {
2141 return BAD_VALUE;
2142 }
2143 } else {
2144 return BAD_VALUE;
2145 }
2146 return NO_ERROR;
2147}
2148
2149status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2150 struct audio_patch *patches,
2151 unsigned int *generation)
2152{
2153 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2154 generation == NULL) {
2155 return BAD_VALUE;
2156 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002157 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002158 *num_patches, patches, mAudioPatches.size());
2159 if (patches == NULL) {
2160 *num_patches = 0;
2161 }
2162
2163 size_t patchesWritten = 0;
2164 size_t patchesMax = *num_patches;
2165 for (size_t i = 0;
2166 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2167 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2168 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002169 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002170 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2171 }
2172 *num_patches = mAudioPatches.size();
2173
2174 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002175 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002176 return NO_ERROR;
2177}
2178
Eric Laurente1715a42014-05-20 11:30:42 -07002179status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002180{
Eric Laurente1715a42014-05-20 11:30:42 -07002181 ALOGV("setAudioPortConfig()");
2182
2183 if (config == NULL) {
2184 return BAD_VALUE;
2185 }
2186 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2187 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002188 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2189 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002190 }
2191
Eric Laurenta121f902014-06-03 13:32:54 -07002192 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002193 if (config->type == AUDIO_PORT_TYPE_MIX) {
2194 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002195 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002196 if (outputDesc == NULL) {
2197 return BAD_VALUE;
2198 }
Eric Laurent84c70242014-06-23 08:46:27 -07002199 ALOG_ASSERT(!outputDesc->isDuplicated(),
2200 "setAudioPortConfig() called on duplicated output %d",
2201 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002202 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002203 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002204 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002205 if (inputDesc == NULL) {
2206 return BAD_VALUE;
2207 }
Eric Laurenta121f902014-06-03 13:32:54 -07002208 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002209 } else {
2210 return BAD_VALUE;
2211 }
2212 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2213 sp<DeviceDescriptor> deviceDesc;
2214 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2215 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2216 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2217 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2218 } else {
2219 return BAD_VALUE;
2220 }
2221 if (deviceDesc == NULL) {
2222 return BAD_VALUE;
2223 }
Eric Laurenta121f902014-06-03 13:32:54 -07002224 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002225 } else {
2226 return BAD_VALUE;
2227 }
2228
Eric Laurenta121f902014-06-03 13:32:54 -07002229 struct audio_port_config backupConfig;
2230 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2231 if (status == NO_ERROR) {
2232 struct audio_port_config newConfig;
2233 audioPortConfig->toAudioPortConfig(&newConfig, config);
2234 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002235 }
Eric Laurenta121f902014-06-03 13:32:54 -07002236 if (status != NO_ERROR) {
2237 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002238 }
Eric Laurente1715a42014-05-20 11:30:42 -07002239
2240 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002241}
2242
2243void AudioPolicyManager::clearAudioPatches(uid_t uid)
2244{
2245 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2246 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2247 if (patchDesc->mUid == uid) {
2248 // releaseAudioPatch() removes the patch from mAudioPatches
2249 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2250 i--;
2251 }
2252 }
2253 }
2254}
2255
2256status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2257 const sp<AudioPatch>& patch)
2258{
2259 ssize_t index = mAudioPatches.indexOfKey(handle);
2260
2261 if (index >= 0) {
2262 ALOGW("addAudioPatch() patch %d already in", handle);
2263 return ALREADY_EXISTS;
2264 }
2265 mAudioPatches.add(handle, patch);
2266 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2267 "sink handle %d",
2268 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2269 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2270 return NO_ERROR;
2271}
2272
2273status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2274{
2275 ssize_t index = mAudioPatches.indexOfKey(handle);
2276
2277 if (index < 0) {
2278 ALOGW("removeAudioPatch() patch %d not in", handle);
2279 return ALREADY_EXISTS;
2280 }
2281 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2282 mAudioPatches.valueAt(index)->mAfPatchHandle);
2283 mAudioPatches.removeItemsAt(index);
2284 return NO_ERROR;
2285}
2286
Eric Laurente552edb2014-03-10 17:42:56 -07002287// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002288// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002289// ----------------------------------------------------------------------------
2290
Eric Laurent3a4311c2014-03-17 12:00:47 -07002291uint32_t AudioPolicyManager::nextUniqueId()
2292{
2293 return android_atomic_inc(&mNextUniqueId);
2294}
2295
Eric Laurent6a94d692014-05-20 11:18:06 -07002296uint32_t AudioPolicyManager::nextAudioPortGeneration()
2297{
2298 return android_atomic_inc(&mAudioPortGeneration);
2299}
2300
Eric Laurente0720872014-03-11 09:30:41 -07002301AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002302 :
2303#ifdef AUDIO_POLICY_TEST
2304 Thread(false),
2305#endif //AUDIO_POLICY_TEST
2306 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002307 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002308 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2309 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002310 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002311 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2312 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002313{
Eric Laurent6a94d692014-05-20 11:18:06 -07002314 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002315 mpClientInterface = clientInterface;
2316
Eric Laurent3b73df72014-03-11 09:06:29 -07002317 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2318 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002319 }
2320
Eric Laurent1afeecb2014-05-14 08:52:28 -07002321 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002322 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2323 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2324 ALOGE("could not load audio policy configuration file, setting defaults");
2325 defaultAudioPolicyConfig();
2326 }
2327 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002328 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002329
2330 // must be done after reading the policy
2331 initializeVolumeCurves();
2332
2333 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002334 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2335 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002336 for (size_t i = 0; i < mHwModules.size(); i++) {
2337 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2338 if (mHwModules[i]->mHandle == 0) {
2339 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2340 continue;
2341 }
2342 // open all output streams needed to access attached devices
2343 // except for direct output streams that are only opened when they are actually
2344 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002345 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002346 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2347 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002348 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002349
Eric Laurent3a4311c2014-03-17 12:00:47 -07002350 if (outProfile->mSupportedDevices.isEmpty()) {
2351 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2352 continue;
2353 }
2354
Eric Laurent83b88082014-06-20 18:31:16 -07002355 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2356 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2357 profileType = mDefaultOutputDevice->mDeviceType;
2358 } else {
2359 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2360 }
2361 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002362 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002363 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002364
Eric Laurent83b88082014-06-20 18:31:16 -07002365 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002366 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2367 config.sample_rate = outputDesc->mSamplingRate;
2368 config.channel_mask = outputDesc->mChannelMask;
2369 config.format = outputDesc->mFormat;
2370 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2371 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2372 &output,
2373 &config,
2374 &outputDesc->mDevice,
2375 String8(""),
2376 &outputDesc->mLatency,
2377 outputDesc->mFlags);
2378
2379 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002380 ALOGW("Cannot open output stream for device %08x on hw module %s",
2381 outputDesc->mDevice,
2382 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002383 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002384 outputDesc->mSamplingRate = config.sample_rate;
2385 outputDesc->mChannelMask = config.channel_mask;
2386 outputDesc->mFormat = config.format;
2387
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002388 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002389 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002390 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002391 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002392 // give a valid ID to an attached device once confirmed it is reachable
2393 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2394 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002395 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002396 }
2397 }
Eric Laurente552edb2014-03-10 17:42:56 -07002398 if (mPrimaryOutput == 0 &&
2399 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2400 mPrimaryOutput = output;
2401 }
2402 addOutput(output, outputDesc);
2403 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002404 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002405 true);
2406 }
2407 }
2408 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002409 // open input streams needed to access attached devices to validate
2410 // mAvailableInputDevices list
2411 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2412 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002413 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002414
Eric Laurent3a4311c2014-03-17 12:00:47 -07002415 if (inProfile->mSupportedDevices.isEmpty()) {
2416 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2417 continue;
2418 }
2419
Eric Laurent83b88082014-06-20 18:31:16 -07002420 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2421 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002422 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002423
2424 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002425 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002426
Eric Laurentcf2c0212014-07-25 16:20:43 -07002427 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2428 config.sample_rate = inputDesc->mSamplingRate;
2429 config.channel_mask = inputDesc->mChannelMask;
2430 config.format = inputDesc->mFormat;
2431 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2432 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2433 &input,
2434 &config,
2435 &inputDesc->mDevice,
2436 String8(""),
2437 AUDIO_SOURCE_MIC,
2438 AUDIO_INPUT_FLAG_NONE);
2439
2440 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002441 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002442 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002443 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002444 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002445 // give a valid ID to an attached device once confirmed it is reachable
2446 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2447 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002448 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002449 }
2450 }
2451 mpClientInterface->closeInput(input);
2452 } else {
2453 ALOGW("Cannot open input stream for device %08x on hw module %s",
2454 inputDesc->mDevice,
2455 mHwModules[i]->mName);
2456 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002457 }
2458 }
2459 }
2460 // make sure all attached devices have been allocated a unique ID
2461 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2462 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002463 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002464 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2465 continue;
2466 }
2467 i++;
2468 }
2469 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2470 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002471 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002472 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2473 continue;
2474 }
2475 i++;
2476 }
2477 // make sure default device is reachable
2478 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002479 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002480 }
Eric Laurente552edb2014-03-10 17:42:56 -07002481
2482 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2483
2484 updateDevicesAndOutputs();
2485
2486#ifdef AUDIO_POLICY_TEST
2487 if (mPrimaryOutput != 0) {
2488 AudioParameter outputCmd = AudioParameter();
2489 outputCmd.addInt(String8("set_id"), 0);
2490 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2491
2492 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2493 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002494 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2495 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002496 mTestLatencyMs = 0;
2497 mCurOutput = 0;
2498 mDirectOutput = false;
2499 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2500 mTestOutputs[i] = 0;
2501 }
2502
2503 const size_t SIZE = 256;
2504 char buffer[SIZE];
2505 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2506 run(buffer, ANDROID_PRIORITY_AUDIO);
2507 }
2508#endif //AUDIO_POLICY_TEST
2509}
2510
Eric Laurente0720872014-03-11 09:30:41 -07002511AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002512{
2513#ifdef AUDIO_POLICY_TEST
2514 exit();
2515#endif //AUDIO_POLICY_TEST
2516 for (size_t i = 0; i < mOutputs.size(); i++) {
2517 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002518 }
2519 for (size_t i = 0; i < mInputs.size(); i++) {
2520 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002521 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002522 mAvailableOutputDevices.clear();
2523 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002524 mOutputs.clear();
2525 mInputs.clear();
2526 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002527}
2528
Eric Laurente0720872014-03-11 09:30:41 -07002529status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002530{
2531 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2532}
2533
2534#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002535bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002536{
2537 ALOGV("entering threadLoop()");
2538 while (!exitPending())
2539 {
2540 String8 command;
2541 int valueInt;
2542 String8 value;
2543
2544 Mutex::Autolock _l(mLock);
2545 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2546
2547 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2548 AudioParameter param = AudioParameter(command);
2549
2550 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2551 valueInt != 0) {
2552 ALOGV("Test command %s received", command.string());
2553 String8 target;
2554 if (param.get(String8("target"), target) != NO_ERROR) {
2555 target = "Manager";
2556 }
2557 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2558 param.remove(String8("test_cmd_policy_output"));
2559 mCurOutput = valueInt;
2560 }
2561 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2562 param.remove(String8("test_cmd_policy_direct"));
2563 if (value == "false") {
2564 mDirectOutput = false;
2565 } else if (value == "true") {
2566 mDirectOutput = true;
2567 }
2568 }
2569 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2570 param.remove(String8("test_cmd_policy_input"));
2571 mTestInput = valueInt;
2572 }
2573
2574 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2575 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002576 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002577 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002578 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002579 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002580 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002581 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002582 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002583 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002584 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002585 if (target == "Manager") {
2586 mTestFormat = format;
2587 } else if (mTestOutputs[mCurOutput] != 0) {
2588 AudioParameter outputParam = AudioParameter();
2589 outputParam.addInt(String8("format"), format);
2590 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2591 }
2592 }
2593 }
2594 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2595 param.remove(String8("test_cmd_policy_channels"));
2596 int channels = 0;
2597
2598 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002599 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002600 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002601 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002602 }
2603 if (channels != 0) {
2604 if (target == "Manager") {
2605 mTestChannels = channels;
2606 } else if (mTestOutputs[mCurOutput] != 0) {
2607 AudioParameter outputParam = AudioParameter();
2608 outputParam.addInt(String8("channels"), channels);
2609 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2610 }
2611 }
2612 }
2613 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2614 param.remove(String8("test_cmd_policy_sampleRate"));
2615 if (valueInt >= 0 && valueInt <= 96000) {
2616 int samplingRate = valueInt;
2617 if (target == "Manager") {
2618 mTestSamplingRate = samplingRate;
2619 } else if (mTestOutputs[mCurOutput] != 0) {
2620 AudioParameter outputParam = AudioParameter();
2621 outputParam.addInt(String8("sampling_rate"), samplingRate);
2622 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2623 }
2624 }
2625 }
2626
2627 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2628 param.remove(String8("test_cmd_policy_reopen"));
2629
Eric Laurent1f2f2232014-06-02 12:01:23 -07002630 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002631 mpClientInterface->closeOutput(mPrimaryOutput);
2632
2633 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2634
Eric Laurente552edb2014-03-10 17:42:56 -07002635 mOutputs.removeItem(mPrimaryOutput);
2636
Eric Laurent1f2f2232014-06-02 12:01:23 -07002637 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002638 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002639 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2640 config.sample_rate = outputDesc->mSamplingRate;
2641 config.channel_mask = outputDesc->mChannelMask;
2642 config.format = outputDesc->mFormat;
2643 status_t status = mpClientInterface->openOutput(moduleHandle,
2644 &mPrimaryOutput,
2645 &config,
2646 &outputDesc->mDevice,
2647 String8(""),
2648 &outputDesc->mLatency,
2649 outputDesc->mFlags);
2650 if (status != NO_ERROR) {
2651 ALOGE("Failed to reopen hardware output stream, "
2652 "samplingRate: %d, format %d, channels %d",
2653 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002654 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002655 outputDesc->mSamplingRate = config.sample_rate;
2656 outputDesc->mChannelMask = config.channel_mask;
2657 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002658 AudioParameter outputCmd = AudioParameter();
2659 outputCmd.addInt(String8("set_id"), 0);
2660 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2661 addOutput(mPrimaryOutput, outputDesc);
2662 }
2663 }
2664
2665
2666 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2667 }
2668 }
2669 return false;
2670}
2671
Eric Laurente0720872014-03-11 09:30:41 -07002672void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002673{
2674 {
2675 AutoMutex _l(mLock);
2676 requestExit();
2677 mWaitWorkCV.signal();
2678 }
2679 requestExitAndWait();
2680}
2681
Eric Laurente0720872014-03-11 09:30:41 -07002682int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002683{
2684 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2685 if (output == mTestOutputs[i]) return i;
2686 }
2687 return 0;
2688}
2689#endif //AUDIO_POLICY_TEST
2690
2691// ---
2692
Eric Laurent1f2f2232014-06-02 12:01:23 -07002693void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002694{
Eric Laurent1c333e22014-05-20 10:48:17 -07002695 outputDesc->mIoHandle = output;
2696 outputDesc->mId = nextUniqueId();
2697 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002698 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002699}
2700
Eric Laurent1f2f2232014-06-02 12:01:23 -07002701void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002702{
Eric Laurent1c333e22014-05-20 10:48:17 -07002703 inputDesc->mIoHandle = input;
2704 inputDesc->mId = nextUniqueId();
2705 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002706 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002707}
Eric Laurente552edb2014-03-10 17:42:56 -07002708
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002709void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2710 const String8 address /*in*/,
2711 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2712 // look for a match on the given address on the addresses of the outputs:
2713 // find the address by finding the patch that maps to this output
2714 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2715 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2716 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2717 if (patchIdx >= 0) {
2718 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2719 const int numSinks = patchDesc->mPatch.num_sinks;
2720 for (ssize_t j=0; j < numSinks; j++) {
2721 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2722 const char* patchAddr =
2723 patchDesc->mPatch.sinks[j].ext.device.address;
2724 if (strncmp(patchAddr,
2725 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2726 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2727 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2728 outputs.add(desc->mIoHandle);
2729 break;
2730 }
2731 }
2732 }
2733 }
2734}
2735
Eric Laurente0720872014-03-11 09:30:41 -07002736status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002737 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002738 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002739 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002740{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002741 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002742
Eric Laurent3b73df72014-03-11 09:06:29 -07002743 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002744 // first list already open outputs that can be routed to this device
2745 for (size_t i = 0; i < mOutputs.size(); i++) {
2746 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002747 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002748 if (!deviceDistinguishesOnAddress(device)) {
2749 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2750 outputs.add(mOutputs.keyAt(i));
2751 } else {
2752 ALOGV(" checking address match due to device 0x%x", device);
2753 findIoHandlesByAddress(desc, address, outputs);
2754 }
Eric Laurente552edb2014-03-10 17:42:56 -07002755 }
2756 }
2757 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002758 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002759 for (size_t i = 0; i < mHwModules.size(); i++)
2760 {
2761 if (mHwModules[i]->mHandle == 0) {
2762 continue;
2763 }
2764 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2765 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002766 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002767 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002768 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2769 }
2770 }
2771 }
2772
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002773 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
2774
Eric Laurente552edb2014-03-10 17:42:56 -07002775 if (profiles.isEmpty() && outputs.isEmpty()) {
2776 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2777 return BAD_VALUE;
2778 }
2779
2780 // open outputs for matching profiles if needed. Direct outputs are also opened to
2781 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2782 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002783 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002784
2785 // nothing to do if one output is already opened for this profile
2786 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002787 for (j = 0; j < outputs.size(); j++) {
2788 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07002789 if (!desc->isDuplicated() && desc->mProfile == profile) {
2790 break;
2791 }
2792 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002793 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002794 continue;
2795 }
2796
Eric Laurent83b88082014-06-20 18:31:16 -07002797 ALOGV("opening output for device %08x with params %s profile %p",
2798 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07002799 desc = new AudioOutputDescriptor(profile);
2800 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002801 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2802 config.sample_rate = desc->mSamplingRate;
2803 config.channel_mask = desc->mChannelMask;
2804 config.format = desc->mFormat;
2805 config.offload_info.sample_rate = desc->mSamplingRate;
2806 config.offload_info.channel_mask = desc->mChannelMask;
2807 config.offload_info.format = desc->mFormat;
2808 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2809 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
2810 &output,
2811 &config,
2812 &desc->mDevice,
2813 address,
2814 &desc->mLatency,
2815 desc->mFlags);
2816 if (status == NO_ERROR) {
2817 desc->mSamplingRate = config.sample_rate;
2818 desc->mChannelMask = config.channel_mask;
2819 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002820
Eric Laurentd4692962014-05-05 18:13:44 -07002821 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002822 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002823 char *param = audio_device_address_to_parameter(device, address);
2824 mpClientInterface->setParameters(output, String8(param));
2825 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07002826 }
2827
Eric Laurentd4692962014-05-05 18:13:44 -07002828 // Here is where we step through and resolve any "dynamic" fields
2829 String8 reply;
2830 char *value;
2831 if (profile->mSamplingRates[0] == 0) {
2832 reply = mpClientInterface->getParameters(output,
2833 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002834 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002835 reply.string());
2836 value = strpbrk((char *)reply.string(), "=");
2837 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002838 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002839 }
Eric Laurentd4692962014-05-05 18:13:44 -07002840 }
2841 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2842 reply = mpClientInterface->getParameters(output,
2843 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002844 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002845 reply.string());
2846 value = strpbrk((char *)reply.string(), "=");
2847 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002848 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002849 }
Eric Laurentd4692962014-05-05 18:13:44 -07002850 }
2851 if (profile->mChannelMasks[0] == 0) {
2852 reply = mpClientInterface->getParameters(output,
2853 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002854 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002855 reply.string());
2856 value = strpbrk((char *)reply.string(), "=");
2857 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002858 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002859 }
Eric Laurentd4692962014-05-05 18:13:44 -07002860 }
2861 if (((profile->mSamplingRates[0] == 0) &&
2862 (profile->mSamplingRates.size() < 2)) ||
2863 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2864 (profile->mFormats.size() < 2)) ||
2865 ((profile->mChannelMasks[0] == 0) &&
2866 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002867 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07002868 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002869 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07002870 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
2871 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002872 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002873 config.sample_rate = profile->pickSamplingRate();
2874 config.channel_mask = profile->pickChannelMask();
2875 config.format = profile->pickFormat();
2876 config.offload_info.sample_rate = config.sample_rate;
2877 config.offload_info.channel_mask = config.channel_mask;
2878 config.offload_info.format = config.format;
2879 status = mpClientInterface->openOutput(profile->mModule->mHandle,
2880 &output,
2881 &config,
2882 &desc->mDevice,
2883 address,
2884 &desc->mLatency,
2885 desc->mFlags);
2886 if (status == NO_ERROR) {
2887 desc->mSamplingRate = config.sample_rate;
2888 desc->mChannelMask = config.channel_mask;
2889 desc->mFormat = config.format;
2890 } else {
2891 output = AUDIO_IO_HANDLE_NONE;
2892 }
Eric Laurentd4692962014-05-05 18:13:44 -07002893 }
2894
Eric Laurentcf2c0212014-07-25 16:20:43 -07002895 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002896 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002897 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002898 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002899
Eric Laurentd4692962014-05-05 18:13:44 -07002900 // set initial stream volume for device
2901 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002902
Eric Laurentd4692962014-05-05 18:13:44 -07002903 //TODO: configure audio effect output stage here
2904
2905 // open a duplicating output thread for the new output and the primary output
2906 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2907 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002908 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07002909 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07002910 sp<AudioOutputDescriptor> dupOutputDesc =
2911 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002912 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2913 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2914 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2915 dupOutputDesc->mFormat = desc->mFormat;
2916 dupOutputDesc->mChannelMask = desc->mChannelMask;
2917 dupOutputDesc->mLatency = desc->mLatency;
2918 addOutput(duplicatedOutput, dupOutputDesc);
2919 applyStreamVolumes(duplicatedOutput, device, 0, true);
2920 } else {
2921 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2922 mPrimaryOutput, output);
2923 mpClientInterface->closeOutput(output);
2924 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002925 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002926 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07002927 }
Eric Laurente552edb2014-03-10 17:42:56 -07002928 }
2929 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002930 } else {
2931 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002932 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002933 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002934 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002935 profiles.removeAt(profile_index);
2936 profile_index--;
2937 } else {
2938 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002939 if (deviceDistinguishesOnAddress(device)) {
2940 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
2941 device, address.string());
2942 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
2943 NULL/*patch handle*/, address.string());
2944 }
Eric Laurente552edb2014-03-10 17:42:56 -07002945 ALOGV("checkOutputsForDevice(): adding output %d", output);
2946 }
2947 }
2948
2949 if (profiles.isEmpty()) {
2950 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2951 return BAD_VALUE;
2952 }
Eric Laurentd4692962014-05-05 18:13:44 -07002953 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002954 // check if one opened output is not needed any more after disconnecting one device
2955 for (size_t i = 0; i < mOutputs.size(); i++) {
2956 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002957 if (!desc->isDuplicated()) {
2958 if (!(desc->mProfile->mSupportedDevices.types()
2959 & mAvailableOutputDevices.types())) {
2960 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
2961 mOutputs.keyAt(i));
2962 outputs.add(mOutputs.keyAt(i));
2963 } else if (deviceDistinguishesOnAddress(device) &&
2964 // exact match on device
2965 (desc->mProfile->mSupportedDevices.types() == device)) {
2966 findIoHandlesByAddress(desc, address, outputs);
2967 }
Eric Laurente552edb2014-03-10 17:42:56 -07002968 }
2969 }
Eric Laurentd4692962014-05-05 18:13:44 -07002970 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002971 for (size_t i = 0; i < mHwModules.size(); i++)
2972 {
2973 if (mHwModules[i]->mHandle == 0) {
2974 continue;
2975 }
2976 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2977 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002978 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002979 if (profile->mSupportedDevices.types() & device) {
2980 ALOGV("checkOutputsForDevice(): "
2981 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002982 if (profile->mSamplingRates[0] == 0) {
2983 profile->mSamplingRates.clear();
2984 profile->mSamplingRates.add(0);
2985 }
2986 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2987 profile->mFormats.clear();
2988 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2989 }
2990 if (profile->mChannelMasks[0] == 0) {
2991 profile->mChannelMasks.clear();
2992 profile->mChannelMasks.add(0);
2993 }
2994 }
2995 }
2996 }
2997 }
2998 return NO_ERROR;
2999}
3000
Eric Laurentd4692962014-05-05 18:13:44 -07003001status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3002 audio_policy_dev_state_t state,
3003 SortedVector<audio_io_handle_t>& inputs,
3004 const String8 address)
3005{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003006 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003007 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3008 // first list already open inputs that can be routed to this device
3009 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3010 desc = mInputs.valueAt(input_index);
3011 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3012 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3013 inputs.add(mInputs.keyAt(input_index));
3014 }
3015 }
3016
3017 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003018 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003019 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3020 {
3021 if (mHwModules[module_idx]->mHandle == 0) {
3022 continue;
3023 }
3024 for (size_t profile_index = 0;
3025 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3026 profile_index++)
3027 {
3028 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3029 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003030 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003031 profile_index, module_idx);
3032 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3033 }
3034 }
3035 }
3036
3037 if (profiles.isEmpty() && inputs.isEmpty()) {
3038 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3039 return BAD_VALUE;
3040 }
3041
3042 // open inputs for matching profiles if needed. Direct inputs are also opened to
3043 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3044 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3045
Eric Laurent1c333e22014-05-20 10:48:17 -07003046 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003047 // nothing to do if one input is already opened for this profile
3048 size_t input_index;
3049 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3050 desc = mInputs.valueAt(input_index);
3051 if (desc->mProfile == profile) {
3052 break;
3053 }
3054 }
3055 if (input_index != mInputs.size()) {
3056 continue;
3057 }
3058
3059 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3060 desc = new AudioInputDescriptor(profile);
3061 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003062 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3063 config.sample_rate = desc->mSamplingRate;
3064 config.channel_mask = desc->mChannelMask;
3065 config.format = desc->mFormat;
3066 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3067 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3068 &input,
3069 &config,
3070 &desc->mDevice,
3071 address,
3072 AUDIO_SOURCE_MIC,
3073 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003074
Eric Laurentcf2c0212014-07-25 16:20:43 -07003075 if (status == NO_ERROR) {
3076 desc->mSamplingRate = config.sample_rate;
3077 desc->mChannelMask = config.channel_mask;
3078 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003079
Eric Laurentd4692962014-05-05 18:13:44 -07003080 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003081 char *param = audio_device_address_to_parameter(device, address);
3082 mpClientInterface->setParameters(input, String8(param));
3083 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003084 }
3085
3086 // Here is where we step through and resolve any "dynamic" fields
3087 String8 reply;
3088 char *value;
3089 if (profile->mSamplingRates[0] == 0) {
3090 reply = mpClientInterface->getParameters(input,
3091 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3092 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3093 reply.string());
3094 value = strpbrk((char *)reply.string(), "=");
3095 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003096 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003097 }
3098 }
3099 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3100 reply = mpClientInterface->getParameters(input,
3101 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3102 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3103 value = strpbrk((char *)reply.string(), "=");
3104 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003105 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003106 }
3107 }
3108 if (profile->mChannelMasks[0] == 0) {
3109 reply = mpClientInterface->getParameters(input,
3110 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3111 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3112 reply.string());
3113 value = strpbrk((char *)reply.string(), "=");
3114 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003115 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003116 }
3117 }
3118 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3119 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3120 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3121 ALOGW("checkInputsForDevice() direct input missing param");
3122 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003123 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003124 }
3125
3126 if (input != 0) {
3127 addInput(input, desc);
3128 }
3129 } // endif input != 0
3130
Eric Laurentcf2c0212014-07-25 16:20:43 -07003131 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003132 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003133 profiles.removeAt(profile_index);
3134 profile_index--;
3135 } else {
3136 inputs.add(input);
3137 ALOGV("checkInputsForDevice(): adding input %d", input);
3138 }
3139 } // end scan profiles
3140
3141 if (profiles.isEmpty()) {
3142 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3143 return BAD_VALUE;
3144 }
3145 } else {
3146 // Disconnect
3147 // check if one opened input is not needed any more after disconnecting one device
3148 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3149 desc = mInputs.valueAt(input_index);
3150 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3151 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3152 mInputs.keyAt(input_index));
3153 inputs.add(mInputs.keyAt(input_index));
3154 }
3155 }
3156 // Clear any profiles associated with the disconnected device.
3157 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3158 if (mHwModules[module_index]->mHandle == 0) {
3159 continue;
3160 }
3161 for (size_t profile_index = 0;
3162 profile_index < mHwModules[module_index]->mInputProfiles.size();
3163 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003164 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003165 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003166 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003167 profile_index, module_index);
3168 if (profile->mSamplingRates[0] == 0) {
3169 profile->mSamplingRates.clear();
3170 profile->mSamplingRates.add(0);
3171 }
3172 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3173 profile->mFormats.clear();
3174 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3175 }
3176 if (profile->mChannelMasks[0] == 0) {
3177 profile->mChannelMasks.clear();
3178 profile->mChannelMasks.add(0);
3179 }
3180 }
3181 }
3182 }
3183 } // end disconnect
3184
3185 return NO_ERROR;
3186}
3187
3188
Eric Laurente0720872014-03-11 09:30:41 -07003189void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003190{
3191 ALOGV("closeOutput(%d)", output);
3192
Eric Laurent1f2f2232014-06-02 12:01:23 -07003193 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003194 if (outputDesc == NULL) {
3195 ALOGW("closeOutput() unknown output %d", output);
3196 return;
3197 }
3198
3199 // look for duplicated outputs connected to the output being removed.
3200 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003201 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003202 if (dupOutputDesc->isDuplicated() &&
3203 (dupOutputDesc->mOutput1 == outputDesc ||
3204 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003205 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003206 if (dupOutputDesc->mOutput1 == outputDesc) {
3207 outputDesc2 = dupOutputDesc->mOutput2;
3208 } else {
3209 outputDesc2 = dupOutputDesc->mOutput1;
3210 }
3211 // As all active tracks on duplicated output will be deleted,
3212 // and as they were also referenced on the other output, the reference
3213 // count for their stream type must be adjusted accordingly on
3214 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003215 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003216 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003217 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003218 }
3219 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3220 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3221
3222 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003223 mOutputs.removeItem(duplicatedOutput);
3224 }
3225 }
3226
3227 AudioParameter param;
3228 param.add(String8("closing"), String8("true"));
3229 mpClientInterface->setParameters(output, param.toString());
3230
3231 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003232 mOutputs.removeItem(output);
3233 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003234 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003235}
3236
Eric Laurente0720872014-03-11 09:30:41 -07003237SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003238 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003239{
3240 SortedVector<audio_io_handle_t> outputs;
3241
3242 ALOGVV("getOutputsForDevice() device %04x", device);
3243 for (size_t i = 0; i < openOutputs.size(); i++) {
3244 ALOGVV("output %d isDuplicated=%d device=%04x",
3245 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3246 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3247 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3248 outputs.add(openOutputs.keyAt(i));
3249 }
3250 }
3251 return outputs;
3252}
3253
Eric Laurente0720872014-03-11 09:30:41 -07003254bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003255 SortedVector<audio_io_handle_t>& outputs2)
3256{
3257 if (outputs1.size() != outputs2.size()) {
3258 return false;
3259 }
3260 for (size_t i = 0; i < outputs1.size(); i++) {
3261 if (outputs1[i] != outputs2[i]) {
3262 return false;
3263 }
3264 }
3265 return true;
3266}
3267
Eric Laurente0720872014-03-11 09:30:41 -07003268void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003269{
3270 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3271 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3272 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3273 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3274
3275 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3276 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3277 strategy, srcOutputs[0], dstOutputs[0]);
3278 // mute strategy while moving tracks from one output to another
3279 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003280 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003281 if (desc->isStrategyActive(strategy)) {
3282 setStrategyMute(strategy, true, srcOutputs[i]);
3283 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3284 }
3285 }
3286
3287 // Move effects associated to this strategy from previous output to new output
3288 if (strategy == STRATEGY_MEDIA) {
3289 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3290 SortedVector<audio_io_handle_t> moved;
3291 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003292 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3293 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3294 effectDesc->mIo != fxOutput) {
3295 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003296 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3297 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003298 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003299 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003300 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003301 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003302 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003303 }
3304 }
3305 }
3306 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003307 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3308 if (getStrategy((audio_stream_type_t)i) == strategy) {
3309 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003310 }
3311 }
3312 }
3313}
3314
Eric Laurente0720872014-03-11 09:30:41 -07003315void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003316{
3317 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3318 checkOutputForStrategy(STRATEGY_PHONE);
3319 checkOutputForStrategy(STRATEGY_SONIFICATION);
3320 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3321 checkOutputForStrategy(STRATEGY_MEDIA);
3322 checkOutputForStrategy(STRATEGY_DTMF);
3323}
3324
Eric Laurente0720872014-03-11 09:30:41 -07003325audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003326{
Eric Laurente552edb2014-03-10 17:42:56 -07003327 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003328 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003329 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3330 return mOutputs.keyAt(i);
3331 }
3332 }
3333
3334 return 0;
3335}
3336
Eric Laurente0720872014-03-11 09:30:41 -07003337void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003338{
Eric Laurente552edb2014-03-10 17:42:56 -07003339 audio_io_handle_t a2dpOutput = getA2dpOutput();
3340 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003341 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003342 return;
3343 }
3344
Eric Laurent3a4311c2014-03-17 12:00:47 -07003345 bool isScoConnected =
3346 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003347 // suspend A2DP output if:
3348 // (NOT already suspended) &&
3349 // ((SCO device is connected &&
3350 // (forced usage for communication || for record is SCO))) ||
3351 // (phone state is ringing || in call)
3352 //
3353 // restore A2DP output if:
3354 // (Already suspended) &&
3355 // ((SCO device is NOT connected ||
3356 // (forced usage NOT for communication && NOT for record is SCO))) &&
3357 // (phone state is NOT ringing && NOT in call)
3358 //
3359 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003360 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003361 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3362 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3363 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3364 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003365
3366 mpClientInterface->restoreOutput(a2dpOutput);
3367 mA2dpSuspended = false;
3368 }
3369 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003370 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003371 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3372 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3373 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3374 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003375
3376 mpClientInterface->suspendOutput(a2dpOutput);
3377 mA2dpSuspended = true;
3378 }
3379 }
3380}
3381
Eric Laurent1c333e22014-05-20 10:48:17 -07003382audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003383{
3384 audio_devices_t device = AUDIO_DEVICE_NONE;
3385
Eric Laurent1f2f2232014-06-02 12:01:23 -07003386 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003387
3388 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3389 if (index >= 0) {
3390 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3391 if (patchDesc->mUid != mUidCached) {
3392 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3393 outputDesc->device(), outputDesc->mPatchHandle);
3394 return outputDesc->device();
3395 }
3396 }
3397
Eric Laurente552edb2014-03-10 17:42:56 -07003398 // check the following by order of priority to request a routing change if necessary:
3399 // 1: the strategy enforced audible is active on the output:
3400 // use device for strategy enforced audible
3401 // 2: we are in call or the strategy phone is active on the output:
3402 // use device for strategy phone
3403 // 3: the strategy sonification is active on the output:
3404 // use device for strategy sonification
3405 // 4: the strategy "respectful" sonification is active on the output:
3406 // use device for strategy "respectful" sonification
3407 // 5: the strategy media is active on the output:
3408 // use device for strategy media
3409 // 6: the strategy DTMF is active on the output:
3410 // use device for strategy DTMF
3411 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3412 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3413 } else if (isInCall() ||
3414 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3415 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3416 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3417 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3418 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3419 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3420 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3421 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3422 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3423 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3424 }
3425
Eric Laurent1c333e22014-05-20 10:48:17 -07003426 ALOGV("getNewOutputDevice() selected device %x", device);
3427 return device;
3428}
3429
3430audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3431{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003432 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003433
3434 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3435 if (index >= 0) {
3436 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3437 if (patchDesc->mUid != mUidCached) {
3438 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3439 inputDesc->mDevice, inputDesc->mPatchHandle);
3440 return inputDesc->mDevice;
3441 }
3442 }
3443
Eric Laurent1c333e22014-05-20 10:48:17 -07003444 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3445
3446 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003447 return device;
3448}
3449
Eric Laurente0720872014-03-11 09:30:41 -07003450uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003451 return (uint32_t)getStrategy(stream);
3452}
3453
Eric Laurente0720872014-03-11 09:30:41 -07003454audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003455 // By checking the range of stream before calling getStrategy, we avoid
3456 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3457 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003458 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003459 return AUDIO_DEVICE_NONE;
3460 }
3461 audio_devices_t devices;
3462 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3463 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3464 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3465 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003466 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003467 if (outputDesc->isStrategyActive(strategy)) {
3468 devices = outputDesc->device();
3469 break;
3470 }
Eric Laurente552edb2014-03-10 17:42:56 -07003471 }
3472 return devices;
3473}
3474
Eric Laurente0720872014-03-11 09:30:41 -07003475AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003476 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003477 // stream to strategy mapping
3478 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003479 case AUDIO_STREAM_VOICE_CALL:
3480 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003481 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003482 case AUDIO_STREAM_RING:
3483 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003484 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003485 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003486 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003487 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003488 return STRATEGY_DTMF;
3489 default:
3490 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003491 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003492 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3493 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003494 case AUDIO_STREAM_TTS:
3495 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003496 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003497 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003498 return STRATEGY_ENFORCED_AUDIBLE;
3499 }
3500}
3501
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003502uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3503 // flags to strategy mapping
3504 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3505 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3506 }
3507
3508 // usage to strategy mapping
3509 switch (attr->usage) {
3510 case AUDIO_USAGE_MEDIA:
3511 case AUDIO_USAGE_GAME:
3512 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3513 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3514 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3515 return (uint32_t) STRATEGY_MEDIA;
3516
3517 case AUDIO_USAGE_VOICE_COMMUNICATION:
3518 return (uint32_t) STRATEGY_PHONE;
3519
3520 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3521 return (uint32_t) STRATEGY_DTMF;
3522
3523 case AUDIO_USAGE_ALARM:
3524 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3525 return (uint32_t) STRATEGY_SONIFICATION;
3526
3527 case AUDIO_USAGE_NOTIFICATION:
3528 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3529 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3530 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3531 case AUDIO_USAGE_NOTIFICATION_EVENT:
3532 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3533
3534 case AUDIO_USAGE_UNKNOWN:
3535 default:
3536 return (uint32_t) STRATEGY_MEDIA;
3537 }
3538}
3539
Eric Laurente0720872014-03-11 09:30:41 -07003540void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003541 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003542 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003543 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3544 updateDevicesAndOutputs();
3545 break;
3546 default:
3547 break;
3548 }
3549}
3550
Eric Laurente0720872014-03-11 09:30:41 -07003551audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003552 bool fromCache)
3553{
3554 uint32_t device = AUDIO_DEVICE_NONE;
3555
3556 if (fromCache) {
3557 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3558 strategy, mDeviceForStrategy[strategy]);
3559 return mDeviceForStrategy[strategy];
3560 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003561 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003562 switch (strategy) {
3563
3564 case STRATEGY_SONIFICATION_RESPECTFUL:
3565 if (isInCall()) {
3566 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003567 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003568 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3569 // while media is playing on a remote device, use the the sonification behavior.
3570 // Note that we test this usecase before testing if media is playing because
3571 // the isStreamActive() method only informs about the activity of a stream, not
3572 // if it's for local playback. Note also that we use the same delay between both tests
3573 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003574 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003575 // while media is playing (or has recently played), use the same device
3576 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3577 } else {
3578 // when media is not playing anymore, fall back on the sonification behavior
3579 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3580 }
3581
3582 break;
3583
3584 case STRATEGY_DTMF:
3585 if (!isInCall()) {
3586 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3587 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3588 break;
3589 }
3590 // when in call, DTMF and PHONE strategies follow the same rules
3591 // FALL THROUGH
3592
3593 case STRATEGY_PHONE:
3594 // for phone strategy, we first consider the forced use and then the available devices by order
3595 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003596 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3597 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003598 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003599 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003600 if (device) break;
3601 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003602 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003603 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003604 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003605 if (device) break;
3606 // if SCO device is requested but no SCO device is available, fall back to default case
3607 // FALL THROUGH
3608
3609 default: // FORCE_NONE
3610 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003611 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003612 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003613 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003614 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003615 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003616 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003617 if (device) break;
3618 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003619 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003620 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003621 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003622 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003623 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003624 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003625 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003626 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003627 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003628 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003629 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003630 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003631 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003632 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003633 if (device) break;
3634 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003635 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003636 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003637 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003638 if (device == AUDIO_DEVICE_NONE) {
3639 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3640 }
3641 break;
3642
Eric Laurent3b73df72014-03-11 09:06:29 -07003643 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003644 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3645 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003646 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003647 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003648 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003649 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003650 if (device) break;
3651 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003652 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003653 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003654 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003655 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003656 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003657 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003658 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003659 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003660 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003661 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003662 if (device) break;
3663 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003664 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003665 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003666 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003667 if (device == AUDIO_DEVICE_NONE) {
3668 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3669 }
3670 break;
3671 }
3672 break;
3673
3674 case STRATEGY_SONIFICATION:
3675
3676 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3677 // handleIncallSonification().
3678 if (isInCall()) {
3679 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3680 break;
3681 }
3682 // FALL THROUGH
3683
3684 case STRATEGY_ENFORCED_AUDIBLE:
3685 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3686 // except:
3687 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3688 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3689
3690 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003691 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003692 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003693 if (device == AUDIO_DEVICE_NONE) {
3694 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3695 }
3696 }
3697 // The second device used for sonification is the same as the device used by media strategy
3698 // FALL THROUGH
3699
3700 case STRATEGY_MEDIA: {
3701 uint32_t device2 = AUDIO_DEVICE_NONE;
3702 if (strategy != STRATEGY_SONIFICATION) {
3703 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003704 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003705 }
3706 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003707 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003708 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003709 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003710 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003711 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003712 }
3713 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003714 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003715 }
3716 }
3717 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003718 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003719 }
3720 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003721 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003722 }
3723 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003724 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003725 }
3726 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003727 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003728 }
3729 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003730 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003731 }
3732 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3733 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003734 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003735 }
3736 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003737 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003738 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003739 }
3740 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003741 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003742 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003743 int device3 = AUDIO_DEVICE_NONE;
3744 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003745 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09003746 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3747 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003748 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003749 }
Eric Laurente552edb2014-03-10 17:42:56 -07003750
Jungshik Jang839e4f32014-06-26 17:23:40 +09003751 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003752 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3753 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3754 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003755
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003756 // If hdmi system audio mode is on, remove speaker out of output list.
3757 if ((strategy == STRATEGY_MEDIA) &&
3758 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3759 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3760 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3761 }
3762
Eric Laurente552edb2014-03-10 17:42:56 -07003763 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003764 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003765 if (device == AUDIO_DEVICE_NONE) {
3766 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3767 }
3768 } break;
3769
3770 default:
3771 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3772 break;
3773 }
3774
3775 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3776 return device;
3777}
3778
Eric Laurente0720872014-03-11 09:30:41 -07003779void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003780{
3781 for (int i = 0; i < NUM_STRATEGIES; i++) {
3782 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3783 }
3784 mPreviousOutputs = mOutputs;
3785}
3786
Eric Laurent1f2f2232014-06-02 12:01:23 -07003787uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003788 audio_devices_t prevDevice,
3789 uint32_t delayMs)
3790{
3791 // mute/unmute strategies using an incompatible device combination
3792 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3793 // if unmuting, unmute only after the specified delay
3794 if (outputDesc->isDuplicated()) {
3795 return 0;
3796 }
3797
3798 uint32_t muteWaitMs = 0;
3799 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003800 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003801
3802 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3803 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3804 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3805 bool doMute = false;
3806
3807 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3808 doMute = true;
3809 outputDesc->mStrategyMutedByDevice[i] = true;
3810 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3811 doMute = true;
3812 outputDesc->mStrategyMutedByDevice[i] = false;
3813 }
Eric Laurent99401132014-05-07 19:48:15 -07003814 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003815 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003816 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003817 // skip output if it does not share any device with current output
3818 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3819 == AUDIO_DEVICE_NONE) {
3820 continue;
3821 }
3822 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3823 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3824 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3825 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3826 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003827 if (mute) {
3828 // FIXME: should not need to double latency if volume could be applied
3829 // immediately by the audioflinger mixer. We must account for the delay
3830 // between now and the next time the audioflinger thread for this output
3831 // will process a buffer (which corresponds to one buffer size,
3832 // usually 1/2 or 1/4 of the latency).
3833 if (muteWaitMs < desc->latency() * 2) {
3834 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003835 }
3836 }
3837 }
3838 }
3839 }
3840 }
3841
Eric Laurent99401132014-05-07 19:48:15 -07003842 // temporary mute output if device selection changes to avoid volume bursts due to
3843 // different per device volumes
3844 if (outputDesc->isActive() && (device != prevDevice)) {
3845 if (muteWaitMs < outputDesc->latency() * 2) {
3846 muteWaitMs = outputDesc->latency() * 2;
3847 }
3848 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3849 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003850 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003851 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003852 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003853 muteWaitMs *2, device);
3854 }
3855 }
3856 }
3857
Eric Laurente552edb2014-03-10 17:42:56 -07003858 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3859 if (muteWaitMs > delayMs) {
3860 muteWaitMs -= delayMs;
3861 usleep(muteWaitMs * 1000);
3862 return muteWaitMs;
3863 }
3864 return 0;
3865}
3866
Eric Laurente0720872014-03-11 09:30:41 -07003867uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003868 audio_devices_t device,
3869 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003870 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003871 audio_patch_handle_t *patchHandle,
3872 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07003873{
3874 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003875 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003876 AudioParameter param;
3877 uint32_t muteWaitMs;
3878
3879 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003880 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3881 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003882 return muteWaitMs;
3883 }
3884 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3885 // output profile
3886 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003887 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003888 return 0;
3889 }
3890
3891 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003892 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003893
3894 audio_devices_t prevDevice = outputDesc->mDevice;
3895
3896 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3897
3898 if (device != AUDIO_DEVICE_NONE) {
3899 outputDesc->mDevice = device;
3900 }
3901 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3902
3903 // Do not change the routing if:
3904 // - the requested device is AUDIO_DEVICE_NONE
3905 // - the requested device is the same as current device and force is not specified.
3906 // Doing this check here allows the caller to call setOutputDevice() without conditions
3907 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3908 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3909 return muteWaitMs;
3910 }
3911
3912 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003913
Eric Laurente552edb2014-03-10 17:42:56 -07003914 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003915 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003916 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003917 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003918 DeviceVector deviceList = (address == NULL) ?
3919 mAvailableOutputDevices.getDevicesFromType(device)
3920 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07003921 if (!deviceList.isEmpty()) {
3922 struct audio_patch patch;
3923 outputDesc->toAudioPortConfig(&patch.sources[0]);
3924 patch.num_sources = 1;
3925 patch.num_sinks = 0;
3926 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3927 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003928 patch.num_sinks++;
3929 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003930 ssize_t index;
3931 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3932 index = mAudioPatches.indexOfKey(*patchHandle);
3933 } else {
3934 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3935 }
3936 sp< AudioPatch> patchDesc;
3937 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3938 if (index >= 0) {
3939 patchDesc = mAudioPatches.valueAt(index);
3940 afPatchHandle = patchDesc->mAfPatchHandle;
3941 }
3942
Eric Laurent1c333e22014-05-20 10:48:17 -07003943 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003944 &afPatchHandle,
3945 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003946 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3947 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003948 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003949 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003950 if (index < 0) {
3951 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3952 &patch, mUidCached);
3953 addAudioPatch(patchDesc->mHandle, patchDesc);
3954 } else {
3955 patchDesc->mPatch = patch;
3956 }
3957 patchDesc->mAfPatchHandle = afPatchHandle;
3958 patchDesc->mUid = mUidCached;
3959 if (patchHandle) {
3960 *patchHandle = patchDesc->mHandle;
3961 }
3962 outputDesc->mPatchHandle = patchDesc->mHandle;
3963 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003964 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003965 }
3966 }
3967 }
Eric Laurente552edb2014-03-10 17:42:56 -07003968
3969 // update stream volumes according to new device
3970 applyStreamVolumes(output, device, delayMs);
3971
3972 return muteWaitMs;
3973}
3974
Eric Laurent1c333e22014-05-20 10:48:17 -07003975status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003976 int delayMs,
3977 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003978{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003979 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003980 ssize_t index;
3981 if (patchHandle) {
3982 index = mAudioPatches.indexOfKey(*patchHandle);
3983 } else {
3984 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3985 }
3986 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003987 return INVALID_OPERATION;
3988 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003989 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3990 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003991 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3992 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003993 removeAudioPatch(patchDesc->mHandle);
3994 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003995 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003996 return status;
3997}
3998
3999status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4000 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004001 bool force,
4002 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004003{
4004 status_t status = NO_ERROR;
4005
Eric Laurent1f2f2232014-06-02 12:01:23 -07004006 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004007 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4008 inputDesc->mDevice = device;
4009
4010 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4011 if (!deviceList.isEmpty()) {
4012 struct audio_patch patch;
4013 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004014 // AUDIO_SOURCE_HOTWORD is for internal use only:
4015 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
4016 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD) {
4017 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4018 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004019 patch.num_sinks = 1;
4020 //only one input device for now
4021 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004022 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004023 ssize_t index;
4024 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4025 index = mAudioPatches.indexOfKey(*patchHandle);
4026 } else {
4027 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4028 }
4029 sp< AudioPatch> patchDesc;
4030 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4031 if (index >= 0) {
4032 patchDesc = mAudioPatches.valueAt(index);
4033 afPatchHandle = patchDesc->mAfPatchHandle;
4034 }
4035
Eric Laurent1c333e22014-05-20 10:48:17 -07004036 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004037 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004038 0);
4039 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004040 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004041 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004042 if (index < 0) {
4043 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4044 &patch, mUidCached);
4045 addAudioPatch(patchDesc->mHandle, patchDesc);
4046 } else {
4047 patchDesc->mPatch = patch;
4048 }
4049 patchDesc->mAfPatchHandle = afPatchHandle;
4050 patchDesc->mUid = mUidCached;
4051 if (patchHandle) {
4052 *patchHandle = patchDesc->mHandle;
4053 }
4054 inputDesc->mPatchHandle = patchDesc->mHandle;
4055 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004056 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004057 }
4058 }
4059 }
4060 return status;
4061}
4062
Eric Laurent6a94d692014-05-20 11:18:06 -07004063status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4064 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004065{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004066 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004067 ssize_t index;
4068 if (patchHandle) {
4069 index = mAudioPatches.indexOfKey(*patchHandle);
4070 } else {
4071 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4072 }
4073 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004074 return INVALID_OPERATION;
4075 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004076 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4077 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004078 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4079 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004080 removeAudioPatch(patchDesc->mHandle);
4081 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004082 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004083 return status;
4084}
4085
4086sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004087 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004088 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004089 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004090 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004091{
4092 // Choose an input profile based on the requested capture parameters: select the first available
4093 // profile supporting all requested parameters.
4094
4095 for (size_t i = 0; i < mHwModules.size(); i++)
4096 {
4097 if (mHwModules[i]->mHandle == 0) {
4098 continue;
4099 }
4100 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4101 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004102 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004103 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004104 if (profile->isCompatibleProfile(device, samplingRate,
4105 &samplingRate /*updatedSamplingRate*/,
4106 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004107 return profile;
4108 }
4109 }
4110 }
4111 return NULL;
4112}
4113
Eric Laurente0720872014-03-11 09:30:41 -07004114audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004115{
4116 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004117 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4118 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004119 switch (inputSource) {
4120 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004121 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004122 device = AUDIO_DEVICE_IN_VOICE_CALL;
4123 break;
4124 }
4125 // FALL THROUGH
4126
4127 case AUDIO_SOURCE_DEFAULT:
4128 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004129 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4130 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
4131 break;
4132 }
4133 // FALL THROUGH
4134
Eric Laurente552edb2014-03-10 17:42:56 -07004135 case AUDIO_SOURCE_VOICE_RECOGNITION:
4136 case AUDIO_SOURCE_HOTWORD:
4137 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07004138 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004139 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004140 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004141 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004142 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004143 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4144 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004145 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004146 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4147 }
4148 break;
4149 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004150 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004151 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004152 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004153 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4154 }
4155 break;
4156 case AUDIO_SOURCE_VOICE_DOWNLINK:
4157 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004158 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004159 device = AUDIO_DEVICE_IN_VOICE_CALL;
4160 }
4161 break;
4162 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004163 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004164 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4165 }
4166 break;
4167 default:
4168 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4169 break;
4170 }
4171 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4172 return device;
4173}
4174
Eric Laurente0720872014-03-11 09:30:41 -07004175bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004176{
4177 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4178 device &= ~AUDIO_DEVICE_BIT_IN;
4179 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4180 return true;
4181 }
4182 return false;
4183}
4184
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004185bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4186 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4187}
4188
Eric Laurente0720872014-03-11 09:30:41 -07004189audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004190{
4191 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004192 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004193 if ((input_descriptor->mRefCount > 0)
4194 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4195 return mInputs.keyAt(i);
4196 }
4197 }
4198 return 0;
4199}
4200
4201
Eric Laurente0720872014-03-11 09:30:41 -07004202audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004203{
4204 if (device == AUDIO_DEVICE_NONE) {
4205 // this happens when forcing a route update and no track is active on an output.
4206 // In this case the returned category is not important.
4207 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004208 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004209 // Multiple device selection is either:
4210 // - speaker + one other device: give priority to speaker in this case.
4211 // - one A2DP device + another device: happens with duplicated output. In this case
4212 // retain the device on the A2DP output as the other must not correspond to an active
4213 // selection if not the speaker.
4214 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4215 device = AUDIO_DEVICE_OUT_SPEAKER;
4216 } else {
4217 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4218 }
4219 }
4220
Eric Laurent3b73df72014-03-11 09:06:29 -07004221 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004222 "getDeviceForVolume() invalid device combination: %08x",
4223 device);
4224
4225 return device;
4226}
4227
Eric Laurente0720872014-03-11 09:30:41 -07004228AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004229{
4230 switch(getDeviceForVolume(device)) {
4231 case AUDIO_DEVICE_OUT_EARPIECE:
4232 return DEVICE_CATEGORY_EARPIECE;
4233 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4234 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4235 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4236 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4237 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4238 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4239 return DEVICE_CATEGORY_HEADSET;
4240 case AUDIO_DEVICE_OUT_SPEAKER:
4241 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4242 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4243 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4244 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4245 case AUDIO_DEVICE_OUT_USB_DEVICE:
4246 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4247 default:
4248 return DEVICE_CATEGORY_SPEAKER;
4249 }
4250}
4251
Eric Laurente0720872014-03-11 09:30:41 -07004252float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004253 int indexInUi)
4254{
4255 device_category deviceCategory = getDeviceCategory(device);
4256 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4257
4258 // the volume index in the UI is relative to the min and max volume indices for this stream type
4259 int nbSteps = 1 + curve[VOLMAX].mIndex -
4260 curve[VOLMIN].mIndex;
4261 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4262 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4263
4264 // find what part of the curve this index volume belongs to, or if it's out of bounds
4265 int segment = 0;
4266 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4267 return 0.0f;
4268 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4269 segment = 0;
4270 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4271 segment = 1;
4272 } else if (volIdx <= curve[VOLMAX].mIndex) {
4273 segment = 2;
4274 } else { // out of bounds
4275 return 1.0f;
4276 }
4277
4278 // linear interpolation in the attenuation table in dB
4279 float decibels = curve[segment].mDBAttenuation +
4280 ((float)(volIdx - curve[segment].mIndex)) *
4281 ( (curve[segment+1].mDBAttenuation -
4282 curve[segment].mDBAttenuation) /
4283 ((float)(curve[segment+1].mIndex -
4284 curve[segment].mIndex)) );
4285
4286 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4287
4288 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4289 curve[segment].mIndex, volIdx,
4290 curve[segment+1].mIndex,
4291 curve[segment].mDBAttenuation,
4292 decibels,
4293 curve[segment+1].mDBAttenuation,
4294 amplification);
4295
4296 return amplification;
4297}
4298
Eric Laurente0720872014-03-11 09:30:41 -07004299const AudioPolicyManager::VolumeCurvePoint
4300 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004301 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4302};
4303
Eric Laurente0720872014-03-11 09:30:41 -07004304const AudioPolicyManager::VolumeCurvePoint
4305 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004306 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4307};
4308
Eric Laurente0720872014-03-11 09:30:41 -07004309const AudioPolicyManager::VolumeCurvePoint
4310 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004311 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4312};
4313
Eric Laurente0720872014-03-11 09:30:41 -07004314const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004315 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004316 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004317};
4318
4319const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004320 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004321 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4322};
4323
Eric Laurente0720872014-03-11 09:30:41 -07004324const AudioPolicyManager::VolumeCurvePoint
4325 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004326 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4327};
4328
4329// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4330// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4331// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4332// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4333
Eric Laurente0720872014-03-11 09:30:41 -07004334const AudioPolicyManager::VolumeCurvePoint
4335 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004336 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4337};
4338
Eric Laurente0720872014-03-11 09:30:41 -07004339const AudioPolicyManager::VolumeCurvePoint
4340 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004341 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4342};
4343
Eric Laurente0720872014-03-11 09:30:41 -07004344const AudioPolicyManager::VolumeCurvePoint
4345 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004346 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4347};
4348
Eric Laurente0720872014-03-11 09:30:41 -07004349const AudioPolicyManager::VolumeCurvePoint
4350 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004351 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4352};
4353
Eric Laurente0720872014-03-11 09:30:41 -07004354const AudioPolicyManager::VolumeCurvePoint
4355 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004356 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4357};
4358
Eric Laurente0720872014-03-11 09:30:41 -07004359const AudioPolicyManager::VolumeCurvePoint
4360 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4361 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004362 { // AUDIO_STREAM_VOICE_CALL
4363 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4364 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4365 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4366 },
4367 { // AUDIO_STREAM_SYSTEM
4368 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4369 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4370 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4371 },
4372 { // AUDIO_STREAM_RING
4373 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4374 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4375 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4376 },
4377 { // AUDIO_STREAM_MUSIC
4378 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4379 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4380 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4381 },
4382 { // AUDIO_STREAM_ALARM
4383 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4384 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4385 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4386 },
4387 { // AUDIO_STREAM_NOTIFICATION
4388 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4389 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4390 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4391 },
4392 { // AUDIO_STREAM_BLUETOOTH_SCO
4393 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4394 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4395 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4396 },
4397 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4398 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4399 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4400 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4401 },
4402 { // AUDIO_STREAM_DTMF
4403 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4404 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4405 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4406 },
4407 { // AUDIO_STREAM_TTS
4408 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4409 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4410 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4411 },
4412};
4413
Eric Laurente0720872014-03-11 09:30:41 -07004414void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004415{
4416 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4417 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4418 mStreams[i].mVolumeCurve[j] =
4419 sVolumeProfiles[i][j];
4420 }
4421 }
4422
4423 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4424 if (mSpeakerDrcEnabled) {
4425 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4426 sDefaultSystemVolumeCurveDrc;
4427 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4428 sSpeakerSonificationVolumeCurveDrc;
4429 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4430 sSpeakerSonificationVolumeCurveDrc;
4431 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4432 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004433 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4434 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004435 }
4436}
4437
Eric Laurente0720872014-03-11 09:30:41 -07004438float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004439 int index,
4440 audio_io_handle_t output,
4441 audio_devices_t device)
4442{
4443 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004444 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004445 StreamDescriptor &streamDesc = mStreams[stream];
4446
4447 if (device == AUDIO_DEVICE_NONE) {
4448 device = outputDesc->device();
4449 }
4450
Eric Laurente552edb2014-03-10 17:42:56 -07004451 volume = volIndexToAmpl(device, streamDesc, index);
4452
4453 // if a headset is connected, apply the following rules to ring tones and notifications
4454 // to avoid sound level bursts in user's ears:
4455 // - always attenuate ring tones and notifications volume by 6dB
4456 // - if music is playing, always limit the volume to current music volume,
4457 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004458 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004459 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4460 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4461 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4462 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4463 ((stream_strategy == STRATEGY_SONIFICATION)
4464 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004465 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004466 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004467 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004468 streamDesc.mCanBeMuted) {
4469 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4470 // when the phone is ringing we must consider that music could have been paused just before
4471 // by the music application and behave as if music was active if the last music track was
4472 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004473 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004474 mLimitRingtoneVolume) {
4475 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004476 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4477 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004478 output,
4479 musicDevice);
4480 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4481 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4482 if (volume > minVol) {
4483 volume = minVol;
4484 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4485 }
4486 }
4487 }
4488
4489 return volume;
4490}
4491
Eric Laurente0720872014-03-11 09:30:41 -07004492status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004493 int index,
4494 audio_io_handle_t output,
4495 audio_devices_t device,
4496 int delayMs,
4497 bool force)
4498{
4499
4500 // do not change actual stream volume if the stream is muted
4501 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4502 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4503 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4504 return NO_ERROR;
4505 }
4506
4507 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004508 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4509 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4510 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4511 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004512 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004513 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004514 return INVALID_OPERATION;
4515 }
4516
4517 float volume = computeVolume(stream, index, output, device);
4518 // We actually change the volume if:
4519 // - the float value returned by computeVolume() changed
4520 // - the force flag is set
4521 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4522 force) {
4523 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4524 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4525 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4526 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004527 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4528 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004529 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004530 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004531 }
4532
Eric Laurent3b73df72014-03-11 09:06:29 -07004533 if (stream == AUDIO_STREAM_VOICE_CALL ||
4534 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004535 float voiceVolume;
4536 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004537 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004538 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4539 } else {
4540 voiceVolume = 1.0;
4541 }
4542
4543 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4544 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4545 mLastVoiceVolume = voiceVolume;
4546 }
4547 }
4548
4549 return NO_ERROR;
4550}
4551
Eric Laurente0720872014-03-11 09:30:41 -07004552void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004553 audio_devices_t device,
4554 int delayMs,
4555 bool force)
4556{
4557 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4558
Eric Laurent3b73df72014-03-11 09:06:29 -07004559 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4560 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004561 mStreams[stream].getVolumeIndex(device),
4562 output,
4563 device,
4564 delayMs,
4565 force);
4566 }
4567}
4568
Eric Laurente0720872014-03-11 09:30:41 -07004569void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004570 bool on,
4571 audio_io_handle_t output,
4572 int delayMs,
4573 audio_devices_t device)
4574{
4575 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004576 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4577 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4578 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004579 }
4580 }
4581}
4582
Eric Laurente0720872014-03-11 09:30:41 -07004583void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004584 bool on,
4585 audio_io_handle_t output,
4586 int delayMs,
4587 audio_devices_t device)
4588{
4589 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004590 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004591 if (device == AUDIO_DEVICE_NONE) {
4592 device = outputDesc->device();
4593 }
4594
4595 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4596 stream, on, output, outputDesc->mMuteCount[stream], device);
4597
4598 if (on) {
4599 if (outputDesc->mMuteCount[stream] == 0) {
4600 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004601 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4602 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004603 checkAndSetVolume(stream, 0, output, device, delayMs);
4604 }
4605 }
4606 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4607 outputDesc->mMuteCount[stream]++;
4608 } else {
4609 if (outputDesc->mMuteCount[stream] == 0) {
4610 ALOGV("setStreamMute() unmuting non muted stream!");
4611 return;
4612 }
4613 if (--outputDesc->mMuteCount[stream] == 0) {
4614 checkAndSetVolume(stream,
4615 streamDesc.getVolumeIndex(device),
4616 output,
4617 device,
4618 delayMs);
4619 }
4620 }
4621}
4622
Eric Laurente0720872014-03-11 09:30:41 -07004623void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004624 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004625{
4626 // if the stream pertains to sonification strategy and we are in call we must
4627 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4628 // in the device used for phone strategy and play the tone if the selected device does not
4629 // interfere with the device used for phone strategy
4630 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4631 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004632 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004633 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4634 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004635 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004636 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4637 stream, starting, outputDesc->mDevice, stateChange);
4638 if (outputDesc->mRefCount[stream]) {
4639 int muteCount = 1;
4640 if (stateChange) {
4641 muteCount = outputDesc->mRefCount[stream];
4642 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004643 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004644 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4645 for (int i = 0; i < muteCount; i++) {
4646 setStreamMute(stream, starting, mPrimaryOutput);
4647 }
4648 } else {
4649 ALOGV("handleIncallSonification() high visibility");
4650 if (outputDesc->device() &
4651 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4652 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4653 for (int i = 0; i < muteCount; i++) {
4654 setStreamMute(stream, starting, mPrimaryOutput);
4655 }
4656 }
4657 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004658 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4659 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004660 } else {
4661 mpClientInterface->stopTone();
4662 }
4663 }
4664 }
4665 }
4666}
4667
Eric Laurente0720872014-03-11 09:30:41 -07004668bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004669{
4670 return isStateInCall(mPhoneState);
4671}
4672
Eric Laurente0720872014-03-11 09:30:41 -07004673bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004674 return ((state == AUDIO_MODE_IN_CALL) ||
4675 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004676}
4677
Eric Laurente0720872014-03-11 09:30:41 -07004678uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004679{
4680 return MAX_EFFECTS_CPU_LOAD;
4681}
4682
Eric Laurente0720872014-03-11 09:30:41 -07004683uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004684{
4685 return MAX_EFFECTS_MEMORY;
4686}
4687
Eric Laurent6a94d692014-05-20 11:18:06 -07004688
Eric Laurente552edb2014-03-10 17:42:56 -07004689// --- AudioOutputDescriptor class implementation
4690
Eric Laurente0720872014-03-11 09:30:41 -07004691AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004692 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004693 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004694 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004695 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4696{
4697 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004698 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004699 mRefCount[i] = 0;
4700 mCurVolume[i] = -1.0;
4701 mMuteCount[i] = 0;
4702 mStopTime[i] = 0;
4703 }
4704 for (int i = 0; i < NUM_STRATEGIES; i++) {
4705 mStrategyMutedByDevice[i] = false;
4706 }
4707 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004708 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07004709 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07004710 mSamplingRate = profile->pickSamplingRate();
4711 mFormat = profile->pickFormat();
4712 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004713 if (profile->mGains.size() > 0) {
4714 profile->mGains[0]->getDefaultConfig(&mGain);
4715 }
Eric Laurente552edb2014-03-10 17:42:56 -07004716 }
4717}
4718
Eric Laurente0720872014-03-11 09:30:41 -07004719audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004720{
4721 if (isDuplicated()) {
4722 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4723 } else {
4724 return mDevice;
4725 }
4726}
4727
Eric Laurente0720872014-03-11 09:30:41 -07004728uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004729{
4730 if (isDuplicated()) {
4731 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4732 } else {
4733 return mLatency;
4734 }
4735}
4736
Eric Laurente0720872014-03-11 09:30:41 -07004737bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004738 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004739{
4740 if (isDuplicated()) {
4741 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4742 } else if (outputDesc->isDuplicated()){
4743 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4744 } else {
4745 return (mProfile->mModule == outputDesc->mProfile->mModule);
4746 }
4747}
4748
Eric Laurente0720872014-03-11 09:30:41 -07004749void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004750 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004751{
4752 // forward usage count change to attached outputs
4753 if (isDuplicated()) {
4754 mOutput1->changeRefCount(stream, delta);
4755 mOutput2->changeRefCount(stream, delta);
4756 }
4757 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004758 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4759 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004760 mRefCount[stream] = 0;
4761 return;
4762 }
4763 mRefCount[stream] += delta;
4764 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4765}
4766
Eric Laurente0720872014-03-11 09:30:41 -07004767audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004768{
4769 if (isDuplicated()) {
4770 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4771 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004772 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004773 }
4774}
4775
Eric Laurente0720872014-03-11 09:30:41 -07004776bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004777{
4778 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4779}
4780
Eric Laurente0720872014-03-11 09:30:41 -07004781bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004782 uint32_t inPastMs,
4783 nsecs_t sysTime) const
4784{
4785 if ((sysTime == 0) && (inPastMs != 0)) {
4786 sysTime = systemTime();
4787 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004788 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4789 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004790 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004791 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004792 return true;
4793 }
4794 }
4795 return false;
4796}
4797
Eric Laurente0720872014-03-11 09:30:41 -07004798bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004799 uint32_t inPastMs,
4800 nsecs_t sysTime) const
4801{
4802 if (mRefCount[stream] != 0) {
4803 return true;
4804 }
4805 if (inPastMs == 0) {
4806 return false;
4807 }
4808 if (sysTime == 0) {
4809 sysTime = systemTime();
4810 }
4811 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4812 return true;
4813 }
4814 return false;
4815}
4816
Eric Laurent1c333e22014-05-20 10:48:17 -07004817void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004818 struct audio_port_config *dstConfig,
4819 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004820{
Eric Laurent84c70242014-06-23 08:46:27 -07004821 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4822
Eric Laurent1f2f2232014-06-02 12:01:23 -07004823 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4824 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4825 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004826 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004827 }
4828 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4829
Eric Laurent6a94d692014-05-20 11:18:06 -07004830 dstConfig->id = mId;
4831 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4832 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004833 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4834 dstConfig->ext.mix.handle = mIoHandle;
4835 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004836}
4837
4838void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4839 struct audio_port *port) const
4840{
Eric Laurent84c70242014-06-23 08:46:27 -07004841 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004842 mProfile->toAudioPort(port);
4843 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004844 toAudioPortConfig(&port->active_config);
4845 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004846 port->ext.mix.handle = mIoHandle;
4847 port->ext.mix.latency_class =
4848 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4849}
Eric Laurente552edb2014-03-10 17:42:56 -07004850
Eric Laurente0720872014-03-11 09:30:41 -07004851status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004852{
4853 const size_t SIZE = 256;
4854 char buffer[SIZE];
4855 String8 result;
4856
4857 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4858 result.append(buffer);
4859 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4860 result.append(buffer);
4861 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4862 result.append(buffer);
4863 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4864 result.append(buffer);
4865 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4866 result.append(buffer);
4867 snprintf(buffer, SIZE, " Devices %08x\n", device());
4868 result.append(buffer);
4869 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4870 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004871 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4872 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4873 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004874 result.append(buffer);
4875 }
4876 write(fd, result.string(), result.size());
4877
4878 return NO_ERROR;
4879}
4880
4881// --- AudioInputDescriptor class implementation
4882
Eric Laurent1c333e22014-05-20 10:48:17 -07004883AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004884 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004885 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004886 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004887{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004888 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004889 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07004890 mSamplingRate = profile->pickSamplingRate();
4891 mFormat = profile->pickFormat();
4892 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004893 if (profile->mGains.size() > 0) {
4894 profile->mGains[0]->getDefaultConfig(&mGain);
4895 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004896 }
Eric Laurente552edb2014-03-10 17:42:56 -07004897}
4898
Eric Laurent1c333e22014-05-20 10:48:17 -07004899void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004900 struct audio_port_config *dstConfig,
4901 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004902{
Eric Laurent84c70242014-06-23 08:46:27 -07004903 ALOG_ASSERT(mProfile != 0,
4904 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004905 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4906 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4907 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004908 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004909 }
4910
4911 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4912
Eric Laurent6a94d692014-05-20 11:18:06 -07004913 dstConfig->id = mId;
4914 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4915 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004916 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4917 dstConfig->ext.mix.handle = mIoHandle;
4918 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004919}
4920
4921void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4922 struct audio_port *port) const
4923{
Eric Laurent84c70242014-06-23 08:46:27 -07004924 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
4925
Eric Laurent1c333e22014-05-20 10:48:17 -07004926 mProfile->toAudioPort(port);
4927 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004928 toAudioPortConfig(&port->active_config);
4929 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004930 port->ext.mix.handle = mIoHandle;
4931 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4932}
4933
Eric Laurente0720872014-03-11 09:30:41 -07004934status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004935{
4936 const size_t SIZE = 256;
4937 char buffer[SIZE];
4938 String8 result;
4939
4940 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4941 result.append(buffer);
4942 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4943 result.append(buffer);
4944 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4945 result.append(buffer);
4946 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4947 result.append(buffer);
4948 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4949 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004950 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
4951 result.append(buffer);
4952
Eric Laurente552edb2014-03-10 17:42:56 -07004953 write(fd, result.string(), result.size());
4954
4955 return NO_ERROR;
4956}
4957
4958// --- StreamDescriptor class implementation
4959
Eric Laurente0720872014-03-11 09:30:41 -07004960AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004961 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4962{
4963 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4964}
4965
Eric Laurente0720872014-03-11 09:30:41 -07004966int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004967{
Eric Laurente0720872014-03-11 09:30:41 -07004968 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004969 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4970 if (mIndexCur.indexOfKey(device) < 0) {
4971 device = AUDIO_DEVICE_OUT_DEFAULT;
4972 }
4973 return mIndexCur.valueFor(device);
4974}
4975
Eric Laurente0720872014-03-11 09:30:41 -07004976void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004977{
4978 const size_t SIZE = 256;
4979 char buffer[SIZE];
4980 String8 result;
4981
4982 snprintf(buffer, SIZE, "%s %02d %02d ",
4983 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4984 result.append(buffer);
4985 for (size_t i = 0; i < mIndexCur.size(); i++) {
4986 snprintf(buffer, SIZE, "%04x : %02d, ",
4987 mIndexCur.keyAt(i),
4988 mIndexCur.valueAt(i));
4989 result.append(buffer);
4990 }
4991 result.append("\n");
4992
4993 write(fd, result.string(), result.size());
4994}
4995
4996// --- EffectDescriptor class implementation
4997
Eric Laurente0720872014-03-11 09:30:41 -07004998status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004999{
5000 const size_t SIZE = 256;
5001 char buffer[SIZE];
5002 String8 result;
5003
5004 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5005 result.append(buffer);
5006 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5007 result.append(buffer);
5008 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5009 result.append(buffer);
5010 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5011 result.append(buffer);
5012 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5013 result.append(buffer);
5014 write(fd, result.string(), result.size());
5015
5016 return NO_ERROR;
5017}
5018
Eric Laurent1c333e22014-05-20 10:48:17 -07005019// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005020
Eric Laurente0720872014-03-11 09:30:41 -07005021AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005022 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5023 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005024{
5025}
5026
Eric Laurente0720872014-03-11 09:30:41 -07005027AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005028{
5029 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005030 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005031 }
5032 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005033 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005034 }
5035 free((void *)mName);
5036}
5037
Eric Laurent1afeecb2014-05-14 08:52:28 -07005038status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5039{
5040 cnode *node = root->first_child;
5041
5042 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5043
5044 while (node) {
5045 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5046 profile->loadSamplingRates((char *)node->value);
5047 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5048 profile->loadFormats((char *)node->value);
5049 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5050 profile->loadInChannels((char *)node->value);
5051 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5052 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5053 mDeclaredDevices);
5054 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5055 profile->loadGains(node);
5056 }
5057 node = node->next;
5058 }
5059 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5060 "loadInput() invalid supported devices");
5061 ALOGW_IF(profile->mChannelMasks.size() == 0,
5062 "loadInput() invalid supported channel masks");
5063 ALOGW_IF(profile->mSamplingRates.size() == 0,
5064 "loadInput() invalid supported sampling rates");
5065 ALOGW_IF(profile->mFormats.size() == 0,
5066 "loadInput() invalid supported formats");
5067 if (!profile->mSupportedDevices.isEmpty() &&
5068 (profile->mChannelMasks.size() != 0) &&
5069 (profile->mSamplingRates.size() != 0) &&
5070 (profile->mFormats.size() != 0)) {
5071
5072 ALOGV("loadInput() adding input Supported Devices %04x",
5073 profile->mSupportedDevices.types());
5074
5075 mInputProfiles.add(profile);
5076 return NO_ERROR;
5077 } else {
5078 return BAD_VALUE;
5079 }
5080}
5081
5082status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5083{
5084 cnode *node = root->first_child;
5085
5086 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5087
5088 while (node) {
5089 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5090 profile->loadSamplingRates((char *)node->value);
5091 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5092 profile->loadFormats((char *)node->value);
5093 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5094 profile->loadOutChannels((char *)node->value);
5095 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5096 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5097 mDeclaredDevices);
5098 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5099 profile->mFlags = parseFlagNames((char *)node->value);
5100 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5101 profile->loadGains(node);
5102 }
5103 node = node->next;
5104 }
5105 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5106 "loadOutput() invalid supported devices");
5107 ALOGW_IF(profile->mChannelMasks.size() == 0,
5108 "loadOutput() invalid supported channel masks");
5109 ALOGW_IF(profile->mSamplingRates.size() == 0,
5110 "loadOutput() invalid supported sampling rates");
5111 ALOGW_IF(profile->mFormats.size() == 0,
5112 "loadOutput() invalid supported formats");
5113 if (!profile->mSupportedDevices.isEmpty() &&
5114 (profile->mChannelMasks.size() != 0) &&
5115 (profile->mSamplingRates.size() != 0) &&
5116 (profile->mFormats.size() != 0)) {
5117
5118 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5119 profile->mSupportedDevices.types(), profile->mFlags);
5120
5121 mOutputProfiles.add(profile);
5122 return NO_ERROR;
5123 } else {
5124 return BAD_VALUE;
5125 }
5126}
5127
5128status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5129{
5130 cnode *node = root->first_child;
5131
5132 audio_devices_t type = AUDIO_DEVICE_NONE;
5133 while (node) {
5134 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5135 type = parseDeviceNames((char *)node->value);
5136 break;
5137 }
5138 node = node->next;
5139 }
5140 if (type == AUDIO_DEVICE_NONE ||
5141 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5142 ALOGW("loadDevice() bad type %08x", type);
5143 return BAD_VALUE;
5144 }
5145 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5146 deviceDesc->mModule = this;
5147
5148 node = root->first_child;
5149 while (node) {
5150 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5151 deviceDesc->mAddress = String8((char *)node->value);
5152 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5153 if (audio_is_input_device(type)) {
5154 deviceDesc->loadInChannels((char *)node->value);
5155 } else {
5156 deviceDesc->loadOutChannels((char *)node->value);
5157 }
5158 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5159 deviceDesc->loadGains(node);
5160 }
5161 node = node->next;
5162 }
5163
5164 ALOGV("loadDevice() adding device name %s type %08x address %s",
5165 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5166
5167 mDeclaredDevices.add(deviceDesc);
5168
5169 return NO_ERROR;
5170}
5171
Eric Laurente0720872014-03-11 09:30:41 -07005172void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005173{
5174 const size_t SIZE = 256;
5175 char buffer[SIZE];
5176 String8 result;
5177
5178 snprintf(buffer, SIZE, " - name: %s\n", mName);
5179 result.append(buffer);
5180 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5181 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005182 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5183 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005184 write(fd, result.string(), result.size());
5185 if (mOutputProfiles.size()) {
5186 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5187 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005188 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005189 write(fd, buffer, strlen(buffer));
5190 mOutputProfiles[i]->dump(fd);
5191 }
5192 }
5193 if (mInputProfiles.size()) {
5194 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5195 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005196 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005197 write(fd, buffer, strlen(buffer));
5198 mInputProfiles[i]->dump(fd);
5199 }
5200 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005201 if (mDeclaredDevices.size()) {
5202 write(fd, " - devices:\n", strlen(" - devices:\n"));
5203 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5204 mDeclaredDevices[i]->dump(fd, 4, i);
5205 }
5206 }
Eric Laurente552edb2014-03-10 17:42:56 -07005207}
5208
Eric Laurent1c333e22014-05-20 10:48:17 -07005209// --- AudioPort class implementation
5210
Eric Laurenta121f902014-06-03 13:32:54 -07005211
5212AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5213 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005214 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005215{
5216 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5217 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5218}
5219
Eric Laurent1c333e22014-05-20 10:48:17 -07005220void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5221{
5222 port->role = mRole;
5223 port->type = mType;
5224 unsigned int i;
5225 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5226 port->sample_rates[i] = mSamplingRates[i];
5227 }
5228 port->num_sample_rates = i;
5229 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5230 port->channel_masks[i] = mChannelMasks[i];
5231 }
5232 port->num_channel_masks = i;
5233 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5234 port->formats[i] = mFormats[i];
5235 }
5236 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005237
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005238 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005239
5240 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5241 port->gains[i] = mGains[i]->mGain;
5242 }
5243 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005244}
5245
5246
5247void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5248{
5249 char *str = strtok(name, "|");
5250
5251 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5252 // rates should be read from the output stream after it is opened for the first time
5253 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5254 mSamplingRates.add(0);
5255 return;
5256 }
5257
5258 while (str != NULL) {
5259 uint32_t rate = atoi(str);
5260 if (rate != 0) {
5261 ALOGV("loadSamplingRates() adding rate %d", rate);
5262 mSamplingRates.add(rate);
5263 }
5264 str = strtok(NULL, "|");
5265 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005266}
5267
5268void AudioPolicyManager::AudioPort::loadFormats(char *name)
5269{
5270 char *str = strtok(name, "|");
5271
5272 // by convention, "0' in the first entry in mFormats indicates the supported formats
5273 // should be read from the output stream after it is opened for the first time
5274 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5275 mFormats.add(AUDIO_FORMAT_DEFAULT);
5276 return;
5277 }
5278
5279 while (str != NULL) {
5280 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5281 ARRAY_SIZE(sFormatNameToEnumTable),
5282 str);
5283 if (format != AUDIO_FORMAT_DEFAULT) {
5284 mFormats.add(format);
5285 }
5286 str = strtok(NULL, "|");
5287 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005288}
5289
5290void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5291{
5292 const char *str = strtok(name, "|");
5293
5294 ALOGV("loadInChannels() %s", name);
5295
5296 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5297 mChannelMasks.add(0);
5298 return;
5299 }
5300
5301 while (str != NULL) {
5302 audio_channel_mask_t channelMask =
5303 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5304 ARRAY_SIZE(sInChannelsNameToEnumTable),
5305 str);
5306 if (channelMask != 0) {
5307 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5308 mChannelMasks.add(channelMask);
5309 }
5310 str = strtok(NULL, "|");
5311 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005312}
5313
5314void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5315{
5316 const char *str = strtok(name, "|");
5317
5318 ALOGV("loadOutChannels() %s", name);
5319
5320 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5321 // masks should be read from the output stream after it is opened for the first time
5322 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5323 mChannelMasks.add(0);
5324 return;
5325 }
5326
5327 while (str != NULL) {
5328 audio_channel_mask_t channelMask =
5329 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5330 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5331 str);
5332 if (channelMask != 0) {
5333 mChannelMasks.add(channelMask);
5334 }
5335 str = strtok(NULL, "|");
5336 }
5337 return;
5338}
5339
Eric Laurent1afeecb2014-05-14 08:52:28 -07005340audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5341{
5342 const char *str = strtok(name, "|");
5343
5344 ALOGV("loadGainMode() %s", name);
5345 audio_gain_mode_t mode = 0;
5346 while (str != NULL) {
5347 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5348 ARRAY_SIZE(sGainModeNameToEnumTable),
5349 str);
5350 str = strtok(NULL, "|");
5351 }
5352 return mode;
5353}
5354
Eric Laurenta121f902014-06-03 13:32:54 -07005355void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005356{
5357 cnode *node = root->first_child;
5358
Eric Laurenta121f902014-06-03 13:32:54 -07005359 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005360
5361 while (node) {
5362 if (strcmp(node->name, GAIN_MODE) == 0) {
5363 gain->mGain.mode = loadGainMode((char *)node->value);
5364 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005365 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005366 gain->mGain.channel_mask =
5367 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5368 ARRAY_SIZE(sInChannelsNameToEnumTable),
5369 (char *)node->value);
5370 } else {
5371 gain->mGain.channel_mask =
5372 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5373 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5374 (char *)node->value);
5375 }
5376 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5377 gain->mGain.min_value = atoi((char *)node->value);
5378 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5379 gain->mGain.max_value = atoi((char *)node->value);
5380 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5381 gain->mGain.default_value = atoi((char *)node->value);
5382 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5383 gain->mGain.step_value = atoi((char *)node->value);
5384 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5385 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5386 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5387 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5388 }
5389 node = node->next;
5390 }
5391
5392 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5393 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5394
5395 if (gain->mGain.mode == 0) {
5396 return;
5397 }
5398 mGains.add(gain);
5399}
5400
5401void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5402{
5403 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005404 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005405 while (node) {
5406 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005407 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005408 node = node->next;
5409 }
5410}
5411
Glenn Kastencbd48022014-07-24 13:46:44 -07005412status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005413{
5414 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5415 if (mSamplingRates[i] == samplingRate) {
5416 return NO_ERROR;
5417 }
5418 }
5419 return BAD_VALUE;
5420}
5421
Glenn Kastencbd48022014-07-24 13:46:44 -07005422status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5423 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005424{
Glenn Kastencbd48022014-07-24 13:46:44 -07005425 // Search for the closest supported sampling rate that is above (preferred)
5426 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5427 // The sampling rates do not need to be sorted in ascending order.
5428 ssize_t maxBelow = -1;
5429 ssize_t minAbove = -1;
5430 uint32_t candidate;
5431 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5432 candidate = mSamplingRates[i];
5433 if (candidate == samplingRate) {
5434 if (updatedSamplingRate != NULL) {
5435 *updatedSamplingRate = candidate;
5436 }
5437 return NO_ERROR;
5438 }
5439 // candidate < desired
5440 if (candidate < samplingRate) {
5441 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5442 maxBelow = i;
5443 }
5444 // candidate > desired
5445 } else {
5446 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5447 minAbove = i;
5448 }
5449 }
5450 }
5451 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5452 // TODO Move these assumptions out.
5453 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5454 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5455 // due to approximation by an int32_t of the
5456 // phase increments
5457 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5458 if (minAbove >= 0) {
5459 candidate = mSamplingRates[minAbove];
5460 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5461 if (updatedSamplingRate != NULL) {
5462 *updatedSamplingRate = candidate;
5463 }
5464 return NO_ERROR;
5465 }
5466 }
5467 // But if we have to up-sample from a lower sampling rate, that's OK.
5468 if (maxBelow >= 0) {
5469 candidate = mSamplingRates[maxBelow];
5470 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5471 if (updatedSamplingRate != NULL) {
5472 *updatedSamplingRate = candidate;
5473 }
5474 return NO_ERROR;
5475 }
5476 }
5477 // leave updatedSamplingRate unmodified
5478 return BAD_VALUE;
5479}
5480
5481status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5482{
5483 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005484 if (mChannelMasks[i] == channelMask) {
5485 return NO_ERROR;
5486 }
5487 }
5488 return BAD_VALUE;
5489}
5490
Glenn Kastencbd48022014-07-24 13:46:44 -07005491status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5492 const
5493{
5494 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5495 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5496 // FIXME Does not handle multi-channel automatic conversions yet
5497 audio_channel_mask_t supported = mChannelMasks[i];
5498 if (supported == channelMask) {
5499 return NO_ERROR;
5500 }
5501 if (isRecordThread) {
5502 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5503 // FIXME Abstract this out to a table.
5504 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5505 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5506 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5507 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5508 return NO_ERROR;
5509 }
5510 }
5511 }
5512 return BAD_VALUE;
5513}
5514
Eric Laurenta121f902014-06-03 13:32:54 -07005515status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5516{
5517 for (size_t i = 0; i < mFormats.size(); i ++) {
5518 if (mFormats[i] == format) {
5519 return NO_ERROR;
5520 }
5521 }
5522 return BAD_VALUE;
5523}
5524
Eric Laurent1e693b52014-07-09 15:03:28 -07005525
5526uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5527{
5528 // special case for uninitialized dynamic profile
5529 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5530 return 0;
5531 }
5532
5533 uint32_t samplingRate = 0;
5534 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5535
5536 // For mixed output and inputs, use max mixer sampling rates. Do not
5537 // limit sampling rate otherwise
5538 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5539 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5540 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5541 maxRate = UINT_MAX;
5542 }
5543 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5544 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5545 samplingRate = mSamplingRates[i];
5546 }
5547 }
5548 return samplingRate;
5549}
5550
5551audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5552{
5553 // special case for uninitialized dynamic profile
5554 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5555 return AUDIO_CHANNEL_NONE;
5556 }
5557
5558 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5559 uint32_t channelCount = 0;
5560 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5561
5562 // For mixed output and inputs, use max mixer channel count. Do not
5563 // limit channel count otherwise
5564 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5565 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5566 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5567 maxCount = UINT_MAX;
5568 }
5569 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5570 uint32_t cnlCount;
5571 if (mUseInChannelMask) {
5572 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5573 } else {
5574 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5575 }
5576 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5577 channelMask = mChannelMasks[i];
5578 }
5579 }
5580 return channelMask;
5581}
5582
Andy Hung9a605382014-07-28 16:16:31 -07005583/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07005584const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5585 AUDIO_FORMAT_DEFAULT,
5586 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005587 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005588 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005589 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07005590 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005591};
5592
5593int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5594 audio_format_t format2)
5595{
5596 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5597 // compressed format and better than any PCM format. This is by design of pickFormat()
5598 if (!audio_is_linear_pcm(format1)) {
5599 if (!audio_is_linear_pcm(format2)) {
5600 return 0;
5601 }
5602 return 1;
5603 }
5604 if (!audio_is_linear_pcm(format2)) {
5605 return -1;
5606 }
5607
5608 int index1 = -1, index2 = -1;
5609 for (size_t i = 0;
5610 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5611 i ++) {
5612 if (sPcmFormatCompareTable[i] == format1) {
5613 index1 = i;
5614 }
5615 if (sPcmFormatCompareTable[i] == format2) {
5616 index2 = i;
5617 }
5618 }
5619 // format1 not found => index1 < 0 => format2 > format1
5620 // format2 not found => index2 < 0 => format2 < format1
5621 return index1 - index2;
5622}
5623
5624audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5625{
5626 // special case for uninitialized dynamic profile
5627 if (mFormats.size() == 1 && mFormats[0] == 0) {
5628 return AUDIO_FORMAT_DEFAULT;
5629 }
5630
5631 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07005632 audio_format_t bestFormat =
5633 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5634 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07005635 // For mixed output and inputs, use best mixer output format. Do not
5636 // limit format otherwise
5637 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5638 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07005639 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005640 bestFormat = AUDIO_FORMAT_INVALID;
5641 }
5642
5643 for (size_t i = 0; i < mFormats.size(); i ++) {
5644 if ((compareFormats(mFormats[i], format) > 0) &&
5645 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5646 format = mFormats[i];
5647 }
5648 }
5649 return format;
5650}
5651
Eric Laurenta121f902014-06-03 13:32:54 -07005652status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5653 int index) const
5654{
5655 if (index < 0 || (size_t)index >= mGains.size()) {
5656 return BAD_VALUE;
5657 }
5658 return mGains[index]->checkConfig(gainConfig);
5659}
5660
Eric Laurent1afeecb2014-05-14 08:52:28 -07005661void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5662{
5663 const size_t SIZE = 256;
5664 char buffer[SIZE];
5665 String8 result;
5666
5667 if (mName.size() != 0) {
5668 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5669 result.append(buffer);
5670 }
5671
5672 if (mSamplingRates.size() != 0) {
5673 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5674 result.append(buffer);
5675 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005676 if (i == 0 && mSamplingRates[i] == 0) {
5677 snprintf(buffer, SIZE, "Dynamic");
5678 } else {
5679 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5680 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005681 result.append(buffer);
5682 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5683 }
5684 result.append("\n");
5685 }
5686
5687 if (mChannelMasks.size() != 0) {
5688 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5689 result.append(buffer);
5690 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005691 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5692
5693 if (i == 0 && mChannelMasks[i] == 0) {
5694 snprintf(buffer, SIZE, "Dynamic");
5695 } else {
5696 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5697 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005698 result.append(buffer);
5699 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5700 }
5701 result.append("\n");
5702 }
5703
5704 if (mFormats.size() != 0) {
5705 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5706 result.append(buffer);
5707 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005708 const char *formatStr = enumToString(sFormatNameToEnumTable,
5709 ARRAY_SIZE(sFormatNameToEnumTable),
5710 mFormats[i]);
5711 if (i == 0 && strcmp(formatStr, "") == 0) {
5712 snprintf(buffer, SIZE, "Dynamic");
5713 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07005714 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07005715 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005716 result.append(buffer);
5717 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5718 }
5719 result.append("\n");
5720 }
5721 write(fd, result.string(), result.size());
5722 if (mGains.size() != 0) {
5723 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5724 write(fd, buffer, strlen(buffer) + 1);
5725 result.append(buffer);
5726 for (size_t i = 0; i < mGains.size(); i++) {
5727 mGains[i]->dump(fd, spaces + 2, i);
5728 }
5729 }
5730}
5731
5732// --- AudioGain class implementation
5733
Eric Laurenta121f902014-06-03 13:32:54 -07005734AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005735{
Eric Laurenta121f902014-06-03 13:32:54 -07005736 mIndex = index;
5737 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005738 memset(&mGain, 0, sizeof(struct audio_gain));
5739}
5740
Eric Laurenta121f902014-06-03 13:32:54 -07005741void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5742{
5743 config->index = mIndex;
5744 config->mode = mGain.mode;
5745 config->channel_mask = mGain.channel_mask;
5746 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5747 config->values[0] = mGain.default_value;
5748 } else {
5749 uint32_t numValues;
5750 if (mUseInChannelMask) {
5751 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5752 } else {
5753 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5754 }
5755 for (size_t i = 0; i < numValues; i++) {
5756 config->values[i] = mGain.default_value;
5757 }
5758 }
5759 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5760 config->ramp_duration_ms = mGain.min_ramp_ms;
5761 }
5762}
5763
5764status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5765{
5766 if ((config->mode & ~mGain.mode) != 0) {
5767 return BAD_VALUE;
5768 }
5769 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5770 if ((config->values[0] < mGain.min_value) ||
5771 (config->values[0] > mGain.max_value)) {
5772 return BAD_VALUE;
5773 }
5774 } else {
5775 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5776 return BAD_VALUE;
5777 }
5778 uint32_t numValues;
5779 if (mUseInChannelMask) {
5780 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5781 } else {
5782 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5783 }
5784 for (size_t i = 0; i < numValues; i++) {
5785 if ((config->values[i] < mGain.min_value) ||
5786 (config->values[i] > mGain.max_value)) {
5787 return BAD_VALUE;
5788 }
5789 }
5790 }
5791 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5792 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5793 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5794 return BAD_VALUE;
5795 }
5796 }
5797 return NO_ERROR;
5798}
5799
Eric Laurent1afeecb2014-05-14 08:52:28 -07005800void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5801{
5802 const size_t SIZE = 256;
5803 char buffer[SIZE];
5804 String8 result;
5805
5806 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5807 result.append(buffer);
5808 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5809 result.append(buffer);
5810 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5811 result.append(buffer);
5812 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5813 result.append(buffer);
5814 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5815 result.append(buffer);
5816 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5817 result.append(buffer);
5818 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5819 result.append(buffer);
5820 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5821 result.append(buffer);
5822 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5823 result.append(buffer);
5824
5825 write(fd, result.string(), result.size());
5826}
5827
Eric Laurent1f2f2232014-06-02 12:01:23 -07005828// --- AudioPortConfig class implementation
5829
5830AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5831{
5832 mSamplingRate = 0;
5833 mChannelMask = AUDIO_CHANNEL_NONE;
5834 mFormat = AUDIO_FORMAT_INVALID;
5835 mGain.index = -1;
5836}
5837
Eric Laurenta121f902014-06-03 13:32:54 -07005838status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5839 const struct audio_port_config *config,
5840 struct audio_port_config *backupConfig)
5841{
5842 struct audio_port_config localBackupConfig;
5843 status_t status = NO_ERROR;
5844
5845 localBackupConfig.config_mask = config->config_mask;
5846 toAudioPortConfig(&localBackupConfig);
5847
5848 if (mAudioPort == 0) {
5849 status = NO_INIT;
5850 goto exit;
5851 }
5852 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005853 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07005854 if (status != NO_ERROR) {
5855 goto exit;
5856 }
5857 mSamplingRate = config->sample_rate;
5858 }
5859 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005860 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07005861 if (status != NO_ERROR) {
5862 goto exit;
5863 }
5864 mChannelMask = config->channel_mask;
5865 }
5866 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5867 status = mAudioPort->checkFormat(config->format);
5868 if (status != NO_ERROR) {
5869 goto exit;
5870 }
5871 mFormat = config->format;
5872 }
5873 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5874 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5875 if (status != NO_ERROR) {
5876 goto exit;
5877 }
5878 mGain = config->gain;
5879 }
5880
5881exit:
5882 if (status != NO_ERROR) {
5883 applyAudioPortConfig(&localBackupConfig);
5884 }
5885 if (backupConfig != NULL) {
5886 *backupConfig = localBackupConfig;
5887 }
5888 return status;
5889}
5890
Eric Laurent1f2f2232014-06-02 12:01:23 -07005891void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5892 struct audio_port_config *dstConfig,
5893 const struct audio_port_config *srcConfig) const
5894{
5895 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5896 dstConfig->sample_rate = mSamplingRate;
5897 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5898 dstConfig->sample_rate = srcConfig->sample_rate;
5899 }
5900 } else {
5901 dstConfig->sample_rate = 0;
5902 }
5903 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5904 dstConfig->channel_mask = mChannelMask;
5905 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5906 dstConfig->channel_mask = srcConfig->channel_mask;
5907 }
5908 } else {
5909 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5910 }
5911 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5912 dstConfig->format = mFormat;
5913 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5914 dstConfig->format = srcConfig->format;
5915 }
5916 } else {
5917 dstConfig->format = AUDIO_FORMAT_INVALID;
5918 }
5919 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5920 dstConfig->gain = mGain;
5921 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5922 dstConfig->gain = srcConfig->gain;
5923 }
5924 } else {
5925 dstConfig->gain.index = -1;
5926 }
5927 if (dstConfig->gain.index != -1) {
5928 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5929 } else {
5930 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5931 }
5932}
5933
Eric Laurent1c333e22014-05-20 10:48:17 -07005934// --- IOProfile class implementation
5935
Eric Laurent1afeecb2014-05-14 08:52:28 -07005936AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005937 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07005938 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07005939{
5940}
5941
Eric Laurente0720872014-03-11 09:30:41 -07005942AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005943{
5944}
5945
5946// checks if the IO profile is compatible with specified parameters.
5947// Sampling rate, format and channel mask must be specified in order to
5948// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005949bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005950 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005951 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005952 audio_format_t format,
5953 audio_channel_mask_t channelMask,
5954 audio_output_flags_t flags) const
5955{
Glenn Kastencbd48022014-07-24 13:46:44 -07005956 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
5957 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5958 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07005959
Glenn Kastencbd48022014-07-24 13:46:44 -07005960 if ((mSupportedDevices.types() & device) != device) {
5961 return false;
5962 }
5963
5964 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005965 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005966 }
5967 uint32_t myUpdatedSamplingRate = samplingRate;
5968 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005969 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005970 }
5971 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
5972 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005973 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005974 }
5975
5976 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
5977 return false;
5978 }
5979
5980 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
5981 checkExactChannelMask(channelMask) != NO_ERROR)) {
5982 return false;
5983 }
5984 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
5985 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
5986 return false;
5987 }
5988
5989 if (isPlaybackThread && (mFlags & flags) != flags) {
5990 return false;
5991 }
5992 // The only input flag that is allowed to be different is the fast flag.
5993 // An existing fast stream is compatible with a normal track request.
5994 // An existing normal stream is compatible with a fast track request,
5995 // but the fast request will be denied by AudioFlinger and converted to normal track.
5996 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
5997 ~AUDIO_INPUT_FLAG_FAST)) {
5998 return false;
5999 }
6000
6001 if (updatedSamplingRate != NULL) {
6002 *updatedSamplingRate = myUpdatedSamplingRate;
6003 }
6004 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006005}
6006
Eric Laurente0720872014-03-11 09:30:41 -07006007void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006008{
6009 const size_t SIZE = 256;
6010 char buffer[SIZE];
6011 String8 result;
6012
Eric Laurent1afeecb2014-05-14 08:52:28 -07006013 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006014
Eric Laurente552edb2014-03-10 17:42:56 -07006015 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6016 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006017 snprintf(buffer, SIZE, " - devices:\n");
6018 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006019 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006020 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6021 mSupportedDevices[i]->dump(fd, 6, i);
6022 }
Eric Laurente552edb2014-03-10 17:42:56 -07006023}
6024
Eric Laurentd4692962014-05-05 18:13:44 -07006025void AudioPolicyManager::IOProfile::log()
6026{
6027 const size_t SIZE = 256;
6028 char buffer[SIZE];
6029 String8 result;
6030
6031 ALOGV(" - sampling rates: ");
6032 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6033 ALOGV(" %d", mSamplingRates[i]);
6034 }
6035
6036 ALOGV(" - channel masks: ");
6037 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6038 ALOGV(" 0x%04x", mChannelMasks[i]);
6039 }
6040
6041 ALOGV(" - formats: ");
6042 for (size_t i = 0; i < mFormats.size(); i++) {
6043 ALOGV(" 0x%08x", mFormats[i]);
6044 }
6045
6046 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6047 ALOGV(" - flags: 0x%04x\n", mFlags);
6048}
6049
6050
Eric Laurent3a4311c2014-03-17 12:00:47 -07006051// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006052
Eric Laurent1f2f2232014-06-02 12:01:23 -07006053
6054AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6055 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6056 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6057 AUDIO_PORT_ROLE_SOURCE,
6058 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006059 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006060{
6061 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07006062 if (mGains.size() > 0) {
6063 mGains[0]->getDefaultConfig(&mGain);
6064 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006065}
6066
Eric Laurent3a4311c2014-03-17 12:00:47 -07006067bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006068{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006069 // Devices are considered equal if they:
6070 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6071 // - have the same address or one device does not specify the address
6072 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006073 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006074 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006075 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006076 mChannelMask == other->mChannelMask);
6077}
6078
6079void AudioPolicyManager::DeviceVector::refreshTypes()
6080{
Eric Laurent1c333e22014-05-20 10:48:17 -07006081 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006082 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006083 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006084 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006085 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006086}
6087
6088ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6089{
6090 for(size_t i = 0; i < size(); i++) {
6091 if (item->equals(itemAt(i))) {
6092 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006093 }
6094 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006095 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006096}
6097
Eric Laurent3a4311c2014-03-17 12:00:47 -07006098ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006099{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006100 ssize_t ret = indexOf(item);
6101
6102 if (ret < 0) {
6103 ret = SortedVector::add(item);
6104 if (ret >= 0) {
6105 refreshTypes();
6106 }
6107 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006108 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006109 ret = -1;
6110 }
6111 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006112}
6113
Eric Laurent3a4311c2014-03-17 12:00:47 -07006114ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6115{
6116 size_t i;
6117 ssize_t ret = indexOf(item);
6118
6119 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006120 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006121 } else {
6122 ret = SortedVector::removeAt(ret);
6123 if (ret >= 0) {
6124 refreshTypes();
6125 }
6126 }
6127 return ret;
6128}
6129
6130void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6131{
6132 DeviceVector deviceList;
6133
6134 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6135 types &= ~role_bit;
6136
6137 while (types) {
6138 uint32_t i = 31 - __builtin_clz(types);
6139 uint32_t type = 1 << i;
6140 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006141 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006142 }
6143}
6144
Eric Laurent1afeecb2014-05-14 08:52:28 -07006145void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6146 const DeviceVector& declaredDevices)
6147{
6148 char *devName = strtok(name, "|");
6149 while (devName != NULL) {
6150 if (strlen(devName) != 0) {
6151 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6152 ARRAY_SIZE(sDeviceNameToEnumTable),
6153 devName);
6154 if (type != AUDIO_DEVICE_NONE) {
6155 add(new DeviceDescriptor(String8(""), type));
6156 } else {
6157 sp<DeviceDescriptor> deviceDesc =
6158 declaredDevices.getDeviceFromName(String8(devName));
6159 if (deviceDesc != 0) {
6160 add(deviceDesc);
6161 }
6162 }
6163 }
6164 devName = strtok(NULL, "|");
6165 }
6166}
6167
Eric Laurent1c333e22014-05-20 10:48:17 -07006168sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6169 audio_devices_t type, String8 address) const
6170{
6171 sp<DeviceDescriptor> device;
6172 for (size_t i = 0; i < size(); i++) {
6173 if (itemAt(i)->mDeviceType == type) {
6174 device = itemAt(i);
6175 if (itemAt(i)->mAddress = address) {
6176 break;
6177 }
6178 }
6179 }
6180 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6181 type, address.string(), device.get());
6182 return device;
6183}
6184
Eric Laurent6a94d692014-05-20 11:18:06 -07006185sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6186 audio_port_handle_t id) const
6187{
6188 sp<DeviceDescriptor> device;
6189 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006190 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006191 if (itemAt(i)->mId == id) {
6192 device = itemAt(i);
6193 break;
6194 }
6195 }
6196 return device;
6197}
6198
Eric Laurent1c333e22014-05-20 10:48:17 -07006199AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6200 audio_devices_t type) const
6201{
6202 DeviceVector devices;
6203 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6204 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6205 devices.add(itemAt(i));
6206 type &= ~itemAt(i)->mDeviceType;
6207 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6208 itemAt(i)->mDeviceType, itemAt(i).get());
6209 }
6210 }
6211 return devices;
6212}
6213
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006214AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6215 audio_devices_t type, String8 address) const
6216{
6217 DeviceVector devices;
6218 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6219 for (size_t i = 0; i < size(); i++) {
6220 //ALOGV(" at i=%d: device=%x, addr=%s",
6221 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6222 if (itemAt(i)->mDeviceType == type) {
6223 if (itemAt(i)->mAddress == address) {
6224 //ALOGV(" found matching address %s", address.string());
6225 devices.add(itemAt(i));
6226 }
6227 }
6228 }
6229 return devices;
6230}
6231
Eric Laurent1afeecb2014-05-14 08:52:28 -07006232sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6233 const String8& name) const
6234{
6235 sp<DeviceDescriptor> device;
6236 for (size_t i = 0; i < size(); i++) {
6237 if (itemAt(i)->mName == name) {
6238 device = itemAt(i);
6239 break;
6240 }
6241 }
6242 return device;
6243}
6244
Eric Laurent6a94d692014-05-20 11:18:06 -07006245void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6246 struct audio_port_config *dstConfig,
6247 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006248{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006249 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6250 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006251 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006252 }
6253
6254 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6255
Eric Laurent6a94d692014-05-20 11:18:06 -07006256 dstConfig->id = mId;
6257 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006258 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006259 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006260 dstConfig->ext.device.type = mDeviceType;
6261 dstConfig->ext.device.hw_module = mModule->mHandle;
6262 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006263}
6264
6265void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6266{
Eric Laurent83b88082014-06-20 18:31:16 -07006267 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006268 AudioPort::toAudioPort(port);
6269 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006270 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006271 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006272 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006273 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6274}
6275
Eric Laurent1afeecb2014-05-14 08:52:28 -07006276status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006277{
6278 const size_t SIZE = 256;
6279 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006280 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006281
Eric Laurent1afeecb2014-05-14 08:52:28 -07006282 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6283 result.append(buffer);
6284 if (mId != 0) {
6285 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6286 result.append(buffer);
6287 }
6288 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6289 enumToString(sDeviceNameToEnumTable,
6290 ARRAY_SIZE(sDeviceNameToEnumTable),
6291 mDeviceType));
6292 result.append(buffer);
6293 if (mAddress.size() != 0) {
6294 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6295 result.append(buffer);
6296 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006297 write(fd, result.string(), result.size());
6298 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006299
6300 return NO_ERROR;
6301}
6302
6303
6304// --- audio_policy.conf file parsing
6305
Eric Laurente0720872014-03-11 09:30:41 -07006306audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006307{
6308 uint32_t flag = 0;
6309
6310 // it is OK to cast name to non const here as we are not going to use it after
6311 // strtok() modifies it
6312 char *flagName = strtok(name, "|");
6313 while (flagName != NULL) {
6314 if (strlen(flagName) != 0) {
6315 flag |= stringToEnum(sFlagNameToEnumTable,
6316 ARRAY_SIZE(sFlagNameToEnumTable),
6317 flagName);
6318 }
6319 flagName = strtok(NULL, "|");
6320 }
6321 //force direct flag if offload flag is set: offloading implies a direct output stream
6322 // and all common behaviors are driven by checking only the direct flag
6323 // this should normally be set appropriately in the policy configuration file
6324 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6325 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6326 }
6327
6328 return (audio_output_flags_t)flag;
6329}
6330
Eric Laurente0720872014-03-11 09:30:41 -07006331audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006332{
6333 uint32_t device = 0;
6334
6335 char *devName = strtok(name, "|");
6336 while (devName != NULL) {
6337 if (strlen(devName) != 0) {
6338 device |= stringToEnum(sDeviceNameToEnumTable,
6339 ARRAY_SIZE(sDeviceNameToEnumTable),
6340 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006341 }
Eric Laurente552edb2014-03-10 17:42:56 -07006342 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006343 }
Eric Laurente552edb2014-03-10 17:42:56 -07006344 return device;
6345}
6346
Eric Laurente0720872014-03-11 09:30:41 -07006347void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006348{
Eric Laurente552edb2014-03-10 17:42:56 -07006349 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006350 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006351 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006352
Eric Laurent1afeecb2014-05-14 08:52:28 -07006353 node = config_find(root, DEVICES_TAG);
6354 if (node != NULL) {
6355 node = node->first_child;
6356 while (node) {
6357 ALOGV("loadHwModule() loading device %s", node->name);
6358 status_t tmpStatus = module->loadDevice(node);
6359 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6360 status = tmpStatus;
6361 }
6362 node = node->next;
6363 }
6364 }
6365 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006366 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006367 node = node->first_child;
6368 while (node) {
6369 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006370 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006371 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6372 status = tmpStatus;
6373 }
6374 node = node->next;
6375 }
6376 }
6377 node = config_find(root, INPUTS_TAG);
6378 if (node != NULL) {
6379 node = node->first_child;
6380 while (node) {
6381 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006382 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006383 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6384 status = tmpStatus;
6385 }
6386 node = node->next;
6387 }
6388 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006389 loadGlobalConfig(root, module);
6390
Eric Laurente552edb2014-03-10 17:42:56 -07006391 if (status == NO_ERROR) {
6392 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006393 }
6394}
6395
Eric Laurente0720872014-03-11 09:30:41 -07006396void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006397{
6398 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6399 if (node == NULL) {
6400 return;
6401 }
6402
6403 node = node->first_child;
6404 while (node) {
6405 ALOGV("loadHwModules() loading module %s", node->name);
6406 loadHwModule(node);
6407 node = node->next;
6408 }
6409}
6410
Eric Laurent1f2f2232014-06-02 12:01:23 -07006411void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006412{
6413 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006414
Eric Laurente552edb2014-03-10 17:42:56 -07006415 if (node == NULL) {
6416 return;
6417 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006418 DeviceVector declaredDevices;
6419 if (module != NULL) {
6420 declaredDevices = module->mDeclaredDevices;
6421 }
6422
Eric Laurente552edb2014-03-10 17:42:56 -07006423 node = node->first_child;
6424 while (node) {
6425 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006426 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6427 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006428 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6429 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006430 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006431 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006432 ARRAY_SIZE(sDeviceNameToEnumTable),
6433 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006434 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006435 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006436 } else {
6437 ALOGW("loadGlobalConfig() default device not specified");
6438 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006439 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006440 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006441 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6442 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006443 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006444 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6445 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6446 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006447 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6448 uint32_t major, minor;
6449 sscanf((char *)node->value, "%u.%u", &major, &minor);
6450 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6451 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6452 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006453 }
6454 node = node->next;
6455 }
6456}
6457
Eric Laurente0720872014-03-11 09:30:41 -07006458status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006459{
6460 cnode *root;
6461 char *data;
6462
6463 data = (char *)load_file(path, NULL);
6464 if (data == NULL) {
6465 return -ENODEV;
6466 }
6467 root = config_node("", "");
6468 config_load(root, data);
6469
Eric Laurente552edb2014-03-10 17:42:56 -07006470 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006471 // legacy audio_policy.conf files have one global_configuration section
6472 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006473 config_free(root);
6474 free(root);
6475 free(data);
6476
6477 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6478
6479 return NO_ERROR;
6480}
6481
Eric Laurente0720872014-03-11 09:30:41 -07006482void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006483{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006484 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006485 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006486 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6487 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006488 mAvailableOutputDevices.add(mDefaultOutputDevice);
6489 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006490
6491 module = new HwModule("primary");
6492
Eric Laurent1afeecb2014-05-14 08:52:28 -07006493 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006494 profile->mSamplingRates.add(44100);
6495 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6496 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006497 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006498 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6499 module->mOutputProfiles.add(profile);
6500
Eric Laurent1afeecb2014-05-14 08:52:28 -07006501 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006502 profile->mSamplingRates.add(8000);
6503 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6504 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006505 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006506 module->mInputProfiles.add(profile);
6507
6508 mHwModules.add(module);
6509}
6510
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006511audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6512{
6513 // flags to stream type mapping
6514 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6515 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6516 }
6517 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6518 return AUDIO_STREAM_BLUETOOTH_SCO;
6519 }
6520
6521 // usage to stream type mapping
6522 switch (attr->usage) {
6523 case AUDIO_USAGE_MEDIA:
6524 case AUDIO_USAGE_GAME:
6525 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6526 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6527 return AUDIO_STREAM_MUSIC;
6528 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6529 return AUDIO_STREAM_SYSTEM;
6530 case AUDIO_USAGE_VOICE_COMMUNICATION:
6531 return AUDIO_STREAM_VOICE_CALL;
6532
6533 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6534 return AUDIO_STREAM_DTMF;
6535
6536 case AUDIO_USAGE_ALARM:
6537 return AUDIO_STREAM_ALARM;
6538 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6539 return AUDIO_STREAM_RING;
6540
6541 case AUDIO_USAGE_NOTIFICATION:
6542 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6543 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6544 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6545 case AUDIO_USAGE_NOTIFICATION_EVENT:
6546 return AUDIO_STREAM_NOTIFICATION;
6547
6548 case AUDIO_USAGE_UNKNOWN:
6549 default:
6550 return AUDIO_STREAM_MUSIC;
6551 }
6552}
Eric Laurente552edb2014-03-10 17:42:56 -07006553}; // namespace android