blob: 22c4e04556c9990a5f393c757246ccdca5d4c18f [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070046#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070047#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070048#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070053// Definitions for audio_policy.conf file parsing
54// ----------------------------------------------------------------------------
55
56struct StringToEnum {
57 const char *name;
58 uint32_t value;
59};
60
61#define STRING_TO_ENUM(string) { #string, string }
62#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
63
64const StringToEnum sDeviceNameToEnumTable[] = {
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050067 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070079 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070086 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070091 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050092 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070093 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
108 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
110 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700111 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900112 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700113};
114
115const StringToEnum sFlagNameToEnumTable[] = {
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700123};
124
125const StringToEnum sFormatNameToEnumTable[] = {
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
127 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
128 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
129 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
130 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
131 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
132 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
133 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700144 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700145 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
146 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
147 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
148 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
149 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150};
151
152const StringToEnum sOutChannelsNameToEnumTable[] = {
153 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
154 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700155 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
157 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
158};
159
160const StringToEnum sInChannelsNameToEnumTable[] = {
161 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
162 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
163 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
164};
165
Eric Laurent1afeecb2014-05-14 08:52:28 -0700166const StringToEnum sGainModeNameToEnumTable[] = {
167 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
168 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
169 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
170};
171
Eric Laurent3a4311c2014-03-17 12:00:47 -0700172
173uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
174 size_t size,
175 const char *name)
176{
177 for (size_t i = 0; i < size; i++) {
178 if (strcmp(table[i].name, name) == 0) {
179 ALOGV("stringToEnum() found %s", table[i].name);
180 return table[i].value;
181 }
182 }
183 return 0;
184}
185
186const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
187 size_t size,
188 uint32_t value)
189{
190 for (size_t i = 0; i < size; i++) {
191 if (table[i].value == value) {
192 return table[i].name;
193 }
194 }
195 return "";
196}
197
198bool AudioPolicyManager::stringToBool(const char *value)
199{
200 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
201}
202
203
204// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700205// AudioPolicyInterface implementation
206// ----------------------------------------------------------------------------
207
208
Eric Laurente0720872014-03-11 09:30:41 -0700209status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700210 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700211 const char *device_address)
212{
Eric Laurent22226012014-08-01 17:00:54 -0700213 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700214
Eric Laurent22226012014-08-01 17:00:54 -0700215 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
216 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700217
218 // connect/disconnect only 1 device at a time
219 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
220
Eric Laurente552edb2014-03-10 17:42:56 -0700221 // handle output devices
222 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700223 SortedVector <audio_io_handle_t> outputs;
224
Eric Laurent1afeecb2014-05-14 08:52:28 -0700225 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
226 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700227 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
228
Eric Laurente552edb2014-03-10 17:42:56 -0700229 // save a copy of the opened output descriptors before any output is opened or closed
230 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
231 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700232 switch (state)
233 {
234 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700235 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700237 ALOGW("setDeviceConnectionState() device already connected: %x", device);
238 return INVALID_OPERATION;
239 }
240 ALOGV("setDeviceConnectionState() connecting device %x", device);
241
Eric Laurente552edb2014-03-10 17:42:56 -0700242 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700243 index = mAvailableOutputDevices.add(devDesc);
244 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700245 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700246 if (module == 0) {
247 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
248 device);
249 mAvailableOutputDevices.remove(devDesc);
250 return INVALID_OPERATION;
251 }
252 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700253 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700254 } else {
255 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700256 }
257
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700258 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700259 mAvailableOutputDevices.remove(devDesc);
260 return INVALID_OPERATION;
261 }
262 // outputs should never be empty here
263 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
264 "checkOutputsForDevice() returned no outputs but status OK");
265 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
266 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700267 break;
268 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700269 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700270 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700271 ALOGW("setDeviceConnectionState() device not connected: %x", device);
272 return INVALID_OPERATION;
273 }
274
Paul McLean5c477aa2014-08-20 16:47:57 -0700275 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
276
277 // Set Disconnect to HALs
278 AudioParameter param = AudioParameter(address);
279 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
280 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
281
Eric Laurente552edb2014-03-10 17:42:56 -0700282 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700283 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700284
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700285 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700286 } break;
287
288 default:
289 ALOGE("setDeviceConnectionState() invalid state: %x", state);
290 return BAD_VALUE;
291 }
292
Eric Laurent3a4311c2014-03-17 12:00:47 -0700293 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
294 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700295 checkA2dpSuspend();
296 checkOutputForAllStrategies();
297 // outputs must be closed after checkOutputForAllStrategies() is executed
298 if (!outputs.isEmpty()) {
299 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700300 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700301 // close unused outputs after device disconnection or direct outputs that have been
302 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700304 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
305 (desc->mDirectOpenCount == 0))) {
306 closeOutput(outputs[i]);
307 }
308 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700309 // check again after closing A2DP output to reset mA2dpSuspended if needed
310 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
312
313 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700314 if (mPhoneState == AUDIO_MODE_IN_CALL) {
315 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
316 updateCallRouting(newDevice);
317 }
Eric Laurente552edb2014-03-10 17:42:56 -0700318 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700319 audio_io_handle_t output = mOutputs.keyAt(i);
320 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
321 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
322 true /*fromCache*/);
323 // do not force device change on duplicated output because if device is 0, it will
324 // also force a device 0 for the two outputs it is duplicated to which may override
325 // a valid device selection on those outputs.
326 bool force = !mOutputs.valueAt(i)->isDuplicated()
327 && (!deviceDistinguishesOnAddress(device)
328 // always force when disconnecting (a non-duplicated device)
329 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
330 setOutputDevice(output, newDevice, force, 0);
331 }
Eric Laurente552edb2014-03-10 17:42:56 -0700332 }
333
Eric Laurent72aa32f2014-05-30 18:51:48 -0700334 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700335 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700336 } // end if is output device
337
Eric Laurente552edb2014-03-10 17:42:56 -0700338 // handle input devices
339 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700340 SortedVector <audio_io_handle_t> inputs;
341
Eric Laurent1afeecb2014-05-14 08:52:28 -0700342 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
343 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700344 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700345 switch (state)
346 {
347 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700348 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700350 ALOGW("setDeviceConnectionState() device already connected: %d", device);
351 return INVALID_OPERATION;
352 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700353 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700354 if (module == NULL) {
355 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
356 device);
357 return INVALID_OPERATION;
358 }
Eric Laurentd4692962014-05-05 18:13:44 -0700359 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
360 return INVALID_OPERATION;
361 }
362
Eric Laurent3a4311c2014-03-17 12:00:47 -0700363 index = mAvailableInputDevices.add(devDesc);
364 if (index >= 0) {
365 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700366 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 } else {
368 return NO_MEMORY;
369 }
Eric Laurentd4692962014-05-05 18:13:44 -0700370 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700371
372 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700373 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700374 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700375 ALOGW("setDeviceConnectionState() device not connected: %d", device);
376 return INVALID_OPERATION;
377 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700378
379 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
380
381 // Set Disconnect to HALs
382 AudioParameter param = AudioParameter(address);
383 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
384 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
385
Eric Laurentd4692962014-05-05 18:13:44 -0700386 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700387 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700388
Eric Laurentd4692962014-05-05 18:13:44 -0700389 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700390
391 default:
392 ALOGE("setDeviceConnectionState() invalid state: %x", state);
393 return BAD_VALUE;
394 }
395
Eric Laurentd4692962014-05-05 18:13:44 -0700396 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700397
Eric Laurentc2730ba2014-07-20 15:47:07 -0700398 if (mPhoneState == AUDIO_MODE_IN_CALL) {
399 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
400 updateCallRouting(newDevice);
401 }
402
Eric Laurentb52c1522014-05-20 11:27:36 -0700403 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700404 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700405 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700406
407 ALOGW("setDeviceConnectionState() invalid device: %x", device);
408 return BAD_VALUE;
409}
410
Eric Laurente0720872014-03-11 09:30:41 -0700411audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700412 const char *device_address)
413{
Eric Laurent3b73df72014-03-11 09:06:29 -0700414 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700415 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700416 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700417 ssize_t index;
418 DeviceVector *deviceVector;
419
Eric Laurente552edb2014-03-10 17:42:56 -0700420 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700421 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700422 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700423 deviceVector = &mAvailableInputDevices;
424 } else {
425 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
426 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700427 }
428
Eric Laurent3a4311c2014-03-17 12:00:47 -0700429 index = deviceVector->indexOf(devDesc);
430 if (index >= 0) {
431 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
432 } else {
433 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
434 }
Eric Laurente552edb2014-03-10 17:42:56 -0700435}
436
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
438{
439 bool createTxPatch = false;
440 struct audio_patch patch;
441 patch.num_sources = 1;
442 patch.num_sinks = 1;
443 status_t status;
444 audio_patch_handle_t afPatchHandle;
445 DeviceVector deviceList;
446
447 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
448 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
449
450 // release existing RX patch if any
451 if (mCallRxPatch != 0) {
452 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
453 mCallRxPatch.clear();
454 }
455 // release TX patch if any
456 if (mCallTxPatch != 0) {
457 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
458 mCallTxPatch.clear();
459 }
460
461 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
462 // via setOutputDevice() on primary output.
463 // Otherwise, create two audio patches for TX and RX path.
464 if (availablePrimaryOutputDevices() & rxDevice) {
465 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
466 // If the TX device is also on the primary HW module, setOutputDevice() will take care
467 // of it due to legacy implementation. If not, create a patch.
468 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
469 == AUDIO_DEVICE_NONE) {
470 createTxPatch = true;
471 }
472 } else {
473 // create RX path audio patch
474 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
475 ALOG_ASSERT(!deviceList.isEmpty(),
476 "updateCallRouting() selected device not in output device list");
477 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
478 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
479 ALOG_ASSERT(!deviceList.isEmpty(),
480 "updateCallRouting() no telephony RX device");
481 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
482
483 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
484 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
485
486 // request to reuse existing output stream if one is already opened to reach the RX device
487 SortedVector<audio_io_handle_t> outputs =
488 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700489 audio_io_handle_t output = selectOutput(outputs,
490 AUDIO_OUTPUT_FLAG_NONE,
491 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700492 if (output != AUDIO_IO_HANDLE_NONE) {
493 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
494 ALOG_ASSERT(!outputDesc->isDuplicated(),
495 "updateCallRouting() RX device output is duplicated");
496 outputDesc->toAudioPortConfig(&patch.sources[1]);
497 patch.num_sources = 2;
498 }
499
500 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
501 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
502 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
503 status);
504 if (status == NO_ERROR) {
505 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
506 &patch, mUidCached);
507 mCallRxPatch->mAfPatchHandle = afPatchHandle;
508 mCallRxPatch->mUid = mUidCached;
509 }
510 createTxPatch = true;
511 }
512 if (createTxPatch) {
513
514 struct audio_patch patch;
515 patch.num_sources = 1;
516 patch.num_sinks = 1;
517 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
518 ALOG_ASSERT(!deviceList.isEmpty(),
519 "updateCallRouting() selected device not in input device list");
520 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
521 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
522 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
523 ALOG_ASSERT(!deviceList.isEmpty(),
524 "updateCallRouting() no telephony TX device");
525 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
526 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
527
528 SortedVector<audio_io_handle_t> outputs =
529 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700530 audio_io_handle_t output = selectOutput(outputs,
531 AUDIO_OUTPUT_FLAG_NONE,
532 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700533 // request to reuse existing output stream if one is already opened to reach the TX
534 // path output device
535 if (output != AUDIO_IO_HANDLE_NONE) {
536 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
537 ALOG_ASSERT(!outputDesc->isDuplicated(),
538 "updateCallRouting() RX device output is duplicated");
539 outputDesc->toAudioPortConfig(&patch.sources[1]);
540 patch.num_sources = 2;
541 }
542
543 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
544 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
545 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
546 status);
547 if (status == NO_ERROR) {
548 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
549 &patch, mUidCached);
550 mCallTxPatch->mAfPatchHandle = afPatchHandle;
551 mCallTxPatch->mUid = mUidCached;
552 }
553 }
554}
555
Eric Laurente0720872014-03-11 09:30:41 -0700556void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700557{
558 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700559 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700560 ALOGW("setPhoneState() invalid state %d", state);
561 return;
562 }
563
564 if (state == mPhoneState ) {
565 ALOGW("setPhoneState() setting same state %d", state);
566 return;
567 }
568
569 // if leaving call state, handle special case of active streams
570 // pertaining to sonification strategy see handleIncallSonification()
571 if (isInCall()) {
572 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700573 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
574 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700575 }
576 }
577
578 // store previous phone state for management of sonification strategy below
579 int oldState = mPhoneState;
580 mPhoneState = state;
581 bool force = false;
582
583 // are we entering or starting a call
584 if (!isStateInCall(oldState) && isStateInCall(state)) {
585 ALOGV(" Entering call in setPhoneState()");
586 // force routing command to audio hardware when starting a call
587 // even if no device change is needed
588 force = true;
589 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
590 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
591 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
592 }
593 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
594 ALOGV(" Exiting call in setPhoneState()");
595 // force routing command to audio hardware when exiting a call
596 // even if no device change is needed
597 force = true;
598 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
599 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
600 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
601 }
602 } else if (isStateInCall(state) && (state != oldState)) {
603 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
604 // force routing command to audio hardware when switching between telephony and VoIP
605 // even if no device change is needed
606 force = true;
607 }
608
609 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700610 checkA2dpSuspend();
611 checkOutputForAllStrategies();
612 updateDevicesAndOutputs();
613
Eric Laurent1f2f2232014-06-02 12:01:23 -0700614 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700615
Eric Laurente552edb2014-03-10 17:42:56 -0700616 int delayMs = 0;
617 if (isStateInCall(state)) {
618 nsecs_t sysTime = systemTime();
619 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700620 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700621 // mute media and sonification strategies and delay device switch by the largest
622 // latency of any output where either strategy is active.
623 // This avoid sending the ring tone or music tail into the earpiece or headset.
624 if ((desc->isStrategyActive(STRATEGY_MEDIA,
625 SONIFICATION_HEADSET_MUSIC_DELAY,
626 sysTime) ||
627 desc->isStrategyActive(STRATEGY_SONIFICATION,
628 SONIFICATION_HEADSET_MUSIC_DELAY,
629 sysTime)) &&
630 (delayMs < (int)desc->mLatency*2)) {
631 delayMs = desc->mLatency*2;
632 }
633 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
634 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
635 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
636 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
637 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
638 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
639 }
640 }
641
Eric Laurentc2730ba2014-07-20 15:47:07 -0700642 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
643 // the device returned is not necessarily reachable via this output
644 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
645 // force routing command to audio hardware when ending call
646 // even if no device change is needed
647 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
648 rxDevice = hwOutputDesc->device();
649 }
Eric Laurente552edb2014-03-10 17:42:56 -0700650
Eric Laurentc2730ba2014-07-20 15:47:07 -0700651 if (state == AUDIO_MODE_IN_CALL) {
652 updateCallRouting(rxDevice, delayMs);
653 } else if (oldState == AUDIO_MODE_IN_CALL) {
654 if (mCallRxPatch != 0) {
655 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
656 mCallRxPatch.clear();
657 }
658 if (mCallTxPatch != 0) {
659 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
660 mCallTxPatch.clear();
661 }
662 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
663 } else {
664 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
665 }
Eric Laurente552edb2014-03-10 17:42:56 -0700666 // if entering in call state, handle special case of active streams
667 // pertaining to sonification strategy see handleIncallSonification()
668 if (isStateInCall(state)) {
669 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700670 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
671 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700672 }
673 }
674
675 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700676 if (state == AUDIO_MODE_RINGTONE &&
677 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700678 mLimitRingtoneVolume = true;
679 } else {
680 mLimitRingtoneVolume = false;
681 }
682}
683
Eric Laurente0720872014-03-11 09:30:41 -0700684void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700685 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700686{
687 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
688
689 bool forceVolumeReeval = false;
690 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700691 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
692 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
693 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700694 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
695 return;
696 }
697 forceVolumeReeval = true;
698 mForceUse[usage] = config;
699 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700700 case AUDIO_POLICY_FORCE_FOR_MEDIA:
701 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
702 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
703 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
704 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900705 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700706 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
707 return;
708 }
709 mForceUse[usage] = config;
710 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700711 case AUDIO_POLICY_FORCE_FOR_RECORD:
712 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
713 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700714 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
715 return;
716 }
717 mForceUse[usage] = config;
718 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700719 case AUDIO_POLICY_FORCE_FOR_DOCK:
720 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
721 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
722 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
723 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
724 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700725 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
726 }
727 forceVolumeReeval = true;
728 mForceUse[usage] = config;
729 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700730 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
731 if (config != AUDIO_POLICY_FORCE_NONE &&
732 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700733 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
734 }
735 forceVolumeReeval = true;
736 mForceUse[usage] = config;
737 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900738 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
739 if (config != AUDIO_POLICY_FORCE_NONE &&
740 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
741 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
742 }
743 mForceUse[usage] = config;
744 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700745 default:
746 ALOGW("setForceUse() invalid usage %d", usage);
747 break;
748 }
749
750 // check for device and output changes triggered by new force usage
751 checkA2dpSuspend();
752 checkOutputForAllStrategies();
753 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700754 if (mPhoneState == AUDIO_MODE_IN_CALL) {
755 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
756 updateCallRouting(newDevice);
757 }
Eric Laurente552edb2014-03-10 17:42:56 -0700758 for (size_t i = 0; i < mOutputs.size(); i++) {
759 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700760 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700761 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
762 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
763 }
Eric Laurente552edb2014-03-10 17:42:56 -0700764 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
765 applyStreamVolumes(output, newDevice, 0, true);
766 }
767 }
768
769 audio_io_handle_t activeInput = getActiveInput();
770 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700771 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700772 }
773
774}
775
Eric Laurente0720872014-03-11 09:30:41 -0700776audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700777{
778 return mForceUse[usage];
779}
780
Eric Laurente0720872014-03-11 09:30:41 -0700781void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700782{
783 ALOGV("setSystemProperty() property %s, value %s", property, value);
784}
785
786// Find a direct output profile compatible with the parameters passed, even if the input flags do
787// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700788sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700789 audio_devices_t device,
790 uint32_t samplingRate,
791 audio_format_t format,
792 audio_channel_mask_t channelMask,
793 audio_output_flags_t flags)
794{
795 for (size_t i = 0; i < mHwModules.size(); i++) {
796 if (mHwModules[i]->mHandle == 0) {
797 continue;
798 }
799 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700800 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700801 bool found = profile->isCompatibleProfile(device, samplingRate,
802 NULL /*updatedSamplingRate*/, format, channelMask,
803 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
804 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700805 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
806 return profile;
807 }
Eric Laurente552edb2014-03-10 17:42:56 -0700808 }
809 }
810 return 0;
811}
812
Eric Laurente0720872014-03-11 09:30:41 -0700813audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700814 uint32_t samplingRate,
815 audio_format_t format,
816 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700817 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700818 const audio_offload_info_t *offloadInfo)
819{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700820
Eric Laurent3b73df72014-03-11 09:06:29 -0700821 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700822 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
823 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
824 device, stream, samplingRate, format, channelMask, flags);
825
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700826 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
827 offloadInfo);
828}
829
830audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
831 uint32_t samplingRate,
832 audio_format_t format,
833 audio_channel_mask_t channelMask,
834 audio_output_flags_t flags,
835 const audio_offload_info_t *offloadInfo)
836{
837 if (attr == NULL) {
838 ALOGE("getOutputForAttr() called with NULL audio attributes");
839 return 0;
840 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700841 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
842 attr->usage, attr->content_type, attr->tags, attr->flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700843
844 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
845 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
846 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700847
848 if ((attr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
849 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
850 }
851
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700852 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
853 device, samplingRate, format, channelMask, flags);
854
855 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
856 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
857 offloadInfo);
858}
859
860audio_io_handle_t AudioPolicyManager::getOutputForDevice(
861 audio_devices_t device,
862 audio_stream_type_t stream,
863 uint32_t samplingRate,
864 audio_format_t format,
865 audio_channel_mask_t channelMask,
866 audio_output_flags_t flags,
867 const audio_offload_info_t *offloadInfo)
868{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700869 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700870 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700871 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700872
Eric Laurente552edb2014-03-10 17:42:56 -0700873#ifdef AUDIO_POLICY_TEST
874 if (mCurOutput != 0) {
875 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
876 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
877
878 if (mTestOutputs[mCurOutput] == 0) {
879 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700880 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700881 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700882 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700883 outputDesc->mFlags =
884 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700885 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700886 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
887 config.sample_rate = mTestSamplingRate;
888 config.channel_mask = mTestChannels;
889 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700890 if (offloadInfo != NULL) {
891 config.offload_info = *offloadInfo;
892 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700893 status = mpClientInterface->openOutput(0,
894 &mTestOutputs[mCurOutput],
895 &config,
896 &outputDesc->mDevice,
897 String8(""),
898 &outputDesc->mLatency,
899 outputDesc->mFlags);
900 if (status == NO_ERROR) {
901 outputDesc->mSamplingRate = config.sample_rate;
902 outputDesc->mFormat = config.format;
903 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700904 AudioParameter outputCmd = AudioParameter();
905 outputCmd.addInt(String8("set_id"),mCurOutput);
906 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
907 addOutput(mTestOutputs[mCurOutput], outputDesc);
908 }
909 }
910 return mTestOutputs[mCurOutput];
911 }
912#endif //AUDIO_POLICY_TEST
913
914 // open a direct output if required by specified parameters
915 //force direct flag if offload flag is set: offloading implies a direct output stream
916 // and all common behaviors are driven by checking only the direct flag
917 // this should normally be set appropriately in the policy configuration file
918 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700919 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700920 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700921 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
922 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
923 }
Eric Laurente552edb2014-03-10 17:42:56 -0700924
925 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
926 // creating an offloaded track and tearing it down immediately after start when audioflinger
927 // detects there is an active non offloadable effect.
928 // FIXME: We should check the audio session here but we do not have it in this context.
929 // This may prevent offloading in rare situations where effects are left active by apps
930 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700931 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700932 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
933 !isNonOffloadableEffectEnabled()) {
934 profile = getProfileForDirectOutput(device,
935 samplingRate,
936 format,
937 channelMask,
938 (audio_output_flags_t)flags);
939 }
940
Eric Laurent1c333e22014-05-20 10:48:17 -0700941 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700942 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700943
944 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700945 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700946 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
947 outputDesc = desc;
948 // reuse direct output if currently open and configured with same parameters
949 if ((samplingRate == outputDesc->mSamplingRate) &&
950 (format == outputDesc->mFormat) &&
951 (channelMask == outputDesc->mChannelMask)) {
952 outputDesc->mDirectOpenCount++;
953 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
954 return mOutputs.keyAt(i);
955 }
956 }
957 }
958 // close direct output if currently open and configured with different parameters
959 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700960 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700961 }
962 outputDesc = new AudioOutputDescriptor(profile);
963 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700964 outputDesc->mLatency = 0;
965 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700966 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
967 config.sample_rate = samplingRate;
968 config.channel_mask = channelMask;
969 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700970 if (offloadInfo != NULL) {
971 config.offload_info = *offloadInfo;
972 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700973 status = mpClientInterface->openOutput(profile->mModule->mHandle,
974 &output,
975 &config,
976 &outputDesc->mDevice,
977 String8(""),
978 &outputDesc->mLatency,
979 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700980
981 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700982 if (status != NO_ERROR ||
983 (samplingRate != 0 && samplingRate != config.sample_rate) ||
984 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
985 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700986 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
987 "format %d %d, channelMask %04x %04x", output, samplingRate,
988 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
989 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700990 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700991 mpClientInterface->closeOutput(output);
992 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700993 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700994 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700995 outputDesc->mSamplingRate = config.sample_rate;
996 outputDesc->mChannelMask = config.channel_mask;
997 outputDesc->mFormat = config.format;
998 outputDesc->mRefCount[stream] = 0;
999 outputDesc->mStopTime[stream] = 0;
1000 outputDesc->mDirectOpenCount = 1;
1001
Eric Laurente552edb2014-03-10 17:42:56 -07001002 audio_io_handle_t srcOutput = getOutputForEffect();
1003 addOutput(output, outputDesc);
1004 audio_io_handle_t dstOutput = getOutputForEffect();
1005 if (dstOutput == output) {
1006 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1007 }
1008 mPreviousOutputs = mOutputs;
1009 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001010 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001011 return output;
1012 }
1013
1014 // ignoring channel mask due to downmix capability in mixer
1015
1016 // open a non direct output
1017
1018 // for non direct outputs, only PCM is supported
1019 if (audio_is_linear_pcm(format)) {
1020 // get which output is suitable for the specified stream. The actual
1021 // routing change will happen when startOutput() will be called
1022 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1023
Eric Laurent8838a382014-09-08 16:44:28 -07001024 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1025 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1026 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001027 }
1028 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1029 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1030
1031 ALOGV("getOutput() returns output %d", output);
1032
1033 return output;
1034}
1035
Eric Laurente0720872014-03-11 09:30:41 -07001036audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001037 audio_output_flags_t flags,
1038 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001039{
1040 // select one output among several that provide a path to a particular device or set of
1041 // devices (the list was previously build by getOutputsForDevice()).
1042 // The priority is as follows:
1043 // 1: the output with the highest number of requested policy flags
1044 // 2: the primary output
1045 // 3: the first output in the list
1046
1047 if (outputs.size() == 0) {
1048 return 0;
1049 }
1050 if (outputs.size() == 1) {
1051 return outputs[0];
1052 }
1053
1054 int maxCommonFlags = 0;
1055 audio_io_handle_t outputFlags = 0;
1056 audio_io_handle_t outputPrimary = 0;
1057
1058 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001059 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001060 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001061 // if a valid format is specified, skip output if not compatible
1062 if (format != AUDIO_FORMAT_INVALID) {
1063 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1064 if (format != outputDesc->mFormat) {
1065 continue;
1066 }
1067 } else if (!audio_is_linear_pcm(format)) {
1068 continue;
1069 }
1070 }
1071
Eric Laurent3b73df72014-03-11 09:06:29 -07001072 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001073 if (commonFlags > maxCommonFlags) {
1074 outputFlags = outputs[i];
1075 maxCommonFlags = commonFlags;
1076 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1077 }
1078 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1079 outputPrimary = outputs[i];
1080 }
1081 }
1082 }
1083
1084 if (outputFlags != 0) {
1085 return outputFlags;
1086 }
1087 if (outputPrimary != 0) {
1088 return outputPrimary;
1089 }
1090
1091 return outputs[0];
1092}
1093
Eric Laurente0720872014-03-11 09:30:41 -07001094status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001095 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001096 int session)
1097{
1098 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1099 ssize_t index = mOutputs.indexOfKey(output);
1100 if (index < 0) {
1101 ALOGW("startOutput() unknown output %d", output);
1102 return BAD_VALUE;
1103 }
1104
Eric Laurent1f2f2232014-06-02 12:01:23 -07001105 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001106
1107 // increment usage count for this stream on the requested output:
1108 // NOTE that the usage count is the same for duplicated output and hardware output which is
1109 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1110 outputDesc->changeRefCount(stream, 1);
1111
1112 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001113 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001114 routing_strategy strategy = getStrategy(stream);
1115 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1116 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1117 uint32_t waitMs = 0;
1118 bool force = false;
1119 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001120 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001121 if (desc != outputDesc) {
1122 // force a device change if any other output is managed by the same hw
1123 // module and has a current device selection that differs from selected device.
1124 // In this case, the audio HAL must receive the new device selection so that it can
1125 // change the device currently selected by the other active output.
1126 if (outputDesc->sharesHwModuleWith(desc) &&
1127 desc->device() != newDevice) {
1128 force = true;
1129 }
1130 // wait for audio on other active outputs to be presented when starting
1131 // a notification so that audio focus effect can propagate.
1132 uint32_t latency = desc->latency();
1133 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1134 waitMs = latency;
1135 }
1136 }
1137 }
1138 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1139
1140 // handle special case for sonification while in call
1141 if (isInCall()) {
1142 handleIncallSonification(stream, true, false);
1143 }
1144
1145 // apply volume rules for current stream and device if necessary
1146 checkAndSetVolume(stream,
1147 mStreams[stream].getVolumeIndex(newDevice),
1148 output,
1149 newDevice);
1150
1151 // update the outputs if starting an output with a stream that can affect notification
1152 // routing
1153 handleNotificationRoutingForStream(stream);
1154 if (waitMs > muteWaitMs) {
1155 usleep((waitMs - muteWaitMs) * 2 * 1000);
1156 }
1157 }
1158 return NO_ERROR;
1159}
1160
1161
Eric Laurente0720872014-03-11 09:30:41 -07001162status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001163 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001164 int session)
1165{
1166 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1167 ssize_t index = mOutputs.indexOfKey(output);
1168 if (index < 0) {
1169 ALOGW("stopOutput() unknown output %d", output);
1170 return BAD_VALUE;
1171 }
1172
Eric Laurent1f2f2232014-06-02 12:01:23 -07001173 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001174
1175 // handle special case for sonification while in call
1176 if (isInCall()) {
1177 handleIncallSonification(stream, false, false);
1178 }
1179
1180 if (outputDesc->mRefCount[stream] > 0) {
1181 // decrement usage count of this stream on the output
1182 outputDesc->changeRefCount(stream, -1);
1183 // store time at which the stream was stopped - see isStreamActive()
1184 if (outputDesc->mRefCount[stream] == 0) {
1185 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001186 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001187 // delay the device switch by twice the latency because stopOutput() is executed when
1188 // the track stop() command is received and at that time the audio track buffer can
1189 // still contain data that needs to be drained. The latency only covers the audio HAL
1190 // and kernel buffers. Also the latency does not always include additional delay in the
1191 // audio path (audio DSP, CODEC ...)
1192 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1193
1194 // force restoring the device selection on other active outputs if it differs from the
1195 // one being selected for this output
1196 for (size_t i = 0; i < mOutputs.size(); i++) {
1197 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001198 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001199 if (curOutput != output &&
1200 desc->isActive() &&
1201 outputDesc->sharesHwModuleWith(desc) &&
1202 (newDevice != desc->device())) {
1203 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001204 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001205 true,
1206 outputDesc->mLatency*2);
1207 }
1208 }
1209 // update the outputs if stopping one with a stream that can affect notification routing
1210 handleNotificationRoutingForStream(stream);
1211 }
1212 return NO_ERROR;
1213 } else {
1214 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1215 return INVALID_OPERATION;
1216 }
1217}
1218
Eric Laurente0720872014-03-11 09:30:41 -07001219void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001220{
1221 ALOGV("releaseOutput() %d", output);
1222 ssize_t index = mOutputs.indexOfKey(output);
1223 if (index < 0) {
1224 ALOGW("releaseOutput() releasing unknown output %d", output);
1225 return;
1226 }
1227
1228#ifdef AUDIO_POLICY_TEST
1229 int testIndex = testOutputIndex(output);
1230 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001231 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001232 if (outputDesc->isActive()) {
1233 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001234 mOutputs.removeItem(output);
1235 mTestOutputs[testIndex] = 0;
1236 }
1237 return;
1238 }
1239#endif //AUDIO_POLICY_TEST
1240
Eric Laurent1f2f2232014-06-02 12:01:23 -07001241 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001242 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001243 if (desc->mDirectOpenCount <= 0) {
1244 ALOGW("releaseOutput() invalid open count %d for output %d",
1245 desc->mDirectOpenCount, output);
1246 return;
1247 }
1248 if (--desc->mDirectOpenCount == 0) {
1249 closeOutput(output);
1250 // If effects where present on the output, audioflinger moved them to the primary
1251 // output by default: move them back to the appropriate output.
1252 audio_io_handle_t dstOutput = getOutputForEffect();
1253 if (dstOutput != mPrimaryOutput) {
1254 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1255 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001256 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001257 }
1258 }
1259}
1260
1261
Eric Laurente0720872014-03-11 09:30:41 -07001262audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001263 uint32_t samplingRate,
1264 audio_format_t format,
1265 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001266 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001267 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001268{
Eric Laurent4dc68062014-07-28 17:26:49 -07001269 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001270 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001271 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001272
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001273 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001274
1275 if (device == AUDIO_DEVICE_NONE) {
1276 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001277 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001278 }
1279
1280 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001281 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001282 case AUDIO_SOURCE_VOICE_UPLINK:
1283 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1284 break;
1285 case AUDIO_SOURCE_VOICE_DOWNLINK:
1286 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1287 break;
1288 case AUDIO_SOURCE_VOICE_CALL:
1289 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1290 break;
1291 default:
1292 break;
1293 }
1294
Eric Laurent1c333e22014-05-20 10:48:17 -07001295 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001296 samplingRate,
1297 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001298 channelMask,
1299 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001300 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001301 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1302 "channelMask 0x%X, flags %#x",
1303 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001304 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001305 }
1306
1307 if (profile->mModule->mHandle == 0) {
1308 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001309 return AUDIO_IO_HANDLE_NONE;
1310 }
1311
1312 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1313 config.sample_rate = samplingRate;
1314 config.channel_mask = channelMask;
1315 config.format = format;
1316 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001317
1318 bool isSoundTrigger = false;
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001319 audio_source_t halInputSource = inputSource;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001320 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1321 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1322 if (index >= 0) {
1323 input = mSoundTriggerSessions.valueFor(session);
1324 isSoundTrigger = true;
1325 ALOGV("SoundTrigger capture on session %d input %d", session, input);
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001326 } else {
1327 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001328 }
1329 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001330 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1331 &input,
1332 &config,
1333 &device,
1334 String8(""),
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001335 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001336 flags);
1337
1338 // only accept input with the exact requested set of parameters
1339 if (status != NO_ERROR ||
1340 (samplingRate != config.sample_rate) ||
1341 (format != config.format) ||
1342 (channelMask != config.channel_mask)) {
1343 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1344 samplingRate, format, channelMask);
1345 if (input != AUDIO_IO_HANDLE_NONE) {
1346 mpClientInterface->closeInput(input);
1347 }
1348 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001349 }
1350
Eric Laurent1f2f2232014-06-02 12:01:23 -07001351 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001352 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001353 inputDesc->mRefCount = 0;
1354 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001355 inputDesc->mSamplingRate = samplingRate;
1356 inputDesc->mFormat = format;
1357 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001358 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001359 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001360 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001361
Eric Laurentd4692962014-05-05 18:13:44 -07001362 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001363 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001364 return input;
1365}
1366
Eric Laurent4dc68062014-07-28 17:26:49 -07001367status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1368 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001369{
1370 ALOGV("startInput() input %d", input);
1371 ssize_t index = mInputs.indexOfKey(input);
1372 if (index < 0) {
1373 ALOGW("startInput() unknown input %d", input);
1374 return BAD_VALUE;
1375 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001376 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001377
Eric Laurent4dc68062014-07-28 17:26:49 -07001378 index = inputDesc->mSessions.indexOf(session);
1379 if (index < 0) {
1380 ALOGW("startInput() unknown session %d on input %d", session, input);
1381 return BAD_VALUE;
1382 }
1383
Glenn Kasten74a8e252014-07-24 14:09:55 -07001384 // virtual input devices are compatible with other input devices
1385 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1386
1387 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001388 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001389 if (activeInput != 0 && activeInput != input) {
1390
1391 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1392 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001393 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001394 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001395 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001396 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1397 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001398 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001399 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001400 return INVALID_OPERATION;
1401 }
1402 }
1403 }
1404
Glenn Kasten74a8e252014-07-24 14:09:55 -07001405 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001406 if (activeInputsCount() == 0) {
1407 SoundTrigger::setCaptureState(true);
1408 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001409 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001410
Glenn Kasten74a8e252014-07-24 14:09:55 -07001411 // Automatically enable the remote submix output when input is started.
1412 // For remote submix (a virtual device), we open only one input per capture request.
1413 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1414 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1415 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1416 }
Eric Laurente552edb2014-03-10 17:42:56 -07001417 }
1418
Eric Laurente552edb2014-03-10 17:42:56 -07001419 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1420
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001421 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001422 return NO_ERROR;
1423}
1424
Eric Laurent4dc68062014-07-28 17:26:49 -07001425status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1426 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001427{
1428 ALOGV("stopInput() input %d", input);
1429 ssize_t index = mInputs.indexOfKey(input);
1430 if (index < 0) {
1431 ALOGW("stopInput() unknown input %d", input);
1432 return BAD_VALUE;
1433 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001434 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001435
Eric Laurent4dc68062014-07-28 17:26:49 -07001436 index = inputDesc->mSessions.indexOf(session);
1437 if (index < 0) {
1438 ALOGW("stopInput() unknown session %d on input %d", session, input);
1439 return BAD_VALUE;
1440 }
1441
Eric Laurente552edb2014-03-10 17:42:56 -07001442 if (inputDesc->mRefCount == 0) {
1443 ALOGW("stopInput() input %d already stopped", input);
1444 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001445 }
1446
1447 inputDesc->mRefCount--;
1448 if (inputDesc->mRefCount == 0) {
1449
Eric Laurente552edb2014-03-10 17:42:56 -07001450 // automatically disable the remote submix output when input is stopped
1451 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1452 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001453 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001454 }
1455
Eric Laurent1c333e22014-05-20 10:48:17 -07001456 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001457
1458 if (activeInputsCount() == 0) {
1459 SoundTrigger::setCaptureState(false);
1460 }
Eric Laurente552edb2014-03-10 17:42:56 -07001461 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001462 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001463}
1464
Eric Laurent4dc68062014-07-28 17:26:49 -07001465void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1466 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001467{
1468 ALOGV("releaseInput() %d", input);
1469 ssize_t index = mInputs.indexOfKey(input);
1470 if (index < 0) {
1471 ALOGW("releaseInput() releasing unknown input %d", input);
1472 return;
1473 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001474 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1475 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001476
1477 index = inputDesc->mSessions.indexOf(session);
1478 if (index < 0) {
1479 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1480 return;
1481 }
1482 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001483 if (inputDesc->mOpenRefCount == 0) {
1484 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1485 return;
1486 }
1487 inputDesc->mOpenRefCount--;
1488 if (inputDesc->mOpenRefCount > 0) {
1489 ALOGV("releaseInput() exit > 0");
1490 return;
1491 }
1492
Eric Laurent05b90f82014-08-27 15:32:29 -07001493 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001494 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001495 ALOGV("releaseInput() exit");
1496}
1497
Eric Laurentd4692962014-05-05 18:13:44 -07001498void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001499 bool patchRemoved = false;
1500
Eric Laurentd4692962014-05-05 18:13:44 -07001501 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001502 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1503 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1504 if (patch_index >= 0) {
1505 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1506 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1507 mAudioPatches.removeItemsAt(patch_index);
1508 patchRemoved = true;
1509 }
Eric Laurentd4692962014-05-05 18:13:44 -07001510 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1511 }
1512 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001513 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001514
1515 if (patchRemoved) {
1516 mpClientInterface->onAudioPatchListUpdate();
1517 }
Eric Laurentd4692962014-05-05 18:13:44 -07001518}
1519
Eric Laurente0720872014-03-11 09:30:41 -07001520void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001521 int indexMin,
1522 int indexMax)
1523{
1524 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1525 if (indexMin < 0 || indexMin >= indexMax) {
1526 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1527 return;
1528 }
1529 mStreams[stream].mIndexMin = indexMin;
1530 mStreams[stream].mIndexMax = indexMax;
1531}
1532
Eric Laurente0720872014-03-11 09:30:41 -07001533status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001534 int index,
1535 audio_devices_t device)
1536{
1537
1538 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1539 return BAD_VALUE;
1540 }
1541 if (!audio_is_output_device(device)) {
1542 return BAD_VALUE;
1543 }
1544
1545 // Force max volume if stream cannot be muted
1546 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1547
1548 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1549 stream, device, index);
1550
1551 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1552 // clear all device specific values
1553 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1554 mStreams[stream].mIndexCur.clear();
1555 }
1556 mStreams[stream].mIndexCur.add(device, index);
1557
1558 // compute and apply stream volume on all outputs according to connected device
1559 status_t status = NO_ERROR;
1560 for (size_t i = 0; i < mOutputs.size(); i++) {
1561 audio_devices_t curDevice =
1562 getDeviceForVolume(mOutputs.valueAt(i)->device());
1563 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1564 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1565 if (volStatus != NO_ERROR) {
1566 status = volStatus;
1567 }
1568 }
1569 }
1570 return status;
1571}
1572
Eric Laurente0720872014-03-11 09:30:41 -07001573status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001574 int *index,
1575 audio_devices_t device)
1576{
1577 if (index == NULL) {
1578 return BAD_VALUE;
1579 }
1580 if (!audio_is_output_device(device)) {
1581 return BAD_VALUE;
1582 }
1583 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1584 // the strategy the stream belongs to.
1585 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1586 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1587 }
1588 device = getDeviceForVolume(device);
1589
1590 *index = mStreams[stream].getVolumeIndex(device);
1591 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1592 return NO_ERROR;
1593}
1594
Eric Laurente0720872014-03-11 09:30:41 -07001595audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001596 const SortedVector<audio_io_handle_t>& outputs)
1597{
1598 // select one output among several suitable for global effects.
1599 // The priority is as follows:
1600 // 1: An offloaded output. If the effect ends up not being offloadable,
1601 // AudioFlinger will invalidate the track and the offloaded output
1602 // will be closed causing the effect to be moved to a PCM output.
1603 // 2: A deep buffer output
1604 // 3: the first output in the list
1605
1606 if (outputs.size() == 0) {
1607 return 0;
1608 }
1609
1610 audio_io_handle_t outputOffloaded = 0;
1611 audio_io_handle_t outputDeepBuffer = 0;
1612
1613 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001614 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001615 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001616 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1617 outputOffloaded = outputs[i];
1618 }
1619 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1620 outputDeepBuffer = outputs[i];
1621 }
1622 }
1623
1624 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1625 outputOffloaded, outputDeepBuffer);
1626 if (outputOffloaded != 0) {
1627 return outputOffloaded;
1628 }
1629 if (outputDeepBuffer != 0) {
1630 return outputDeepBuffer;
1631 }
1632
1633 return outputs[0];
1634}
1635
Eric Laurente0720872014-03-11 09:30:41 -07001636audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001637{
1638 // apply simple rule where global effects are attached to the same output as MUSIC streams
1639
Eric Laurent3b73df72014-03-11 09:06:29 -07001640 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001641 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1642 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1643
1644 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1645 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1646 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1647
1648 return output;
1649}
1650
Eric Laurente0720872014-03-11 09:30:41 -07001651status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001652 audio_io_handle_t io,
1653 uint32_t strategy,
1654 int session,
1655 int id)
1656{
1657 ssize_t index = mOutputs.indexOfKey(io);
1658 if (index < 0) {
1659 index = mInputs.indexOfKey(io);
1660 if (index < 0) {
1661 ALOGW("registerEffect() unknown io %d", io);
1662 return INVALID_OPERATION;
1663 }
1664 }
1665
1666 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1667 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1668 desc->name, desc->memoryUsage);
1669 return INVALID_OPERATION;
1670 }
1671 mTotalEffectsMemory += desc->memoryUsage;
1672 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1673 desc->name, io, strategy, session, id);
1674 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1675
Eric Laurent1f2f2232014-06-02 12:01:23 -07001676 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1677 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1678 effectDesc->mIo = io;
1679 effectDesc->mStrategy = (routing_strategy)strategy;
1680 effectDesc->mSession = session;
1681 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001682
Eric Laurent1f2f2232014-06-02 12:01:23 -07001683 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001684
1685 return NO_ERROR;
1686}
1687
Eric Laurente0720872014-03-11 09:30:41 -07001688status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001689{
1690 ssize_t index = mEffects.indexOfKey(id);
1691 if (index < 0) {
1692 ALOGW("unregisterEffect() unknown effect ID %d", id);
1693 return INVALID_OPERATION;
1694 }
1695
Eric Laurent1f2f2232014-06-02 12:01:23 -07001696 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001697
Eric Laurent1f2f2232014-06-02 12:01:23 -07001698 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001699
Eric Laurent1f2f2232014-06-02 12:01:23 -07001700 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001701 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001702 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1703 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001704 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001705 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001706 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001707 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001708
1709 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001710
1711 return NO_ERROR;
1712}
1713
Eric Laurente0720872014-03-11 09:30:41 -07001714status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001715{
1716 ssize_t index = mEffects.indexOfKey(id);
1717 if (index < 0) {
1718 ALOGW("unregisterEffect() unknown effect ID %d", id);
1719 return INVALID_OPERATION;
1720 }
1721
1722 return setEffectEnabled(mEffects.valueAt(index), enabled);
1723}
1724
Eric Laurent1f2f2232014-06-02 12:01:23 -07001725status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001726{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001727 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001728 ALOGV("setEffectEnabled(%s) effect already %s",
1729 enabled?"true":"false", enabled?"enabled":"disabled");
1730 return INVALID_OPERATION;
1731 }
1732
1733 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001734 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001735 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001736 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001737 return INVALID_OPERATION;
1738 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001739 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001740 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1741 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001742 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001743 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001744 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1745 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001746 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001747 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001748 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1749 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001750 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001751 return NO_ERROR;
1752}
1753
Eric Laurente0720872014-03-11 09:30:41 -07001754bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001755{
1756 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001757 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1758 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1759 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001760 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001761 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001762 return true;
1763 }
1764 }
1765 return false;
1766}
1767
Eric Laurente0720872014-03-11 09:30:41 -07001768bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001769{
1770 nsecs_t sysTime = systemTime();
1771 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001772 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001773 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001774 return true;
1775 }
1776 }
1777 return false;
1778}
1779
Eric Laurente0720872014-03-11 09:30:41 -07001780bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001781 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001782{
1783 nsecs_t sysTime = systemTime();
1784 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001785 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001786 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001787 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001788 return true;
1789 }
1790 }
1791 return false;
1792}
1793
Eric Laurente0720872014-03-11 09:30:41 -07001794bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001795{
1796 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001797 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001798 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001799 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001800 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1801 && (inputDescriptor->mRefCount > 0)) {
1802 return true;
1803 }
1804 }
1805 return false;
1806}
1807
1808
Eric Laurente0720872014-03-11 09:30:41 -07001809status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001810{
1811 const size_t SIZE = 256;
1812 char buffer[SIZE];
1813 String8 result;
1814
1815 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1816 result.append(buffer);
1817
1818 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1819 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001820 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1821 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001822 snprintf(buffer, SIZE, " Force use for communications %d\n",
1823 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001824 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001825 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001826 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001827 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001828 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001829 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001830 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001831 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001832 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001833 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1834 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1835 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001836
Eric Laurent3a4311c2014-03-17 12:00:47 -07001837 snprintf(buffer, SIZE, " Available output devices:\n");
1838 result.append(buffer);
1839 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001840 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001841 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001842 }
1843 snprintf(buffer, SIZE, "\n Available input devices:\n");
1844 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001845 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001846 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001847 }
Eric Laurente552edb2014-03-10 17:42:56 -07001848
1849 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1850 write(fd, buffer, strlen(buffer));
1851 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001852 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001853 write(fd, buffer, strlen(buffer));
1854 mHwModules[i]->dump(fd);
1855 }
1856
1857 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1858 write(fd, buffer, strlen(buffer));
1859 for (size_t i = 0; i < mOutputs.size(); i++) {
1860 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1861 write(fd, buffer, strlen(buffer));
1862 mOutputs.valueAt(i)->dump(fd);
1863 }
1864
1865 snprintf(buffer, SIZE, "\nInputs dump:\n");
1866 write(fd, buffer, strlen(buffer));
1867 for (size_t i = 0; i < mInputs.size(); i++) {
1868 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1869 write(fd, buffer, strlen(buffer));
1870 mInputs.valueAt(i)->dump(fd);
1871 }
1872
1873 snprintf(buffer, SIZE, "\nStreams dump:\n");
1874 write(fd, buffer, strlen(buffer));
1875 snprintf(buffer, SIZE,
1876 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1877 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001878 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001879 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001880 write(fd, buffer, strlen(buffer));
1881 mStreams[i].dump(fd);
1882 }
1883
1884 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1885 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1886 write(fd, buffer, strlen(buffer));
1887
1888 snprintf(buffer, SIZE, "Registered effects:\n");
1889 write(fd, buffer, strlen(buffer));
1890 for (size_t i = 0; i < mEffects.size(); i++) {
1891 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1892 write(fd, buffer, strlen(buffer));
1893 mEffects.valueAt(i)->dump(fd);
1894 }
1895
Eric Laurent4d416952014-08-10 14:07:09 -07001896 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1897 write(fd, buffer, strlen(buffer));
1898 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1899 mAudioPatches[i]->dump(fd, 2, i);
1900 }
Eric Laurente552edb2014-03-10 17:42:56 -07001901
1902 return NO_ERROR;
1903}
1904
1905// This function checks for the parameters which can be offloaded.
1906// This can be enhanced depending on the capability of the DSP and policy
1907// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001908bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001909{
1910 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001911 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001912 offloadInfo.sample_rate, offloadInfo.channel_mask,
1913 offloadInfo.format,
1914 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1915 offloadInfo.has_video);
1916
1917 // Check if offload has been disabled
1918 char propValue[PROPERTY_VALUE_MAX];
1919 if (property_get("audio.offload.disable", propValue, "0")) {
1920 if (atoi(propValue) != 0) {
1921 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1922 return false;
1923 }
1924 }
1925
1926 // Check if stream type is music, then only allow offload as of now.
1927 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1928 {
1929 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1930 return false;
1931 }
1932
1933 //TODO: enable audio offloading with video when ready
1934 if (offloadInfo.has_video)
1935 {
1936 ALOGV("isOffloadSupported: has_video == true, returning false");
1937 return false;
1938 }
1939
1940 //If duration is less than minimum value defined in property, return false
1941 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1942 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1943 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1944 return false;
1945 }
1946 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1947 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1948 return false;
1949 }
1950
1951 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1952 // creating an offloaded track and tearing it down immediately after start when audioflinger
1953 // detects there is an active non offloadable effect.
1954 // FIXME: We should check the audio session here but we do not have it in this context.
1955 // This may prevent offloading in rare situations where effects are left active by apps
1956 // in the background.
1957 if (isNonOffloadableEffectEnabled()) {
1958 return false;
1959 }
1960
1961 // See if there is a profile to support this.
1962 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001963 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001964 offloadInfo.sample_rate,
1965 offloadInfo.format,
1966 offloadInfo.channel_mask,
1967 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001968 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1969 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001970}
1971
Eric Laurent6a94d692014-05-20 11:18:06 -07001972status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1973 audio_port_type_t type,
1974 unsigned int *num_ports,
1975 struct audio_port *ports,
1976 unsigned int *generation)
1977{
1978 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1979 generation == NULL) {
1980 return BAD_VALUE;
1981 }
1982 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1983 if (ports == NULL) {
1984 *num_ports = 0;
1985 }
1986
1987 size_t portsWritten = 0;
1988 size_t portsMax = *num_ports;
1989 *num_ports = 0;
1990 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1991 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1992 for (size_t i = 0;
1993 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1994 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1995 }
1996 *num_ports += mAvailableOutputDevices.size();
1997 }
1998 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1999 for (size_t i = 0;
2000 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2001 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2002 }
2003 *num_ports += mAvailableInputDevices.size();
2004 }
2005 }
2006 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2007 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2008 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2009 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2010 }
2011 *num_ports += mInputs.size();
2012 }
2013 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002014 size_t numOutputs = 0;
2015 for (size_t i = 0; i < mOutputs.size(); i++) {
2016 if (!mOutputs[i]->isDuplicated()) {
2017 numOutputs++;
2018 if (portsWritten < portsMax) {
2019 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2020 }
2021 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002022 }
Eric Laurent84c70242014-06-23 08:46:27 -07002023 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002024 }
2025 }
2026 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002027 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002028 return NO_ERROR;
2029}
2030
2031status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2032{
2033 return NO_ERROR;
2034}
2035
Eric Laurent1f2f2232014-06-02 12:01:23 -07002036sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002037 audio_port_handle_t id) const
2038{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002039 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002040 for (size_t i = 0; i < mOutputs.size(); i++) {
2041 outputDesc = mOutputs.valueAt(i);
2042 if (outputDesc->mId == id) {
2043 break;
2044 }
2045 }
2046 return outputDesc;
2047}
2048
Eric Laurent1f2f2232014-06-02 12:01:23 -07002049sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002050 audio_port_handle_t id) const
2051{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002052 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002053 for (size_t i = 0; i < mInputs.size(); i++) {
2054 inputDesc = mInputs.valueAt(i);
2055 if (inputDesc->mId == id) {
2056 break;
2057 }
2058 }
2059 return inputDesc;
2060}
2061
Eric Laurent1f2f2232014-06-02 12:01:23 -07002062sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2063 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002064{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002065 sp <HwModule> module;
2066
Eric Laurent6a94d692014-05-20 11:18:06 -07002067 for (size_t i = 0; i < mHwModules.size(); i++) {
2068 if (mHwModules[i]->mHandle == 0) {
2069 continue;
2070 }
2071 if (audio_is_output_device(device)) {
2072 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2073 {
2074 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2075 return mHwModules[i];
2076 }
2077 }
2078 } else {
2079 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2080 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2081 device & ~AUDIO_DEVICE_BIT_IN) {
2082 return mHwModules[i];
2083 }
2084 }
2085 }
2086 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002087 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002088}
2089
Eric Laurent1f2f2232014-06-02 12:01:23 -07002090sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002091{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002092 sp <HwModule> module;
2093
Eric Laurent1afeecb2014-05-14 08:52:28 -07002094 for (size_t i = 0; i < mHwModules.size(); i++)
2095 {
2096 if (strcmp(mHwModules[i]->mName, name) == 0) {
2097 return mHwModules[i];
2098 }
2099 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002100 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002101}
2102
Eric Laurentc2730ba2014-07-20 15:47:07 -07002103audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2104{
2105 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2106 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2107 return devices & mAvailableOutputDevices.types();
2108}
2109
2110audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2111{
2112 audio_module_handle_t primaryHandle =
2113 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2114 audio_devices_t devices = AUDIO_DEVICE_NONE;
2115 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2116 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2117 devices |= mAvailableInputDevices[i]->mDeviceType;
2118 }
2119 }
2120 return devices;
2121}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002122
Eric Laurent6a94d692014-05-20 11:18:06 -07002123status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2124 audio_patch_handle_t *handle,
2125 uid_t uid)
2126{
2127 ALOGV("createAudioPatch()");
2128
2129 if (handle == NULL || patch == NULL) {
2130 return BAD_VALUE;
2131 }
2132 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2133
Eric Laurent874c42872014-08-08 15:13:39 -07002134 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2135 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2136 return BAD_VALUE;
2137 }
2138 // only one source per audio patch supported for now
2139 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002140 return INVALID_OPERATION;
2141 }
Eric Laurent874c42872014-08-08 15:13:39 -07002142
2143 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002144 return INVALID_OPERATION;
2145 }
Eric Laurent874c42872014-08-08 15:13:39 -07002146 for (size_t i = 0; i < patch->num_sinks; i++) {
2147 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2148 return INVALID_OPERATION;
2149 }
2150 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002151
2152 sp<AudioPatch> patchDesc;
2153 ssize_t index = mAudioPatches.indexOfKey(*handle);
2154
Eric Laurent6a94d692014-05-20 11:18:06 -07002155 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2156 patch->sources[0].role,
2157 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002158#if LOG_NDEBUG == 0
2159 for (size_t i = 0; i < patch->num_sinks; i++) {
2160 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2161 patch->sinks[i].role,
2162 patch->sinks[i].type);
2163 }
2164#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002165
2166 if (index >= 0) {
2167 patchDesc = mAudioPatches.valueAt(index);
2168 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2169 mUidCached, patchDesc->mUid, uid);
2170 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2171 return INVALID_OPERATION;
2172 }
2173 } else {
2174 *handle = 0;
2175 }
2176
2177 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002178 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002179 if (outputDesc == NULL) {
2180 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2181 return BAD_VALUE;
2182 }
Eric Laurent84c70242014-06-23 08:46:27 -07002183 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2184 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002185 if (patchDesc != 0) {
2186 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2187 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2188 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2189 return BAD_VALUE;
2190 }
2191 }
Eric Laurent874c42872014-08-08 15:13:39 -07002192 DeviceVector devices;
2193 for (size_t i = 0; i < patch->num_sinks; i++) {
2194 // Only support mix to devices connection
2195 // TODO add support for mix to mix connection
2196 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2197 ALOGV("createAudioPatch() source mix but sink is not a device");
2198 return INVALID_OPERATION;
2199 }
2200 sp<DeviceDescriptor> devDesc =
2201 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2202 if (devDesc == 0) {
2203 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2204 return BAD_VALUE;
2205 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002206
Eric Laurent874c42872014-08-08 15:13:39 -07002207 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2208 patch->sources[0].sample_rate,
2209 NULL, // updatedSamplingRate
2210 patch->sources[0].format,
2211 patch->sources[0].channel_mask,
2212 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2213 ALOGV("createAudioPatch() profile not supported for device %08x",
2214 devDesc->mDeviceType);
2215 return INVALID_OPERATION;
2216 }
2217 devices.add(devDesc);
2218 }
2219 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002220 return INVALID_OPERATION;
2221 }
Eric Laurent874c42872014-08-08 15:13:39 -07002222
Eric Laurent6a94d692014-05-20 11:18:06 -07002223 // TODO: reconfigure output format and channels here
2224 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002225 devices.types(), outputDesc->mIoHandle);
2226 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002227 index = mAudioPatches.indexOfKey(*handle);
2228 if (index >= 0) {
2229 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2230 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2231 }
2232 patchDesc = mAudioPatches.valueAt(index);
2233 patchDesc->mUid = uid;
2234 ALOGV("createAudioPatch() success");
2235 } else {
2236 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2237 return INVALID_OPERATION;
2238 }
2239 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2240 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2241 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002242 // only one sink supported when connecting an input device to a mix
2243 if (patch->num_sinks > 1) {
2244 return INVALID_OPERATION;
2245 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002246 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002247 if (inputDesc == NULL) {
2248 return BAD_VALUE;
2249 }
2250 if (patchDesc != 0) {
2251 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2252 return BAD_VALUE;
2253 }
2254 }
2255 sp<DeviceDescriptor> devDesc =
2256 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2257 if (devDesc == 0) {
2258 return BAD_VALUE;
2259 }
2260
Eric Laurent84c70242014-06-23 08:46:27 -07002261 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002262 patch->sinks[0].sample_rate,
2263 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002264 patch->sinks[0].format,
2265 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002266 // FIXME for the parameter type,
2267 // and the NONE
2268 (audio_output_flags_t)
2269 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002270 return INVALID_OPERATION;
2271 }
2272 // TODO: reconfigure output format and channels here
2273 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002274 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002275 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002276 index = mAudioPatches.indexOfKey(*handle);
2277 if (index >= 0) {
2278 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2279 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2280 }
2281 patchDesc = mAudioPatches.valueAt(index);
2282 patchDesc->mUid = uid;
2283 ALOGV("createAudioPatch() success");
2284 } else {
2285 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2286 return INVALID_OPERATION;
2287 }
2288 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2289 // device to device connection
2290 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002291 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002292 return BAD_VALUE;
2293 }
2294 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002295 sp<DeviceDescriptor> srcDeviceDesc =
2296 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent874c42872014-08-08 15:13:39 -07002297
Eric Laurent6a94d692014-05-20 11:18:06 -07002298 //update source and sink with our own data as the data passed in the patch may
2299 // be incomplete.
2300 struct audio_patch newPatch = *patch;
2301 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent874c42872014-08-08 15:13:39 -07002302 if (srcDeviceDesc == 0) {
2303 return BAD_VALUE;
2304 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002305
Eric Laurent874c42872014-08-08 15:13:39 -07002306 for (size_t i = 0; i < patch->num_sinks; i++) {
2307 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2308 ALOGV("createAudioPatch() source device but one sink is not a device");
2309 return INVALID_OPERATION;
2310 }
2311
2312 sp<DeviceDescriptor> sinkDeviceDesc =
2313 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2314 if (sinkDeviceDesc == 0) {
2315 return BAD_VALUE;
2316 }
2317 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2318
2319 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2320 // only one sink supported when connected devices across HW modules
2321 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002322 return INVALID_OPERATION;
2323 }
Eric Laurent874c42872014-08-08 15:13:39 -07002324 SortedVector<audio_io_handle_t> outputs =
2325 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2326 mOutputs);
2327 // if the sink device is reachable via an opened output stream, request to go via
2328 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002329 audio_io_handle_t output = selectOutput(outputs,
2330 AUDIO_OUTPUT_FLAG_NONE,
2331 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002332 if (output != AUDIO_IO_HANDLE_NONE) {
2333 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2334 if (outputDesc->isDuplicated()) {
2335 return INVALID_OPERATION;
2336 }
2337 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2338 newPatch.num_sources = 2;
2339 }
Eric Laurent83b88082014-06-20 18:31:16 -07002340 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002341 }
2342 // TODO: check from routing capabilities in config file and other conflicting patches
2343
2344 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2345 if (index >= 0) {
2346 afPatchHandle = patchDesc->mAfPatchHandle;
2347 }
2348
2349 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2350 &afPatchHandle,
2351 0);
2352 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2353 status, afPatchHandle);
2354 if (status == NO_ERROR) {
2355 if (index < 0) {
2356 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2357 &newPatch, uid);
2358 addAudioPatch(patchDesc->mHandle, patchDesc);
2359 } else {
2360 patchDesc->mPatch = newPatch;
2361 }
2362 patchDesc->mAfPatchHandle = afPatchHandle;
2363 *handle = patchDesc->mHandle;
2364 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002365 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002366 } else {
2367 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2368 status);
2369 return INVALID_OPERATION;
2370 }
2371 } else {
2372 return BAD_VALUE;
2373 }
2374 } else {
2375 return BAD_VALUE;
2376 }
2377 return NO_ERROR;
2378}
2379
2380status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2381 uid_t uid)
2382{
2383 ALOGV("releaseAudioPatch() patch %d", handle);
2384
2385 ssize_t index = mAudioPatches.indexOfKey(handle);
2386
2387 if (index < 0) {
2388 return BAD_VALUE;
2389 }
2390 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2391 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2392 mUidCached, patchDesc->mUid, uid);
2393 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2394 return INVALID_OPERATION;
2395 }
2396
2397 struct audio_patch *patch = &patchDesc->mPatch;
2398 patchDesc->mUid = mUidCached;
2399 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002400 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002401 if (outputDesc == NULL) {
2402 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2403 return BAD_VALUE;
2404 }
2405
2406 setOutputDevice(outputDesc->mIoHandle,
2407 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2408 true,
2409 0,
2410 NULL);
2411 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2412 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002413 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002414 if (inputDesc == NULL) {
2415 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2416 return BAD_VALUE;
2417 }
2418 setInputDevice(inputDesc->mIoHandle,
2419 getNewInputDevice(inputDesc->mIoHandle),
2420 true,
2421 NULL);
2422 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2423 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2424 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2425 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2426 status, patchDesc->mAfPatchHandle);
2427 removeAudioPatch(patchDesc->mHandle);
2428 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002429 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002430 } else {
2431 return BAD_VALUE;
2432 }
2433 } else {
2434 return BAD_VALUE;
2435 }
2436 return NO_ERROR;
2437}
2438
2439status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2440 struct audio_patch *patches,
2441 unsigned int *generation)
2442{
2443 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2444 generation == NULL) {
2445 return BAD_VALUE;
2446 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002447 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002448 *num_patches, patches, mAudioPatches.size());
2449 if (patches == NULL) {
2450 *num_patches = 0;
2451 }
2452
2453 size_t patchesWritten = 0;
2454 size_t patchesMax = *num_patches;
2455 for (size_t i = 0;
2456 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2457 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2458 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002459 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002460 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2461 }
2462 *num_patches = mAudioPatches.size();
2463
2464 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002465 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002466 return NO_ERROR;
2467}
2468
Eric Laurente1715a42014-05-20 11:30:42 -07002469status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002470{
Eric Laurente1715a42014-05-20 11:30:42 -07002471 ALOGV("setAudioPortConfig()");
2472
2473 if (config == NULL) {
2474 return BAD_VALUE;
2475 }
2476 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2477 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002478 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2479 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002480 }
2481
Eric Laurenta121f902014-06-03 13:32:54 -07002482 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002483 if (config->type == AUDIO_PORT_TYPE_MIX) {
2484 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002485 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002486 if (outputDesc == NULL) {
2487 return BAD_VALUE;
2488 }
Eric Laurent84c70242014-06-23 08:46:27 -07002489 ALOG_ASSERT(!outputDesc->isDuplicated(),
2490 "setAudioPortConfig() called on duplicated output %d",
2491 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002492 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002493 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002494 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002495 if (inputDesc == NULL) {
2496 return BAD_VALUE;
2497 }
Eric Laurenta121f902014-06-03 13:32:54 -07002498 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002499 } else {
2500 return BAD_VALUE;
2501 }
2502 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2503 sp<DeviceDescriptor> deviceDesc;
2504 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2505 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2506 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2507 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2508 } else {
2509 return BAD_VALUE;
2510 }
2511 if (deviceDesc == NULL) {
2512 return BAD_VALUE;
2513 }
Eric Laurenta121f902014-06-03 13:32:54 -07002514 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002515 } else {
2516 return BAD_VALUE;
2517 }
2518
Eric Laurenta121f902014-06-03 13:32:54 -07002519 struct audio_port_config backupConfig;
2520 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2521 if (status == NO_ERROR) {
2522 struct audio_port_config newConfig;
2523 audioPortConfig->toAudioPortConfig(&newConfig, config);
2524 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002525 }
Eric Laurenta121f902014-06-03 13:32:54 -07002526 if (status != NO_ERROR) {
2527 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002528 }
Eric Laurente1715a42014-05-20 11:30:42 -07002529
2530 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002531}
2532
2533void AudioPolicyManager::clearAudioPatches(uid_t uid)
2534{
2535 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2536 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2537 if (patchDesc->mUid == uid) {
2538 // releaseAudioPatch() removes the patch from mAudioPatches
2539 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2540 i--;
2541 }
2542 }
2543 }
2544}
2545
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002546status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2547 audio_io_handle_t *ioHandle,
2548 audio_devices_t *device)
2549{
2550 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2551 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2552 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2553
2554 mSoundTriggerSessions.add(*session, *ioHandle);
2555
2556 return NO_ERROR;
2557}
2558
2559status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2560{
2561 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2562 if (index < 0) {
2563 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2564 return BAD_VALUE;
2565 }
2566
2567 mSoundTriggerSessions.removeItem(session);
2568 return NO_ERROR;
2569}
2570
Eric Laurent6a94d692014-05-20 11:18:06 -07002571status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2572 const sp<AudioPatch>& patch)
2573{
2574 ssize_t index = mAudioPatches.indexOfKey(handle);
2575
2576 if (index >= 0) {
2577 ALOGW("addAudioPatch() patch %d already in", handle);
2578 return ALREADY_EXISTS;
2579 }
2580 mAudioPatches.add(handle, patch);
2581 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2582 "sink handle %d",
2583 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2584 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2585 return NO_ERROR;
2586}
2587
2588status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2589{
2590 ssize_t index = mAudioPatches.indexOfKey(handle);
2591
2592 if (index < 0) {
2593 ALOGW("removeAudioPatch() patch %d not in", handle);
2594 return ALREADY_EXISTS;
2595 }
2596 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2597 mAudioPatches.valueAt(index)->mAfPatchHandle);
2598 mAudioPatches.removeItemsAt(index);
2599 return NO_ERROR;
2600}
2601
Eric Laurente552edb2014-03-10 17:42:56 -07002602// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002603// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002604// ----------------------------------------------------------------------------
2605
Eric Laurent3a4311c2014-03-17 12:00:47 -07002606uint32_t AudioPolicyManager::nextUniqueId()
2607{
2608 return android_atomic_inc(&mNextUniqueId);
2609}
2610
Eric Laurent6a94d692014-05-20 11:18:06 -07002611uint32_t AudioPolicyManager::nextAudioPortGeneration()
2612{
2613 return android_atomic_inc(&mAudioPortGeneration);
2614}
2615
Eric Laurente0720872014-03-11 09:30:41 -07002616AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002617 :
2618#ifdef AUDIO_POLICY_TEST
2619 Thread(false),
2620#endif //AUDIO_POLICY_TEST
2621 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002622 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002623 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2624 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002625 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002626 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2627 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002628{
Eric Laurent6a94d692014-05-20 11:18:06 -07002629 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002630 mpClientInterface = clientInterface;
2631
Eric Laurent3b73df72014-03-11 09:06:29 -07002632 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2633 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002634 }
2635
Eric Laurent1afeecb2014-05-14 08:52:28 -07002636 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002637 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2638 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2639 ALOGE("could not load audio policy configuration file, setting defaults");
2640 defaultAudioPolicyConfig();
2641 }
2642 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002643 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002644
2645 // must be done after reading the policy
2646 initializeVolumeCurves();
2647
2648 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002649 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2650 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002651 for (size_t i = 0; i < mHwModules.size(); i++) {
2652 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2653 if (mHwModules[i]->mHandle == 0) {
2654 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2655 continue;
2656 }
2657 // open all output streams needed to access attached devices
2658 // except for direct output streams that are only opened when they are actually
2659 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002660 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002661 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2662 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002663 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002664
Eric Laurent3a4311c2014-03-17 12:00:47 -07002665 if (outProfile->mSupportedDevices.isEmpty()) {
2666 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2667 continue;
2668 }
2669
Eric Laurent83b88082014-06-20 18:31:16 -07002670 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2671 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2672 profileType = mDefaultOutputDevice->mDeviceType;
2673 } else {
2674 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2675 }
2676 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002677 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002678 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002679
Eric Laurent83b88082014-06-20 18:31:16 -07002680 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002681 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2682 config.sample_rate = outputDesc->mSamplingRate;
2683 config.channel_mask = outputDesc->mChannelMask;
2684 config.format = outputDesc->mFormat;
2685 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2686 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2687 &output,
2688 &config,
2689 &outputDesc->mDevice,
2690 String8(""),
2691 &outputDesc->mLatency,
2692 outputDesc->mFlags);
2693
2694 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002695 ALOGW("Cannot open output stream for device %08x on hw module %s",
2696 outputDesc->mDevice,
2697 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002698 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002699 outputDesc->mSamplingRate = config.sample_rate;
2700 outputDesc->mChannelMask = config.channel_mask;
2701 outputDesc->mFormat = config.format;
2702
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002703 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002704 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002705 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002706 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002707 // give a valid ID to an attached device once confirmed it is reachable
2708 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2709 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002710 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002711 }
2712 }
Eric Laurente552edb2014-03-10 17:42:56 -07002713 if (mPrimaryOutput == 0 &&
2714 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2715 mPrimaryOutput = output;
2716 }
2717 addOutput(output, outputDesc);
2718 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002719 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002720 true);
2721 }
2722 }
2723 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002724 // open input streams needed to access attached devices to validate
2725 // mAvailableInputDevices list
2726 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2727 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002728 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002729
Eric Laurent3a4311c2014-03-17 12:00:47 -07002730 if (inProfile->mSupportedDevices.isEmpty()) {
2731 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2732 continue;
2733 }
2734
Eric Laurent83b88082014-06-20 18:31:16 -07002735 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2736 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002737 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002738
2739 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002740 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002741
Eric Laurentcf2c0212014-07-25 16:20:43 -07002742 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2743 config.sample_rate = inputDesc->mSamplingRate;
2744 config.channel_mask = inputDesc->mChannelMask;
2745 config.format = inputDesc->mFormat;
2746 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2747 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2748 &input,
2749 &config,
2750 &inputDesc->mDevice,
2751 String8(""),
2752 AUDIO_SOURCE_MIC,
2753 AUDIO_INPUT_FLAG_NONE);
2754
2755 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002756 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002757 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002758 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002759 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002760 // give a valid ID to an attached device once confirmed it is reachable
2761 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2762 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002763 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002764 }
2765 }
2766 mpClientInterface->closeInput(input);
2767 } else {
2768 ALOGW("Cannot open input stream for device %08x on hw module %s",
2769 inputDesc->mDevice,
2770 mHwModules[i]->mName);
2771 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002772 }
2773 }
2774 }
2775 // make sure all attached devices have been allocated a unique ID
2776 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2777 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002778 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002779 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2780 continue;
2781 }
2782 i++;
2783 }
2784 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2785 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002786 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002787 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2788 continue;
2789 }
2790 i++;
2791 }
2792 // make sure default device is reachable
2793 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002794 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002795 }
Eric Laurente552edb2014-03-10 17:42:56 -07002796
2797 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2798
2799 updateDevicesAndOutputs();
2800
2801#ifdef AUDIO_POLICY_TEST
2802 if (mPrimaryOutput != 0) {
2803 AudioParameter outputCmd = AudioParameter();
2804 outputCmd.addInt(String8("set_id"), 0);
2805 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2806
2807 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2808 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002809 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2810 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002811 mTestLatencyMs = 0;
2812 mCurOutput = 0;
2813 mDirectOutput = false;
2814 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2815 mTestOutputs[i] = 0;
2816 }
2817
2818 const size_t SIZE = 256;
2819 char buffer[SIZE];
2820 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2821 run(buffer, ANDROID_PRIORITY_AUDIO);
2822 }
2823#endif //AUDIO_POLICY_TEST
2824}
2825
Eric Laurente0720872014-03-11 09:30:41 -07002826AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002827{
2828#ifdef AUDIO_POLICY_TEST
2829 exit();
2830#endif //AUDIO_POLICY_TEST
2831 for (size_t i = 0; i < mOutputs.size(); i++) {
2832 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002833 }
2834 for (size_t i = 0; i < mInputs.size(); i++) {
2835 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002836 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002837 mAvailableOutputDevices.clear();
2838 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002839 mOutputs.clear();
2840 mInputs.clear();
2841 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002842}
2843
Eric Laurente0720872014-03-11 09:30:41 -07002844status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002845{
2846 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2847}
2848
2849#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002850bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002851{
2852 ALOGV("entering threadLoop()");
2853 while (!exitPending())
2854 {
2855 String8 command;
2856 int valueInt;
2857 String8 value;
2858
2859 Mutex::Autolock _l(mLock);
2860 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2861
2862 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2863 AudioParameter param = AudioParameter(command);
2864
2865 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2866 valueInt != 0) {
2867 ALOGV("Test command %s received", command.string());
2868 String8 target;
2869 if (param.get(String8("target"), target) != NO_ERROR) {
2870 target = "Manager";
2871 }
2872 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2873 param.remove(String8("test_cmd_policy_output"));
2874 mCurOutput = valueInt;
2875 }
2876 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2877 param.remove(String8("test_cmd_policy_direct"));
2878 if (value == "false") {
2879 mDirectOutput = false;
2880 } else if (value == "true") {
2881 mDirectOutput = true;
2882 }
2883 }
2884 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2885 param.remove(String8("test_cmd_policy_input"));
2886 mTestInput = valueInt;
2887 }
2888
2889 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2890 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002891 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002892 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002893 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002894 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002895 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002896 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002897 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002898 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002899 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002900 if (target == "Manager") {
2901 mTestFormat = format;
2902 } else if (mTestOutputs[mCurOutput] != 0) {
2903 AudioParameter outputParam = AudioParameter();
2904 outputParam.addInt(String8("format"), format);
2905 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2906 }
2907 }
2908 }
2909 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2910 param.remove(String8("test_cmd_policy_channels"));
2911 int channels = 0;
2912
2913 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002914 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002915 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002916 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002917 }
2918 if (channels != 0) {
2919 if (target == "Manager") {
2920 mTestChannels = channels;
2921 } else if (mTestOutputs[mCurOutput] != 0) {
2922 AudioParameter outputParam = AudioParameter();
2923 outputParam.addInt(String8("channels"), channels);
2924 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2925 }
2926 }
2927 }
2928 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2929 param.remove(String8("test_cmd_policy_sampleRate"));
2930 if (valueInt >= 0 && valueInt <= 96000) {
2931 int samplingRate = valueInt;
2932 if (target == "Manager") {
2933 mTestSamplingRate = samplingRate;
2934 } else if (mTestOutputs[mCurOutput] != 0) {
2935 AudioParameter outputParam = AudioParameter();
2936 outputParam.addInt(String8("sampling_rate"), samplingRate);
2937 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2938 }
2939 }
2940 }
2941
2942 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2943 param.remove(String8("test_cmd_policy_reopen"));
2944
Eric Laurent1f2f2232014-06-02 12:01:23 -07002945 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002946 mpClientInterface->closeOutput(mPrimaryOutput);
2947
2948 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2949
Eric Laurente552edb2014-03-10 17:42:56 -07002950 mOutputs.removeItem(mPrimaryOutput);
2951
Eric Laurent1f2f2232014-06-02 12:01:23 -07002952 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002953 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002954 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2955 config.sample_rate = outputDesc->mSamplingRate;
2956 config.channel_mask = outputDesc->mChannelMask;
2957 config.format = outputDesc->mFormat;
2958 status_t status = mpClientInterface->openOutput(moduleHandle,
2959 &mPrimaryOutput,
2960 &config,
2961 &outputDesc->mDevice,
2962 String8(""),
2963 &outputDesc->mLatency,
2964 outputDesc->mFlags);
2965 if (status != NO_ERROR) {
2966 ALOGE("Failed to reopen hardware output stream, "
2967 "samplingRate: %d, format %d, channels %d",
2968 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002969 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002970 outputDesc->mSamplingRate = config.sample_rate;
2971 outputDesc->mChannelMask = config.channel_mask;
2972 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002973 AudioParameter outputCmd = AudioParameter();
2974 outputCmd.addInt(String8("set_id"), 0);
2975 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2976 addOutput(mPrimaryOutput, outputDesc);
2977 }
2978 }
2979
2980
2981 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2982 }
2983 }
2984 return false;
2985}
2986
Eric Laurente0720872014-03-11 09:30:41 -07002987void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002988{
2989 {
2990 AutoMutex _l(mLock);
2991 requestExit();
2992 mWaitWorkCV.signal();
2993 }
2994 requestExitAndWait();
2995}
2996
Eric Laurente0720872014-03-11 09:30:41 -07002997int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002998{
2999 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3000 if (output == mTestOutputs[i]) return i;
3001 }
3002 return 0;
3003}
3004#endif //AUDIO_POLICY_TEST
3005
3006// ---
3007
Eric Laurent1f2f2232014-06-02 12:01:23 -07003008void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003009{
Eric Laurent1c333e22014-05-20 10:48:17 -07003010 outputDesc->mIoHandle = output;
3011 outputDesc->mId = nextUniqueId();
3012 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003013 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003014}
3015
Eric Laurent1f2f2232014-06-02 12:01:23 -07003016void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003017{
Eric Laurent1c333e22014-05-20 10:48:17 -07003018 inputDesc->mIoHandle = input;
3019 inputDesc->mId = nextUniqueId();
3020 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003021 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003022}
Eric Laurente552edb2014-03-10 17:42:56 -07003023
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003024void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3025 const String8 address /*in*/,
3026 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3027 // look for a match on the given address on the addresses of the outputs:
3028 // find the address by finding the patch that maps to this output
3029 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3030 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3031 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3032 if (patchIdx >= 0) {
3033 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3034 const int numSinks = patchDesc->mPatch.num_sinks;
3035 for (ssize_t j=0; j < numSinks; j++) {
3036 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3037 const char* patchAddr =
3038 patchDesc->mPatch.sinks[j].ext.device.address;
3039 if (strncmp(patchAddr,
3040 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003041 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003042 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3043 outputs.add(desc->mIoHandle);
3044 break;
3045 }
3046 }
3047 }
3048 }
3049}
3050
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003051status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003052 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003053 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003054 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003055{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003056 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003057 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003058 // erase all current sample rates, formats and channel masks
3059 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003060
Eric Laurent3b73df72014-03-11 09:06:29 -07003061 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003062 // first list already open outputs that can be routed to this device
3063 for (size_t i = 0; i < mOutputs.size(); i++) {
3064 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003065 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003066 if (!deviceDistinguishesOnAddress(device)) {
3067 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3068 outputs.add(mOutputs.keyAt(i));
3069 } else {
3070 ALOGV(" checking address match due to device 0x%x", device);
3071 findIoHandlesByAddress(desc, address, outputs);
3072 }
Eric Laurente552edb2014-03-10 17:42:56 -07003073 }
3074 }
3075 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003076 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003077 for (size_t i = 0; i < mHwModules.size(); i++)
3078 {
3079 if (mHwModules[i]->mHandle == 0) {
3080 continue;
3081 }
3082 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3083 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003084 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003085 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003086 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3087 }
3088 }
3089 }
3090
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003091 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3092
Eric Laurente552edb2014-03-10 17:42:56 -07003093 if (profiles.isEmpty() && outputs.isEmpty()) {
3094 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3095 return BAD_VALUE;
3096 }
3097
3098 // open outputs for matching profiles if needed. Direct outputs are also opened to
3099 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3100 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003101 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003102
3103 // nothing to do if one output is already opened for this profile
3104 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003105 for (j = 0; j < outputs.size(); j++) {
3106 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003107 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003108 // matching profile: save the sample rates, format and channel masks supported
3109 // by the profile in our device descriptor
3110 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003111 break;
3112 }
3113 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003114 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003115 continue;
3116 }
3117
Eric Laurent83b88082014-06-20 18:31:16 -07003118 ALOGV("opening output for device %08x with params %s profile %p",
3119 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003120 desc = new AudioOutputDescriptor(profile);
3121 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003122 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3123 config.sample_rate = desc->mSamplingRate;
3124 config.channel_mask = desc->mChannelMask;
3125 config.format = desc->mFormat;
3126 config.offload_info.sample_rate = desc->mSamplingRate;
3127 config.offload_info.channel_mask = desc->mChannelMask;
3128 config.offload_info.format = desc->mFormat;
3129 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3130 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3131 &output,
3132 &config,
3133 &desc->mDevice,
3134 address,
3135 &desc->mLatency,
3136 desc->mFlags);
3137 if (status == NO_ERROR) {
3138 desc->mSamplingRate = config.sample_rate;
3139 desc->mChannelMask = config.channel_mask;
3140 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003141
Eric Laurentd4692962014-05-05 18:13:44 -07003142 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003143 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003144 char *param = audio_device_address_to_parameter(device, address);
3145 mpClientInterface->setParameters(output, String8(param));
3146 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003147 }
3148
Eric Laurentd4692962014-05-05 18:13:44 -07003149 // Here is where we step through and resolve any "dynamic" fields
3150 String8 reply;
3151 char *value;
3152 if (profile->mSamplingRates[0] == 0) {
3153 reply = mpClientInterface->getParameters(output,
3154 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003155 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003156 reply.string());
3157 value = strpbrk((char *)reply.string(), "=");
3158 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003159 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003160 }
Eric Laurentd4692962014-05-05 18:13:44 -07003161 }
3162 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3163 reply = mpClientInterface->getParameters(output,
3164 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003165 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003166 reply.string());
3167 value = strpbrk((char *)reply.string(), "=");
3168 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003169 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003170 }
Eric Laurentd4692962014-05-05 18:13:44 -07003171 }
3172 if (profile->mChannelMasks[0] == 0) {
3173 reply = mpClientInterface->getParameters(output,
3174 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003175 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003176 reply.string());
3177 value = strpbrk((char *)reply.string(), "=");
3178 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003179 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003180 }
Eric Laurentd4692962014-05-05 18:13:44 -07003181 }
3182 if (((profile->mSamplingRates[0] == 0) &&
3183 (profile->mSamplingRates.size() < 2)) ||
3184 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3185 (profile->mFormats.size() < 2)) ||
3186 ((profile->mChannelMasks[0] == 0) &&
3187 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003188 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003189 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003190 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003191 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3192 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003193 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003194 config.sample_rate = profile->pickSamplingRate();
3195 config.channel_mask = profile->pickChannelMask();
3196 config.format = profile->pickFormat();
3197 config.offload_info.sample_rate = config.sample_rate;
3198 config.offload_info.channel_mask = config.channel_mask;
3199 config.offload_info.format = config.format;
3200 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3201 &output,
3202 &config,
3203 &desc->mDevice,
3204 address,
3205 &desc->mLatency,
3206 desc->mFlags);
3207 if (status == NO_ERROR) {
3208 desc->mSamplingRate = config.sample_rate;
3209 desc->mChannelMask = config.channel_mask;
3210 desc->mFormat = config.format;
3211 } else {
3212 output = AUDIO_IO_HANDLE_NONE;
3213 }
Eric Laurentd4692962014-05-05 18:13:44 -07003214 }
3215
Eric Laurentcf2c0212014-07-25 16:20:43 -07003216 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003217 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003218 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003219 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003220
Eric Laurentd4692962014-05-05 18:13:44 -07003221 // set initial stream volume for device
3222 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003223
Eric Laurentd4692962014-05-05 18:13:44 -07003224 //TODO: configure audio effect output stage here
3225
3226 // open a duplicating output thread for the new output and the primary output
3227 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3228 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003229 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003230 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003231 sp<AudioOutputDescriptor> dupOutputDesc =
3232 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003233 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3234 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3235 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3236 dupOutputDesc->mFormat = desc->mFormat;
3237 dupOutputDesc->mChannelMask = desc->mChannelMask;
3238 dupOutputDesc->mLatency = desc->mLatency;
3239 addOutput(duplicatedOutput, dupOutputDesc);
3240 applyStreamVolumes(duplicatedOutput, device, 0, true);
3241 } else {
3242 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3243 mPrimaryOutput, output);
3244 mpClientInterface->closeOutput(output);
3245 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003246 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003247 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003248 }
Eric Laurente552edb2014-03-10 17:42:56 -07003249 }
3250 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003251 } else {
3252 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003253 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003254 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003255 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003256 profiles.removeAt(profile_index);
3257 profile_index--;
3258 } else {
3259 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003260 devDesc->importAudioPort(profile);
3261
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003262 if (deviceDistinguishesOnAddress(device)) {
3263 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3264 device, address.string());
3265 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3266 NULL/*patch handle*/, address.string());
3267 }
Eric Laurente552edb2014-03-10 17:42:56 -07003268 ALOGV("checkOutputsForDevice(): adding output %d", output);
3269 }
3270 }
3271
3272 if (profiles.isEmpty()) {
3273 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3274 return BAD_VALUE;
3275 }
Eric Laurentd4692962014-05-05 18:13:44 -07003276 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003277 // check if one opened output is not needed any more after disconnecting one device
3278 for (size_t i = 0; i < mOutputs.size(); i++) {
3279 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003280 if (!desc->isDuplicated()) {
3281 if (!(desc->mProfile->mSupportedDevices.types()
3282 & mAvailableOutputDevices.types())) {
3283 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3284 mOutputs.keyAt(i));
3285 outputs.add(mOutputs.keyAt(i));
3286 } else if (deviceDistinguishesOnAddress(device) &&
3287 // exact match on device
3288 (desc->mProfile->mSupportedDevices.types() == device)) {
3289 findIoHandlesByAddress(desc, address, outputs);
3290 }
Eric Laurente552edb2014-03-10 17:42:56 -07003291 }
3292 }
Eric Laurentd4692962014-05-05 18:13:44 -07003293 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003294 for (size_t i = 0; i < mHwModules.size(); i++)
3295 {
3296 if (mHwModules[i]->mHandle == 0) {
3297 continue;
3298 }
3299 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3300 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003301 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003302 if (profile->mSupportedDevices.types() & device) {
3303 ALOGV("checkOutputsForDevice(): "
3304 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003305 if (profile->mSamplingRates[0] == 0) {
3306 profile->mSamplingRates.clear();
3307 profile->mSamplingRates.add(0);
3308 }
3309 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3310 profile->mFormats.clear();
3311 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3312 }
3313 if (profile->mChannelMasks[0] == 0) {
3314 profile->mChannelMasks.clear();
3315 profile->mChannelMasks.add(0);
3316 }
3317 }
3318 }
3319 }
3320 }
3321 return NO_ERROR;
3322}
3323
Eric Laurentd4692962014-05-05 18:13:44 -07003324status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3325 audio_policy_dev_state_t state,
3326 SortedVector<audio_io_handle_t>& inputs,
3327 const String8 address)
3328{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003329 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003330 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3331 // first list already open inputs that can be routed to this device
3332 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3333 desc = mInputs.valueAt(input_index);
3334 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3335 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3336 inputs.add(mInputs.keyAt(input_index));
3337 }
3338 }
3339
3340 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003341 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003342 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3343 {
3344 if (mHwModules[module_idx]->mHandle == 0) {
3345 continue;
3346 }
3347 for (size_t profile_index = 0;
3348 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3349 profile_index++)
3350 {
3351 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3352 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003353 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003354 profile_index, module_idx);
3355 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3356 }
3357 }
3358 }
3359
3360 if (profiles.isEmpty() && inputs.isEmpty()) {
3361 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3362 return BAD_VALUE;
3363 }
3364
3365 // open inputs for matching profiles if needed. Direct inputs are also opened to
3366 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3367 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3368
Eric Laurent1c333e22014-05-20 10:48:17 -07003369 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003370 // nothing to do if one input is already opened for this profile
3371 size_t input_index;
3372 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3373 desc = mInputs.valueAt(input_index);
3374 if (desc->mProfile == profile) {
3375 break;
3376 }
3377 }
3378 if (input_index != mInputs.size()) {
3379 continue;
3380 }
3381
3382 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3383 desc = new AudioInputDescriptor(profile);
3384 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003385 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3386 config.sample_rate = desc->mSamplingRate;
3387 config.channel_mask = desc->mChannelMask;
3388 config.format = desc->mFormat;
3389 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3390 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3391 &input,
3392 &config,
3393 &desc->mDevice,
3394 address,
3395 AUDIO_SOURCE_MIC,
3396 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003397
Eric Laurentcf2c0212014-07-25 16:20:43 -07003398 if (status == NO_ERROR) {
3399 desc->mSamplingRate = config.sample_rate;
3400 desc->mChannelMask = config.channel_mask;
3401 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003402
Eric Laurentd4692962014-05-05 18:13:44 -07003403 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003404 char *param = audio_device_address_to_parameter(device, address);
3405 mpClientInterface->setParameters(input, String8(param));
3406 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003407 }
3408
3409 // Here is where we step through and resolve any "dynamic" fields
3410 String8 reply;
3411 char *value;
3412 if (profile->mSamplingRates[0] == 0) {
3413 reply = mpClientInterface->getParameters(input,
3414 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3415 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3416 reply.string());
3417 value = strpbrk((char *)reply.string(), "=");
3418 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003419 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003420 }
3421 }
3422 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3423 reply = mpClientInterface->getParameters(input,
3424 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3425 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3426 value = strpbrk((char *)reply.string(), "=");
3427 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003428 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003429 }
3430 }
3431 if (profile->mChannelMasks[0] == 0) {
3432 reply = mpClientInterface->getParameters(input,
3433 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3434 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3435 reply.string());
3436 value = strpbrk((char *)reply.string(), "=");
3437 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003438 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003439 }
3440 }
3441 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3442 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3443 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3444 ALOGW("checkInputsForDevice() direct input missing param");
3445 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003446 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003447 }
3448
3449 if (input != 0) {
3450 addInput(input, desc);
3451 }
3452 } // endif input != 0
3453
Eric Laurentcf2c0212014-07-25 16:20:43 -07003454 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003455 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003456 profiles.removeAt(profile_index);
3457 profile_index--;
3458 } else {
3459 inputs.add(input);
3460 ALOGV("checkInputsForDevice(): adding input %d", input);
3461 }
3462 } // end scan profiles
3463
3464 if (profiles.isEmpty()) {
3465 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3466 return BAD_VALUE;
3467 }
3468 } else {
3469 // Disconnect
3470 // check if one opened input is not needed any more after disconnecting one device
3471 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3472 desc = mInputs.valueAt(input_index);
3473 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3474 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3475 mInputs.keyAt(input_index));
3476 inputs.add(mInputs.keyAt(input_index));
3477 }
3478 }
3479 // Clear any profiles associated with the disconnected device.
3480 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3481 if (mHwModules[module_index]->mHandle == 0) {
3482 continue;
3483 }
3484 for (size_t profile_index = 0;
3485 profile_index < mHwModules[module_index]->mInputProfiles.size();
3486 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003487 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003488 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003489 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003490 profile_index, module_index);
3491 if (profile->mSamplingRates[0] == 0) {
3492 profile->mSamplingRates.clear();
3493 profile->mSamplingRates.add(0);
3494 }
3495 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3496 profile->mFormats.clear();
3497 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3498 }
3499 if (profile->mChannelMasks[0] == 0) {
3500 profile->mChannelMasks.clear();
3501 profile->mChannelMasks.add(0);
3502 }
3503 }
3504 }
3505 }
3506 } // end disconnect
3507
3508 return NO_ERROR;
3509}
3510
3511
Eric Laurente0720872014-03-11 09:30:41 -07003512void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003513{
3514 ALOGV("closeOutput(%d)", output);
3515
Eric Laurent1f2f2232014-06-02 12:01:23 -07003516 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003517 if (outputDesc == NULL) {
3518 ALOGW("closeOutput() unknown output %d", output);
3519 return;
3520 }
3521
3522 // look for duplicated outputs connected to the output being removed.
3523 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003524 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003525 if (dupOutputDesc->isDuplicated() &&
3526 (dupOutputDesc->mOutput1 == outputDesc ||
3527 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003528 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003529 if (dupOutputDesc->mOutput1 == outputDesc) {
3530 outputDesc2 = dupOutputDesc->mOutput2;
3531 } else {
3532 outputDesc2 = dupOutputDesc->mOutput1;
3533 }
3534 // As all active tracks on duplicated output will be deleted,
3535 // and as they were also referenced on the other output, the reference
3536 // count for their stream type must be adjusted accordingly on
3537 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003538 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003539 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003540 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003541 }
3542 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3543 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3544
3545 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003546 mOutputs.removeItem(duplicatedOutput);
3547 }
3548 }
3549
Eric Laurent05b90f82014-08-27 15:32:29 -07003550 nextAudioPortGeneration();
3551
3552 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3553 if (index >= 0) {
3554 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3555 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3556 mAudioPatches.removeItemsAt(index);
3557 mpClientInterface->onAudioPatchListUpdate();
3558 }
3559
Eric Laurente552edb2014-03-10 17:42:56 -07003560 AudioParameter param;
3561 param.add(String8("closing"), String8("true"));
3562 mpClientInterface->setParameters(output, param.toString());
3563
3564 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003565 mOutputs.removeItem(output);
3566 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003567}
3568
3569void AudioPolicyManager::closeInput(audio_io_handle_t input)
3570{
3571 ALOGV("closeInput(%d)", input);
3572
3573 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3574 if (inputDesc == NULL) {
3575 ALOGW("closeInput() unknown input %d", input);
3576 return;
3577 }
3578
Eric Laurent6a94d692014-05-20 11:18:06 -07003579 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003580
3581 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3582 if (index >= 0) {
3583 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3584 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3585 mAudioPatches.removeItemsAt(index);
3586 mpClientInterface->onAudioPatchListUpdate();
3587 }
3588
3589 mpClientInterface->closeInput(input);
3590 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003591}
3592
Eric Laurente0720872014-03-11 09:30:41 -07003593SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003594 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003595{
3596 SortedVector<audio_io_handle_t> outputs;
3597
3598 ALOGVV("getOutputsForDevice() device %04x", device);
3599 for (size_t i = 0; i < openOutputs.size(); i++) {
3600 ALOGVV("output %d isDuplicated=%d device=%04x",
3601 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3602 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3603 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3604 outputs.add(openOutputs.keyAt(i));
3605 }
3606 }
3607 return outputs;
3608}
3609
Eric Laurente0720872014-03-11 09:30:41 -07003610bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003611 SortedVector<audio_io_handle_t>& outputs2)
3612{
3613 if (outputs1.size() != outputs2.size()) {
3614 return false;
3615 }
3616 for (size_t i = 0; i < outputs1.size(); i++) {
3617 if (outputs1[i] != outputs2[i]) {
3618 return false;
3619 }
3620 }
3621 return true;
3622}
3623
Eric Laurente0720872014-03-11 09:30:41 -07003624void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003625{
3626 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3627 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3628 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3629 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3630
3631 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3632 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3633 strategy, srcOutputs[0], dstOutputs[0]);
3634 // mute strategy while moving tracks from one output to another
3635 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003636 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003637 if (desc->isStrategyActive(strategy)) {
3638 setStrategyMute(strategy, true, srcOutputs[i]);
3639 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3640 }
3641 }
3642
3643 // Move effects associated to this strategy from previous output to new output
3644 if (strategy == STRATEGY_MEDIA) {
3645 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3646 SortedVector<audio_io_handle_t> moved;
3647 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003648 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3649 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3650 effectDesc->mIo != fxOutput) {
3651 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003652 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3653 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003654 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003655 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003656 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003657 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003658 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003659 }
3660 }
3661 }
3662 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003663 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3664 if (getStrategy((audio_stream_type_t)i) == strategy) {
3665 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003666 }
3667 }
3668 }
3669}
3670
Eric Laurente0720872014-03-11 09:30:41 -07003671void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003672{
3673 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3674 checkOutputForStrategy(STRATEGY_PHONE);
3675 checkOutputForStrategy(STRATEGY_SONIFICATION);
3676 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3677 checkOutputForStrategy(STRATEGY_MEDIA);
3678 checkOutputForStrategy(STRATEGY_DTMF);
3679}
3680
Eric Laurente0720872014-03-11 09:30:41 -07003681audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003682{
Eric Laurente552edb2014-03-10 17:42:56 -07003683 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003684 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003685 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3686 return mOutputs.keyAt(i);
3687 }
3688 }
3689
3690 return 0;
3691}
3692
Eric Laurente0720872014-03-11 09:30:41 -07003693void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003694{
Eric Laurente552edb2014-03-10 17:42:56 -07003695 audio_io_handle_t a2dpOutput = getA2dpOutput();
3696 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003697 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003698 return;
3699 }
3700
Eric Laurent3a4311c2014-03-17 12:00:47 -07003701 bool isScoConnected =
3702 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003703 // suspend A2DP output if:
3704 // (NOT already suspended) &&
3705 // ((SCO device is connected &&
3706 // (forced usage for communication || for record is SCO))) ||
3707 // (phone state is ringing || in call)
3708 //
3709 // restore A2DP output if:
3710 // (Already suspended) &&
3711 // ((SCO device is NOT connected ||
3712 // (forced usage NOT for communication && NOT for record is SCO))) &&
3713 // (phone state is NOT ringing && NOT in call)
3714 //
3715 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003716 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003717 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3718 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3719 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3720 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003721
3722 mpClientInterface->restoreOutput(a2dpOutput);
3723 mA2dpSuspended = false;
3724 }
3725 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003726 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003727 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3728 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3729 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3730 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003731
3732 mpClientInterface->suspendOutput(a2dpOutput);
3733 mA2dpSuspended = true;
3734 }
3735 }
3736}
3737
Eric Laurent1c333e22014-05-20 10:48:17 -07003738audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003739{
3740 audio_devices_t device = AUDIO_DEVICE_NONE;
3741
Eric Laurent1f2f2232014-06-02 12:01:23 -07003742 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003743
3744 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3745 if (index >= 0) {
3746 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3747 if (patchDesc->mUid != mUidCached) {
3748 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3749 outputDesc->device(), outputDesc->mPatchHandle);
3750 return outputDesc->device();
3751 }
3752 }
3753
Eric Laurente552edb2014-03-10 17:42:56 -07003754 // check the following by order of priority to request a routing change if necessary:
3755 // 1: the strategy enforced audible is active on the output:
3756 // use device for strategy enforced audible
3757 // 2: we are in call or the strategy phone is active on the output:
3758 // use device for strategy phone
3759 // 3: the strategy sonification is active on the output:
3760 // use device for strategy sonification
3761 // 4: the strategy "respectful" sonification is active on the output:
3762 // use device for strategy "respectful" sonification
3763 // 5: the strategy media is active on the output:
3764 // use device for strategy media
3765 // 6: the strategy DTMF is active on the output:
3766 // use device for strategy DTMF
3767 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3768 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3769 } else if (isInCall() ||
3770 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3771 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3772 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3773 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3774 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3775 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3776 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3777 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3778 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3779 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3780 }
3781
Eric Laurent1c333e22014-05-20 10:48:17 -07003782 ALOGV("getNewOutputDevice() selected device %x", device);
3783 return device;
3784}
3785
3786audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3787{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003788 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003789
3790 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3791 if (index >= 0) {
3792 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3793 if (patchDesc->mUid != mUidCached) {
3794 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3795 inputDesc->mDevice, inputDesc->mPatchHandle);
3796 return inputDesc->mDevice;
3797 }
3798 }
3799
Eric Laurent1c333e22014-05-20 10:48:17 -07003800 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3801
3802 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003803 return device;
3804}
3805
Eric Laurente0720872014-03-11 09:30:41 -07003806uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003807 return (uint32_t)getStrategy(stream);
3808}
3809
Eric Laurente0720872014-03-11 09:30:41 -07003810audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003811 // By checking the range of stream before calling getStrategy, we avoid
3812 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3813 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003814 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003815 return AUDIO_DEVICE_NONE;
3816 }
3817 audio_devices_t devices;
3818 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3819 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3820 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3821 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003822 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003823 if (outputDesc->isStrategyActive(strategy)) {
3824 devices = outputDesc->device();
3825 break;
3826 }
Eric Laurente552edb2014-03-10 17:42:56 -07003827 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003828
3829 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
3830 and doesn't really need to.*/
3831 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
3832 devices |= AUDIO_DEVICE_OUT_SPEAKER;
3833 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3834 }
3835
Eric Laurente552edb2014-03-10 17:42:56 -07003836 return devices;
3837}
3838
Eric Laurente0720872014-03-11 09:30:41 -07003839AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003840 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003841 // stream to strategy mapping
3842 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003843 case AUDIO_STREAM_VOICE_CALL:
3844 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003845 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003846 case AUDIO_STREAM_RING:
3847 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003848 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003849 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003850 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003851 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003852 return STRATEGY_DTMF;
3853 default:
3854 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003855 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003856 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3857 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003858 case AUDIO_STREAM_TTS:
3859 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003860 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003861 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003862 return STRATEGY_ENFORCED_AUDIBLE;
3863 }
3864}
3865
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003866uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3867 // flags to strategy mapping
3868 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3869 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3870 }
3871
3872 // usage to strategy mapping
3873 switch (attr->usage) {
3874 case AUDIO_USAGE_MEDIA:
3875 case AUDIO_USAGE_GAME:
3876 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3877 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3878 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3879 return (uint32_t) STRATEGY_MEDIA;
3880
3881 case AUDIO_USAGE_VOICE_COMMUNICATION:
3882 return (uint32_t) STRATEGY_PHONE;
3883
3884 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3885 return (uint32_t) STRATEGY_DTMF;
3886
3887 case AUDIO_USAGE_ALARM:
3888 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3889 return (uint32_t) STRATEGY_SONIFICATION;
3890
3891 case AUDIO_USAGE_NOTIFICATION:
3892 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3893 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3894 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3895 case AUDIO_USAGE_NOTIFICATION_EVENT:
3896 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3897
3898 case AUDIO_USAGE_UNKNOWN:
3899 default:
3900 return (uint32_t) STRATEGY_MEDIA;
3901 }
3902}
3903
Eric Laurente0720872014-03-11 09:30:41 -07003904void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003905 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003906 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003907 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3908 updateDevicesAndOutputs();
3909 break;
3910 default:
3911 break;
3912 }
3913}
3914
Eric Laurente0720872014-03-11 09:30:41 -07003915audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003916 bool fromCache)
3917{
3918 uint32_t device = AUDIO_DEVICE_NONE;
3919
3920 if (fromCache) {
3921 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3922 strategy, mDeviceForStrategy[strategy]);
3923 return mDeviceForStrategy[strategy];
3924 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003925 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003926 switch (strategy) {
3927
3928 case STRATEGY_SONIFICATION_RESPECTFUL:
3929 if (isInCall()) {
3930 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003931 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003932 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3933 // while media is playing on a remote device, use the the sonification behavior.
3934 // Note that we test this usecase before testing if media is playing because
3935 // the isStreamActive() method only informs about the activity of a stream, not
3936 // if it's for local playback. Note also that we use the same delay between both tests
3937 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05003938 //user "safe" speaker if available instead of normal speaker to avoid triggering
3939 //other acoustic safety mechanisms for notification
3940 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
3941 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003942 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003943 // while media is playing (or has recently played), use the same device
3944 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3945 } else {
3946 // when media is not playing anymore, fall back on the sonification behavior
3947 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05003948 //user "safe" speaker if available instead of normal speaker to avoid triggering
3949 //other acoustic safety mechanisms for notification
3950 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
3951 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07003952 }
3953
3954 break;
3955
3956 case STRATEGY_DTMF:
3957 if (!isInCall()) {
3958 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3959 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3960 break;
3961 }
3962 // when in call, DTMF and PHONE strategies follow the same rules
3963 // FALL THROUGH
3964
3965 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07003966 // Force use of only devices on primary output if:
3967 // - in call AND
3968 // - cannot route from voice call RX OR
3969 // - audio HAL version is < 3.0 and TX device is on the primary HW module
3970 if (mPhoneState == AUDIO_MODE_IN_CALL) {
3971 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
3972 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
3973 if (((mAvailableInputDevices.types() &
3974 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
3975 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07003976 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07003977 AUDIO_DEVICE_API_VERSION_3_0))) {
3978 availableOutputDeviceTypes = availablePrimaryOutputDevices();
3979 }
3980 }
Eric Laurente552edb2014-03-10 17:42:56 -07003981 // for phone strategy, we first consider the forced use and then the available devices by order
3982 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003983 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3984 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003985 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003986 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003987 if (device) break;
3988 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003989 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003990 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003991 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003992 if (device) break;
3993 // if SCO device is requested but no SCO device is available, fall back to default case
3994 // FALL THROUGH
3995
3996 default: // FORCE_NONE
3997 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003998 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003999 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004000 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004001 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004002 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004003 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004004 if (device) break;
4005 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004006 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004007 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004008 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004009 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004010 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4011 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004012 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004013 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004014 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004015 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004016 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004017 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004018 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004019 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004020 if (device) break;
4021 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004022 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004023 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004024 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004025 if (device == AUDIO_DEVICE_NONE) {
4026 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4027 }
4028 break;
4029
Eric Laurent3b73df72014-03-11 09:06:29 -07004030 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004031 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4032 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004033 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004034 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004035 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004036 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004037 if (device) break;
4038 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004039 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004040 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004041 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004042 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004043 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004044 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004045 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004046 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004047 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004048 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004049 if (device) break;
4050 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004051 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4052 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004053 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004054 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004055 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004056 if (device == AUDIO_DEVICE_NONE) {
4057 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4058 }
4059 break;
4060 }
4061 break;
4062
4063 case STRATEGY_SONIFICATION:
4064
4065 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4066 // handleIncallSonification().
4067 if (isInCall()) {
4068 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4069 break;
4070 }
4071 // FALL THROUGH
4072
4073 case STRATEGY_ENFORCED_AUDIBLE:
4074 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4075 // except:
4076 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4077 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4078
4079 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004080 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004081 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004082 if (device == AUDIO_DEVICE_NONE) {
4083 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4084 }
4085 }
4086 // The second device used for sonification is the same as the device used by media strategy
4087 // FALL THROUGH
4088
4089 case STRATEGY_MEDIA: {
4090 uint32_t device2 = AUDIO_DEVICE_NONE;
4091 if (strategy != STRATEGY_SONIFICATION) {
4092 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004093 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004094 }
4095 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004096 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004097 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004098 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004099 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004100 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004101 }
4102 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004103 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004104 }
4105 }
4106 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004107 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004108 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004109 if ((device2 == AUDIO_DEVICE_NONE)) {
4110 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4111 }
Eric Laurente552edb2014-03-10 17:42:56 -07004112 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004113 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004114 }
4115 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004116 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004117 }
4118 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004119 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004120 }
4121 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004122 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004123 }
4124 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4125 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004126 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004127 }
4128 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004129 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004130 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004131 }
4132 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004133 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004134 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004135 int device3 = AUDIO_DEVICE_NONE;
4136 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004137 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004138 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4139 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004140 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004141 }
Eric Laurente552edb2014-03-10 17:42:56 -07004142
Jungshik Jang839e4f32014-06-26 17:23:40 +09004143 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004144 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4145 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4146 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004147
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004148 // If hdmi system audio mode is on, remove speaker out of output list.
4149 if ((strategy == STRATEGY_MEDIA) &&
4150 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4151 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4152 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4153 }
4154
Eric Laurente552edb2014-03-10 17:42:56 -07004155 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004156 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004157 if (device == AUDIO_DEVICE_NONE) {
4158 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4159 }
4160 } break;
4161
4162 default:
4163 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4164 break;
4165 }
4166
4167 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4168 return device;
4169}
4170
Eric Laurente0720872014-03-11 09:30:41 -07004171void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004172{
4173 for (int i = 0; i < NUM_STRATEGIES; i++) {
4174 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4175 }
4176 mPreviousOutputs = mOutputs;
4177}
4178
Eric Laurent1f2f2232014-06-02 12:01:23 -07004179uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004180 audio_devices_t prevDevice,
4181 uint32_t delayMs)
4182{
4183 // mute/unmute strategies using an incompatible device combination
4184 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4185 // if unmuting, unmute only after the specified delay
4186 if (outputDesc->isDuplicated()) {
4187 return 0;
4188 }
4189
4190 uint32_t muteWaitMs = 0;
4191 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004192 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004193
4194 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4195 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4196 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4197 bool doMute = false;
4198
4199 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4200 doMute = true;
4201 outputDesc->mStrategyMutedByDevice[i] = true;
4202 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4203 doMute = true;
4204 outputDesc->mStrategyMutedByDevice[i] = false;
4205 }
Eric Laurent99401132014-05-07 19:48:15 -07004206 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004207 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004208 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004209 // skip output if it does not share any device with current output
4210 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4211 == AUDIO_DEVICE_NONE) {
4212 continue;
4213 }
4214 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4215 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4216 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4217 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4218 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004219 if (mute) {
4220 // FIXME: should not need to double latency if volume could be applied
4221 // immediately by the audioflinger mixer. We must account for the delay
4222 // between now and the next time the audioflinger thread for this output
4223 // will process a buffer (which corresponds to one buffer size,
4224 // usually 1/2 or 1/4 of the latency).
4225 if (muteWaitMs < desc->latency() * 2) {
4226 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004227 }
4228 }
4229 }
4230 }
4231 }
4232 }
4233
Eric Laurent99401132014-05-07 19:48:15 -07004234 // temporary mute output if device selection changes to avoid volume bursts due to
4235 // different per device volumes
4236 if (outputDesc->isActive() && (device != prevDevice)) {
4237 if (muteWaitMs < outputDesc->latency() * 2) {
4238 muteWaitMs = outputDesc->latency() * 2;
4239 }
4240 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4241 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004242 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004243 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004244 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004245 muteWaitMs *2, device);
4246 }
4247 }
4248 }
4249
Eric Laurente552edb2014-03-10 17:42:56 -07004250 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4251 if (muteWaitMs > delayMs) {
4252 muteWaitMs -= delayMs;
4253 usleep(muteWaitMs * 1000);
4254 return muteWaitMs;
4255 }
4256 return 0;
4257}
4258
Eric Laurente0720872014-03-11 09:30:41 -07004259uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004260 audio_devices_t device,
4261 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004262 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004263 audio_patch_handle_t *patchHandle,
4264 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004265{
4266 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004267 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004268 AudioParameter param;
4269 uint32_t muteWaitMs;
4270
4271 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004272 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4273 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004274 return muteWaitMs;
4275 }
4276 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4277 // output profile
4278 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004279 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004280 return 0;
4281 }
4282
4283 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004284 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004285
4286 audio_devices_t prevDevice = outputDesc->mDevice;
4287
4288 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4289
4290 if (device != AUDIO_DEVICE_NONE) {
4291 outputDesc->mDevice = device;
4292 }
4293 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4294
4295 // Do not change the routing if:
4296 // - the requested device is AUDIO_DEVICE_NONE
4297 // - the requested device is the same as current device and force is not specified.
4298 // Doing this check here allows the caller to call setOutputDevice() without conditions
4299 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4300 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4301 return muteWaitMs;
4302 }
4303
4304 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004305
Eric Laurente552edb2014-03-10 17:42:56 -07004306 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004307 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004308 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004309 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004310 DeviceVector deviceList = (address == NULL) ?
4311 mAvailableOutputDevices.getDevicesFromType(device)
4312 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004313 if (!deviceList.isEmpty()) {
4314 struct audio_patch patch;
4315 outputDesc->toAudioPortConfig(&patch.sources[0]);
4316 patch.num_sources = 1;
4317 patch.num_sinks = 0;
4318 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4319 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004320 patch.num_sinks++;
4321 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004322 ssize_t index;
4323 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4324 index = mAudioPatches.indexOfKey(*patchHandle);
4325 } else {
4326 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4327 }
4328 sp< AudioPatch> patchDesc;
4329 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4330 if (index >= 0) {
4331 patchDesc = mAudioPatches.valueAt(index);
4332 afPatchHandle = patchDesc->mAfPatchHandle;
4333 }
4334
Eric Laurent1c333e22014-05-20 10:48:17 -07004335 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004336 &afPatchHandle,
4337 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004338 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4339 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004340 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004341 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004342 if (index < 0) {
4343 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4344 &patch, mUidCached);
4345 addAudioPatch(patchDesc->mHandle, patchDesc);
4346 } else {
4347 patchDesc->mPatch = patch;
4348 }
4349 patchDesc->mAfPatchHandle = afPatchHandle;
4350 patchDesc->mUid = mUidCached;
4351 if (patchHandle) {
4352 *patchHandle = patchDesc->mHandle;
4353 }
4354 outputDesc->mPatchHandle = patchDesc->mHandle;
4355 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004356 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004357 }
4358 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004359
4360 // inform all input as well
4361 for (size_t i = 0; i < mInputs.size(); i++) {
4362 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4363 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4364 AudioParameter inputCmd = AudioParameter();
4365 ALOGV("%s: inform input %d of device:%d", __func__,
4366 inputDescriptor->mIoHandle, device);
4367 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4368 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4369 inputCmd.toString(),
4370 delayMs);
4371 }
4372 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004373 }
Eric Laurente552edb2014-03-10 17:42:56 -07004374
4375 // update stream volumes according to new device
4376 applyStreamVolumes(output, device, delayMs);
4377
4378 return muteWaitMs;
4379}
4380
Eric Laurent1c333e22014-05-20 10:48:17 -07004381status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004382 int delayMs,
4383 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004384{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004385 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004386 ssize_t index;
4387 if (patchHandle) {
4388 index = mAudioPatches.indexOfKey(*patchHandle);
4389 } else {
4390 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4391 }
4392 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004393 return INVALID_OPERATION;
4394 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004395 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4396 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004397 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4398 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004399 removeAudioPatch(patchDesc->mHandle);
4400 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004401 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004402 return status;
4403}
4404
4405status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4406 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004407 bool force,
4408 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004409{
4410 status_t status = NO_ERROR;
4411
Eric Laurent1f2f2232014-06-02 12:01:23 -07004412 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004413 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4414 inputDesc->mDevice = device;
4415
4416 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4417 if (!deviceList.isEmpty()) {
4418 struct audio_patch patch;
4419 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004420 // AUDIO_SOURCE_HOTWORD is for internal use only:
4421 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004422 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4423 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004424 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4425 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004426 patch.num_sinks = 1;
4427 //only one input device for now
4428 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004429 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004430 ssize_t index;
4431 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4432 index = mAudioPatches.indexOfKey(*patchHandle);
4433 } else {
4434 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4435 }
4436 sp< AudioPatch> patchDesc;
4437 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4438 if (index >= 0) {
4439 patchDesc = mAudioPatches.valueAt(index);
4440 afPatchHandle = patchDesc->mAfPatchHandle;
4441 }
4442
Eric Laurent1c333e22014-05-20 10:48:17 -07004443 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004444 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004445 0);
4446 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004447 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004448 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004449 if (index < 0) {
4450 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4451 &patch, mUidCached);
4452 addAudioPatch(patchDesc->mHandle, patchDesc);
4453 } else {
4454 patchDesc->mPatch = patch;
4455 }
4456 patchDesc->mAfPatchHandle = afPatchHandle;
4457 patchDesc->mUid = mUidCached;
4458 if (patchHandle) {
4459 *patchHandle = patchDesc->mHandle;
4460 }
4461 inputDesc->mPatchHandle = patchDesc->mHandle;
4462 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004463 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004464 }
4465 }
4466 }
4467 return status;
4468}
4469
Eric Laurent6a94d692014-05-20 11:18:06 -07004470status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4471 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004472{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004473 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004474 ssize_t index;
4475 if (patchHandle) {
4476 index = mAudioPatches.indexOfKey(*patchHandle);
4477 } else {
4478 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4479 }
4480 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004481 return INVALID_OPERATION;
4482 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004483 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4484 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004485 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4486 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004487 removeAudioPatch(patchDesc->mHandle);
4488 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004489 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004490 return status;
4491}
4492
4493sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004494 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004495 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004496 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004497 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004498{
4499 // Choose an input profile based on the requested capture parameters: select the first available
4500 // profile supporting all requested parameters.
4501
4502 for (size_t i = 0; i < mHwModules.size(); i++)
4503 {
4504 if (mHwModules[i]->mHandle == 0) {
4505 continue;
4506 }
4507 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4508 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004509 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004510 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004511 if (profile->isCompatibleProfile(device, samplingRate,
4512 &samplingRate /*updatedSamplingRate*/,
4513 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004514 return profile;
4515 }
4516 }
4517 }
4518 return NULL;
4519}
4520
Eric Laurente0720872014-03-11 09:30:41 -07004521audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004522{
4523 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004524 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4525 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004526 switch (inputSource) {
4527 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004528 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004529 device = AUDIO_DEVICE_IN_VOICE_CALL;
4530 break;
4531 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004532 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004533
4534 case AUDIO_SOURCE_DEFAULT:
4535 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004536 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4537 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004538 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4539 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4540 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4541 device = AUDIO_DEVICE_IN_USB_DEVICE;
4542 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4543 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004544 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004545 break;
4546
4547 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4548 // Allow only use of devices on primary input if in call and HAL does not support routing
4549 // to voice call path.
4550 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4551 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4552 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4553 }
4554
4555 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4556 case AUDIO_POLICY_FORCE_BT_SCO:
4557 // if SCO device is requested but no SCO device is available, fall back to default case
4558 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4559 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4560 break;
4561 }
4562 // FALL THROUGH
4563
4564 default: // FORCE_NONE
4565 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4566 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4567 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4568 device = AUDIO_DEVICE_IN_USB_DEVICE;
4569 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4570 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4571 }
4572 break;
4573
4574 case AUDIO_POLICY_FORCE_SPEAKER:
4575 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4576 device = AUDIO_DEVICE_IN_BACK_MIC;
4577 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4578 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4579 }
4580 break;
4581 }
4582 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004583
Eric Laurente552edb2014-03-10 17:42:56 -07004584 case AUDIO_SOURCE_VOICE_RECOGNITION:
4585 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004586 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004587 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004588 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004589 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004590 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004591 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4592 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004593 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004594 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4595 }
4596 break;
4597 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004598 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004599 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004600 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004601 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4602 }
4603 break;
4604 case AUDIO_SOURCE_VOICE_DOWNLINK:
4605 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004606 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004607 device = AUDIO_DEVICE_IN_VOICE_CALL;
4608 }
4609 break;
4610 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004611 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004612 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4613 }
4614 break;
4615 default:
4616 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4617 break;
4618 }
4619 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4620 return device;
4621}
4622
Eric Laurente0720872014-03-11 09:30:41 -07004623bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004624{
4625 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4626 device &= ~AUDIO_DEVICE_BIT_IN;
4627 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4628 return true;
4629 }
4630 return false;
4631}
4632
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004633bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4634 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4635}
4636
Eric Laurente0720872014-03-11 09:30:41 -07004637audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004638{
4639 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004640 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004641 if ((input_descriptor->mRefCount > 0)
4642 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4643 return mInputs.keyAt(i);
4644 }
4645 }
4646 return 0;
4647}
4648
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004649uint32_t AudioPolicyManager::activeInputsCount() const
4650{
4651 uint32_t count = 0;
4652 for (size_t i = 0; i < mInputs.size(); i++) {
4653 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4654 if (desc->mRefCount > 0) {
4655 return count++;
4656 }
4657 }
4658 return count;
4659}
4660
Eric Laurente552edb2014-03-10 17:42:56 -07004661
Eric Laurente0720872014-03-11 09:30:41 -07004662audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004663{
4664 if (device == AUDIO_DEVICE_NONE) {
4665 // this happens when forcing a route update and no track is active on an output.
4666 // In this case the returned category is not important.
4667 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004668 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004669 // Multiple device selection is either:
4670 // - speaker + one other device: give priority to speaker in this case.
4671 // - one A2DP device + another device: happens with duplicated output. In this case
4672 // retain the device on the A2DP output as the other must not correspond to an active
4673 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004674 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004675 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4676 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004677 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4678 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4679 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4680 device = AUDIO_DEVICE_OUT_AUX_LINE;
4681 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4682 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004683 } else {
4684 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4685 }
4686 }
4687
Jon Eklund11c9fb12014-06-23 14:47:03 -05004688 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4689 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4690 device = AUDIO_DEVICE_OUT_SPEAKER;
4691
Eric Laurent3b73df72014-03-11 09:06:29 -07004692 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004693 "getDeviceForVolume() invalid device combination: %08x",
4694 device);
4695
4696 return device;
4697}
4698
Eric Laurente0720872014-03-11 09:30:41 -07004699AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004700{
4701 switch(getDeviceForVolume(device)) {
4702 case AUDIO_DEVICE_OUT_EARPIECE:
4703 return DEVICE_CATEGORY_EARPIECE;
4704 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4705 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4706 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4707 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4708 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4709 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4710 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004711 case AUDIO_DEVICE_OUT_LINE:
4712 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4713 /*USB? Remote submix?*/
4714 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004715 case AUDIO_DEVICE_OUT_SPEAKER:
4716 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4717 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004718 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4719 case AUDIO_DEVICE_OUT_USB_DEVICE:
4720 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4721 default:
4722 return DEVICE_CATEGORY_SPEAKER;
4723 }
4724}
4725
Eric Laurente0720872014-03-11 09:30:41 -07004726float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004727 int indexInUi)
4728{
4729 device_category deviceCategory = getDeviceCategory(device);
4730 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4731
4732 // the volume index in the UI is relative to the min and max volume indices for this stream type
4733 int nbSteps = 1 + curve[VOLMAX].mIndex -
4734 curve[VOLMIN].mIndex;
4735 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4736 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4737
4738 // find what part of the curve this index volume belongs to, or if it's out of bounds
4739 int segment = 0;
4740 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4741 return 0.0f;
4742 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4743 segment = 0;
4744 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4745 segment = 1;
4746 } else if (volIdx <= curve[VOLMAX].mIndex) {
4747 segment = 2;
4748 } else { // out of bounds
4749 return 1.0f;
4750 }
4751
4752 // linear interpolation in the attenuation table in dB
4753 float decibels = curve[segment].mDBAttenuation +
4754 ((float)(volIdx - curve[segment].mIndex)) *
4755 ( (curve[segment+1].mDBAttenuation -
4756 curve[segment].mDBAttenuation) /
4757 ((float)(curve[segment+1].mIndex -
4758 curve[segment].mIndex)) );
4759
4760 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4761
4762 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4763 curve[segment].mIndex, volIdx,
4764 curve[segment+1].mIndex,
4765 curve[segment].mDBAttenuation,
4766 decibels,
4767 curve[segment+1].mDBAttenuation,
4768 amplification);
4769
4770 return amplification;
4771}
4772
Eric Laurente0720872014-03-11 09:30:41 -07004773const AudioPolicyManager::VolumeCurvePoint
4774 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004775 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4776};
4777
Eric Laurente0720872014-03-11 09:30:41 -07004778const AudioPolicyManager::VolumeCurvePoint
4779 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004780 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4781};
4782
Eric Laurente0720872014-03-11 09:30:41 -07004783const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004784 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4785 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4786};
4787
4788const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004789 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004790 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4791};
4792
Eric Laurente0720872014-03-11 09:30:41 -07004793const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004794 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004795 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004796};
4797
4798const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004799 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004800 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4801};
4802
Eric Laurente0720872014-03-11 09:30:41 -07004803const AudioPolicyManager::VolumeCurvePoint
4804 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004805 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4806};
4807
4808// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4809// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4810// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4811// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4812
Eric Laurente0720872014-03-11 09:30:41 -07004813const AudioPolicyManager::VolumeCurvePoint
4814 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004815 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4816};
4817
Eric Laurente0720872014-03-11 09:30:41 -07004818const AudioPolicyManager::VolumeCurvePoint
4819 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004820 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4821};
4822
Eric Laurente0720872014-03-11 09:30:41 -07004823const AudioPolicyManager::VolumeCurvePoint
4824 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004825 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4826};
4827
Eric Laurente0720872014-03-11 09:30:41 -07004828const AudioPolicyManager::VolumeCurvePoint
4829 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004830 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4831};
4832
Eric Laurente0720872014-03-11 09:30:41 -07004833const AudioPolicyManager::VolumeCurvePoint
4834 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004835 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4836};
4837
Eric Laurente0720872014-03-11 09:30:41 -07004838const AudioPolicyManager::VolumeCurvePoint
4839 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4840 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004841 { // AUDIO_STREAM_VOICE_CALL
4842 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4843 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004844 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4845 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004846 },
4847 { // AUDIO_STREAM_SYSTEM
4848 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4849 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004850 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4851 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004852 },
4853 { // AUDIO_STREAM_RING
4854 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4855 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004856 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4857 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004858 },
4859 { // AUDIO_STREAM_MUSIC
4860 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4861 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004862 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4863 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004864 },
4865 { // AUDIO_STREAM_ALARM
4866 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4867 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004868 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4869 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004870 },
4871 { // AUDIO_STREAM_NOTIFICATION
4872 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4873 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004874 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4875 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004876 },
4877 { // AUDIO_STREAM_BLUETOOTH_SCO
4878 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4879 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004880 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4881 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004882 },
4883 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4884 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4885 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004886 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4887 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004888 },
4889 { // AUDIO_STREAM_DTMF
4890 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4891 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004892 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4893 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004894 },
4895 { // AUDIO_STREAM_TTS
4896 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4897 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004898 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4899 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004900 },
4901};
4902
Eric Laurente0720872014-03-11 09:30:41 -07004903void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004904{
4905 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4906 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4907 mStreams[i].mVolumeCurve[j] =
4908 sVolumeProfiles[i][j];
4909 }
4910 }
4911
4912 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4913 if (mSpeakerDrcEnabled) {
4914 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4915 sDefaultSystemVolumeCurveDrc;
4916 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4917 sSpeakerSonificationVolumeCurveDrc;
4918 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4919 sSpeakerSonificationVolumeCurveDrc;
4920 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4921 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004922 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4923 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004924 }
4925}
4926
Eric Laurente0720872014-03-11 09:30:41 -07004927float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004928 int index,
4929 audio_io_handle_t output,
4930 audio_devices_t device)
4931{
4932 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004933 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004934 StreamDescriptor &streamDesc = mStreams[stream];
4935
4936 if (device == AUDIO_DEVICE_NONE) {
4937 device = outputDesc->device();
4938 }
4939
Eric Laurente552edb2014-03-10 17:42:56 -07004940 volume = volIndexToAmpl(device, streamDesc, index);
4941
4942 // if a headset is connected, apply the following rules to ring tones and notifications
4943 // to avoid sound level bursts in user's ears:
4944 // - always attenuate ring tones and notifications volume by 6dB
4945 // - if music is playing, always limit the volume to current music volume,
4946 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004947 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004948 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4949 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4950 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4951 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4952 ((stream_strategy == STRATEGY_SONIFICATION)
4953 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004954 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004955 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004956 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004957 streamDesc.mCanBeMuted) {
4958 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4959 // when the phone is ringing we must consider that music could have been paused just before
4960 // by the music application and behave as if music was active if the last music track was
4961 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004962 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004963 mLimitRingtoneVolume) {
4964 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004965 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4966 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004967 output,
4968 musicDevice);
4969 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4970 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4971 if (volume > minVol) {
4972 volume = minVol;
4973 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4974 }
4975 }
4976 }
4977
4978 return volume;
4979}
4980
Eric Laurente0720872014-03-11 09:30:41 -07004981status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004982 int index,
4983 audio_io_handle_t output,
4984 audio_devices_t device,
4985 int delayMs,
4986 bool force)
4987{
4988
4989 // do not change actual stream volume if the stream is muted
4990 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4991 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4992 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4993 return NO_ERROR;
4994 }
4995
4996 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004997 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4998 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4999 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5000 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005001 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005002 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005003 return INVALID_OPERATION;
5004 }
5005
5006 float volume = computeVolume(stream, index, output, device);
5007 // We actually change the volume if:
5008 // - the float value returned by computeVolume() changed
5009 // - the force flag is set
5010 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5011 force) {
5012 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5013 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5014 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5015 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005016 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5017 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005018 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005019 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005020 }
5021
Eric Laurent3b73df72014-03-11 09:06:29 -07005022 if (stream == AUDIO_STREAM_VOICE_CALL ||
5023 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005024 float voiceVolume;
5025 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005026 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005027 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5028 } else {
5029 voiceVolume = 1.0;
5030 }
5031
5032 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5033 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5034 mLastVoiceVolume = voiceVolume;
5035 }
5036 }
5037
5038 return NO_ERROR;
5039}
5040
Eric Laurente0720872014-03-11 09:30:41 -07005041void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005042 audio_devices_t device,
5043 int delayMs,
5044 bool force)
5045{
5046 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5047
Eric Laurent3b73df72014-03-11 09:06:29 -07005048 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5049 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005050 mStreams[stream].getVolumeIndex(device),
5051 output,
5052 device,
5053 delayMs,
5054 force);
5055 }
5056}
5057
Eric Laurente0720872014-03-11 09:30:41 -07005058void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005059 bool on,
5060 audio_io_handle_t output,
5061 int delayMs,
5062 audio_devices_t device)
5063{
5064 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005065 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5066 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5067 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005068 }
5069 }
5070}
5071
Eric Laurente0720872014-03-11 09:30:41 -07005072void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005073 bool on,
5074 audio_io_handle_t output,
5075 int delayMs,
5076 audio_devices_t device)
5077{
5078 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005079 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005080 if (device == AUDIO_DEVICE_NONE) {
5081 device = outputDesc->device();
5082 }
5083
5084 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5085 stream, on, output, outputDesc->mMuteCount[stream], device);
5086
5087 if (on) {
5088 if (outputDesc->mMuteCount[stream] == 0) {
5089 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005090 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5091 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005092 checkAndSetVolume(stream, 0, output, device, delayMs);
5093 }
5094 }
5095 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5096 outputDesc->mMuteCount[stream]++;
5097 } else {
5098 if (outputDesc->mMuteCount[stream] == 0) {
5099 ALOGV("setStreamMute() unmuting non muted stream!");
5100 return;
5101 }
5102 if (--outputDesc->mMuteCount[stream] == 0) {
5103 checkAndSetVolume(stream,
5104 streamDesc.getVolumeIndex(device),
5105 output,
5106 device,
5107 delayMs);
5108 }
5109 }
5110}
5111
Eric Laurente0720872014-03-11 09:30:41 -07005112void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005113 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005114{
5115 // if the stream pertains to sonification strategy and we are in call we must
5116 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5117 // in the device used for phone strategy and play the tone if the selected device does not
5118 // interfere with the device used for phone strategy
5119 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5120 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005121 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005122 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5123 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005124 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005125 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5126 stream, starting, outputDesc->mDevice, stateChange);
5127 if (outputDesc->mRefCount[stream]) {
5128 int muteCount = 1;
5129 if (stateChange) {
5130 muteCount = outputDesc->mRefCount[stream];
5131 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005132 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005133 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5134 for (int i = 0; i < muteCount; i++) {
5135 setStreamMute(stream, starting, mPrimaryOutput);
5136 }
5137 } else {
5138 ALOGV("handleIncallSonification() high visibility");
5139 if (outputDesc->device() &
5140 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5141 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5142 for (int i = 0; i < muteCount; i++) {
5143 setStreamMute(stream, starting, mPrimaryOutput);
5144 }
5145 }
5146 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005147 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5148 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005149 } else {
5150 mpClientInterface->stopTone();
5151 }
5152 }
5153 }
5154 }
5155}
5156
Eric Laurente0720872014-03-11 09:30:41 -07005157bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005158{
5159 return isStateInCall(mPhoneState);
5160}
5161
Eric Laurente0720872014-03-11 09:30:41 -07005162bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005163 return ((state == AUDIO_MODE_IN_CALL) ||
5164 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005165}
5166
Eric Laurente0720872014-03-11 09:30:41 -07005167uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005168{
5169 return MAX_EFFECTS_CPU_LOAD;
5170}
5171
Eric Laurente0720872014-03-11 09:30:41 -07005172uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005173{
5174 return MAX_EFFECTS_MEMORY;
5175}
5176
Eric Laurent6a94d692014-05-20 11:18:06 -07005177
Eric Laurente552edb2014-03-10 17:42:56 -07005178// --- AudioOutputDescriptor class implementation
5179
Eric Laurente0720872014-03-11 09:30:41 -07005180AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005181 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005182 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005183 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005184 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5185{
5186 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005187 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005188 mRefCount[i] = 0;
5189 mCurVolume[i] = -1.0;
5190 mMuteCount[i] = 0;
5191 mStopTime[i] = 0;
5192 }
5193 for (int i = 0; i < NUM_STRATEGIES; i++) {
5194 mStrategyMutedByDevice[i] = false;
5195 }
5196 if (profile != NULL) {
Eric Laurentd8622372014-07-27 13:47:31 -07005197 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005198 mSamplingRate = profile->pickSamplingRate();
5199 mFormat = profile->pickFormat();
5200 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005201 if (profile->mGains.size() > 0) {
5202 profile->mGains[0]->getDefaultConfig(&mGain);
5203 }
Eric Laurente552edb2014-03-10 17:42:56 -07005204 }
5205}
5206
Eric Laurente0720872014-03-11 09:30:41 -07005207audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005208{
5209 if (isDuplicated()) {
5210 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5211 } else {
5212 return mDevice;
5213 }
5214}
5215
Eric Laurente0720872014-03-11 09:30:41 -07005216uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005217{
5218 if (isDuplicated()) {
5219 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5220 } else {
5221 return mLatency;
5222 }
5223}
5224
Eric Laurente0720872014-03-11 09:30:41 -07005225bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005226 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005227{
5228 if (isDuplicated()) {
5229 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5230 } else if (outputDesc->isDuplicated()){
5231 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5232 } else {
5233 return (mProfile->mModule == outputDesc->mProfile->mModule);
5234 }
5235}
5236
Eric Laurente0720872014-03-11 09:30:41 -07005237void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005238 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005239{
5240 // forward usage count change to attached outputs
5241 if (isDuplicated()) {
5242 mOutput1->changeRefCount(stream, delta);
5243 mOutput2->changeRefCount(stream, delta);
5244 }
5245 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005246 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5247 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005248 mRefCount[stream] = 0;
5249 return;
5250 }
5251 mRefCount[stream] += delta;
5252 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5253}
5254
Eric Laurente0720872014-03-11 09:30:41 -07005255audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005256{
5257 if (isDuplicated()) {
5258 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5259 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005260 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005261 }
5262}
5263
Eric Laurente0720872014-03-11 09:30:41 -07005264bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005265{
5266 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5267}
5268
Eric Laurente0720872014-03-11 09:30:41 -07005269bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005270 uint32_t inPastMs,
5271 nsecs_t sysTime) const
5272{
5273 if ((sysTime == 0) && (inPastMs != 0)) {
5274 sysTime = systemTime();
5275 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005276 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5277 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005278 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005279 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005280 return true;
5281 }
5282 }
5283 return false;
5284}
5285
Eric Laurente0720872014-03-11 09:30:41 -07005286bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005287 uint32_t inPastMs,
5288 nsecs_t sysTime) const
5289{
5290 if (mRefCount[stream] != 0) {
5291 return true;
5292 }
5293 if (inPastMs == 0) {
5294 return false;
5295 }
5296 if (sysTime == 0) {
5297 sysTime = systemTime();
5298 }
5299 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5300 return true;
5301 }
5302 return false;
5303}
5304
Eric Laurent1c333e22014-05-20 10:48:17 -07005305void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005306 struct audio_port_config *dstConfig,
5307 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005308{
Eric Laurent84c70242014-06-23 08:46:27 -07005309 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5310
Eric Laurent1f2f2232014-06-02 12:01:23 -07005311 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5312 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5313 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005314 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005315 }
5316 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5317
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 dstConfig->id = mId;
5319 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5320 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5322 dstConfig->ext.mix.handle = mIoHandle;
5323 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005324}
5325
5326void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5327 struct audio_port *port) const
5328{
Eric Laurent84c70242014-06-23 08:46:27 -07005329 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005330 mProfile->toAudioPort(port);
5331 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005332 toAudioPortConfig(&port->active_config);
5333 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005334 port->ext.mix.handle = mIoHandle;
5335 port->ext.mix.latency_class =
5336 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5337}
Eric Laurente552edb2014-03-10 17:42:56 -07005338
Eric Laurente0720872014-03-11 09:30:41 -07005339status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005340{
5341 const size_t SIZE = 256;
5342 char buffer[SIZE];
5343 String8 result;
5344
Eric Laurent4d416952014-08-10 14:07:09 -07005345 snprintf(buffer, SIZE, " ID: %d\n", mId);
5346 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005347 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5348 result.append(buffer);
5349 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5350 result.append(buffer);
5351 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5352 result.append(buffer);
5353 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5354 result.append(buffer);
5355 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5356 result.append(buffer);
5357 snprintf(buffer, SIZE, " Devices %08x\n", device());
5358 result.append(buffer);
5359 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5360 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005361 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5362 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5363 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005364 result.append(buffer);
5365 }
5366 write(fd, result.string(), result.size());
5367
5368 return NO_ERROR;
5369}
5370
5371// --- AudioInputDescriptor class implementation
5372
Eric Laurent1c333e22014-05-20 10:48:17 -07005373AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005374 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005375 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005376 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005377{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005378 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005379 mSamplingRate = profile->pickSamplingRate();
5380 mFormat = profile->pickFormat();
5381 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005382 if (profile->mGains.size() > 0) {
5383 profile->mGains[0]->getDefaultConfig(&mGain);
5384 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005385 }
Eric Laurente552edb2014-03-10 17:42:56 -07005386}
5387
Eric Laurent1c333e22014-05-20 10:48:17 -07005388void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005389 struct audio_port_config *dstConfig,
5390 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005391{
Eric Laurent84c70242014-06-23 08:46:27 -07005392 ALOG_ASSERT(mProfile != 0,
5393 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005394 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5395 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5396 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005397 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005398 }
5399
5400 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5401
Eric Laurent6a94d692014-05-20 11:18:06 -07005402 dstConfig->id = mId;
5403 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5404 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005405 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5406 dstConfig->ext.mix.handle = mIoHandle;
5407 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005408}
5409
5410void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5411 struct audio_port *port) const
5412{
Eric Laurent84c70242014-06-23 08:46:27 -07005413 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5414
Eric Laurent1c333e22014-05-20 10:48:17 -07005415 mProfile->toAudioPort(port);
5416 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005417 toAudioPortConfig(&port->active_config);
5418 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005419 port->ext.mix.handle = mIoHandle;
5420 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5421}
5422
Eric Laurente0720872014-03-11 09:30:41 -07005423status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005424{
5425 const size_t SIZE = 256;
5426 char buffer[SIZE];
5427 String8 result;
5428
Eric Laurent4d416952014-08-10 14:07:09 -07005429 snprintf(buffer, SIZE, " ID: %d\n", mId);
5430 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005431 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5432 result.append(buffer);
5433 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5434 result.append(buffer);
5435 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5436 result.append(buffer);
5437 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5438 result.append(buffer);
5439 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5440 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005441 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5442 result.append(buffer);
5443
Eric Laurente552edb2014-03-10 17:42:56 -07005444 write(fd, result.string(), result.size());
5445
5446 return NO_ERROR;
5447}
5448
5449// --- StreamDescriptor class implementation
5450
Eric Laurente0720872014-03-11 09:30:41 -07005451AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005452 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5453{
5454 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5455}
5456
Eric Laurente0720872014-03-11 09:30:41 -07005457int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005458{
Eric Laurente0720872014-03-11 09:30:41 -07005459 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005460 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5461 if (mIndexCur.indexOfKey(device) < 0) {
5462 device = AUDIO_DEVICE_OUT_DEFAULT;
5463 }
5464 return mIndexCur.valueFor(device);
5465}
5466
Eric Laurente0720872014-03-11 09:30:41 -07005467void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005468{
5469 const size_t SIZE = 256;
5470 char buffer[SIZE];
5471 String8 result;
5472
5473 snprintf(buffer, SIZE, "%s %02d %02d ",
5474 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5475 result.append(buffer);
5476 for (size_t i = 0; i < mIndexCur.size(); i++) {
5477 snprintf(buffer, SIZE, "%04x : %02d, ",
5478 mIndexCur.keyAt(i),
5479 mIndexCur.valueAt(i));
5480 result.append(buffer);
5481 }
5482 result.append("\n");
5483
5484 write(fd, result.string(), result.size());
5485}
5486
5487// --- EffectDescriptor class implementation
5488
Eric Laurente0720872014-03-11 09:30:41 -07005489status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005490{
5491 const size_t SIZE = 256;
5492 char buffer[SIZE];
5493 String8 result;
5494
5495 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5496 result.append(buffer);
5497 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5498 result.append(buffer);
5499 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5500 result.append(buffer);
5501 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5502 result.append(buffer);
5503 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5504 result.append(buffer);
5505 write(fd, result.string(), result.size());
5506
5507 return NO_ERROR;
5508}
5509
Eric Laurent1c333e22014-05-20 10:48:17 -07005510// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005511
Eric Laurente0720872014-03-11 09:30:41 -07005512AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005513 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5514 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005515{
5516}
5517
Eric Laurente0720872014-03-11 09:30:41 -07005518AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005519{
5520 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005521 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005522 }
5523 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005524 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005525 }
5526 free((void *)mName);
5527}
5528
Eric Laurent1afeecb2014-05-14 08:52:28 -07005529status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5530{
5531 cnode *node = root->first_child;
5532
5533 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5534
5535 while (node) {
5536 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5537 profile->loadSamplingRates((char *)node->value);
5538 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5539 profile->loadFormats((char *)node->value);
5540 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5541 profile->loadInChannels((char *)node->value);
5542 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5543 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5544 mDeclaredDevices);
5545 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5546 profile->loadGains(node);
5547 }
5548 node = node->next;
5549 }
5550 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5551 "loadInput() invalid supported devices");
5552 ALOGW_IF(profile->mChannelMasks.size() == 0,
5553 "loadInput() invalid supported channel masks");
5554 ALOGW_IF(profile->mSamplingRates.size() == 0,
5555 "loadInput() invalid supported sampling rates");
5556 ALOGW_IF(profile->mFormats.size() == 0,
5557 "loadInput() invalid supported formats");
5558 if (!profile->mSupportedDevices.isEmpty() &&
5559 (profile->mChannelMasks.size() != 0) &&
5560 (profile->mSamplingRates.size() != 0) &&
5561 (profile->mFormats.size() != 0)) {
5562
5563 ALOGV("loadInput() adding input Supported Devices %04x",
5564 profile->mSupportedDevices.types());
5565
5566 mInputProfiles.add(profile);
5567 return NO_ERROR;
5568 } else {
5569 return BAD_VALUE;
5570 }
5571}
5572
5573status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5574{
5575 cnode *node = root->first_child;
5576
5577 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5578
5579 while (node) {
5580 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5581 profile->loadSamplingRates((char *)node->value);
5582 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5583 profile->loadFormats((char *)node->value);
5584 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5585 profile->loadOutChannels((char *)node->value);
5586 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5587 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5588 mDeclaredDevices);
5589 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5590 profile->mFlags = parseFlagNames((char *)node->value);
5591 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5592 profile->loadGains(node);
5593 }
5594 node = node->next;
5595 }
5596 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5597 "loadOutput() invalid supported devices");
5598 ALOGW_IF(profile->mChannelMasks.size() == 0,
5599 "loadOutput() invalid supported channel masks");
5600 ALOGW_IF(profile->mSamplingRates.size() == 0,
5601 "loadOutput() invalid supported sampling rates");
5602 ALOGW_IF(profile->mFormats.size() == 0,
5603 "loadOutput() invalid supported formats");
5604 if (!profile->mSupportedDevices.isEmpty() &&
5605 (profile->mChannelMasks.size() != 0) &&
5606 (profile->mSamplingRates.size() != 0) &&
5607 (profile->mFormats.size() != 0)) {
5608
5609 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5610 profile->mSupportedDevices.types(), profile->mFlags);
5611
5612 mOutputProfiles.add(profile);
5613 return NO_ERROR;
5614 } else {
5615 return BAD_VALUE;
5616 }
5617}
5618
5619status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5620{
5621 cnode *node = root->first_child;
5622
5623 audio_devices_t type = AUDIO_DEVICE_NONE;
5624 while (node) {
5625 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5626 type = parseDeviceNames((char *)node->value);
5627 break;
5628 }
5629 node = node->next;
5630 }
5631 if (type == AUDIO_DEVICE_NONE ||
5632 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5633 ALOGW("loadDevice() bad type %08x", type);
5634 return BAD_VALUE;
5635 }
5636 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5637 deviceDesc->mModule = this;
5638
5639 node = root->first_child;
5640 while (node) {
5641 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5642 deviceDesc->mAddress = String8((char *)node->value);
5643 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5644 if (audio_is_input_device(type)) {
5645 deviceDesc->loadInChannels((char *)node->value);
5646 } else {
5647 deviceDesc->loadOutChannels((char *)node->value);
5648 }
5649 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5650 deviceDesc->loadGains(node);
5651 }
5652 node = node->next;
5653 }
5654
5655 ALOGV("loadDevice() adding device name %s type %08x address %s",
5656 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5657
5658 mDeclaredDevices.add(deviceDesc);
5659
5660 return NO_ERROR;
5661}
5662
Eric Laurente0720872014-03-11 09:30:41 -07005663void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005664{
5665 const size_t SIZE = 256;
5666 char buffer[SIZE];
5667 String8 result;
5668
5669 snprintf(buffer, SIZE, " - name: %s\n", mName);
5670 result.append(buffer);
5671 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5672 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005673 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5674 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005675 write(fd, result.string(), result.size());
5676 if (mOutputProfiles.size()) {
5677 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5678 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005679 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005680 write(fd, buffer, strlen(buffer));
5681 mOutputProfiles[i]->dump(fd);
5682 }
5683 }
5684 if (mInputProfiles.size()) {
5685 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5686 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005687 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005688 write(fd, buffer, strlen(buffer));
5689 mInputProfiles[i]->dump(fd);
5690 }
5691 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005692 if (mDeclaredDevices.size()) {
5693 write(fd, " - devices:\n", strlen(" - devices:\n"));
5694 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5695 mDeclaredDevices[i]->dump(fd, 4, i);
5696 }
5697 }
Eric Laurente552edb2014-03-10 17:42:56 -07005698}
5699
Eric Laurent1c333e22014-05-20 10:48:17 -07005700// --- AudioPort class implementation
5701
Eric Laurenta121f902014-06-03 13:32:54 -07005702
5703AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5704 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005705 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005706{
5707 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5708 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5709}
5710
Eric Laurent1c333e22014-05-20 10:48:17 -07005711void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5712{
5713 port->role = mRole;
5714 port->type = mType;
5715 unsigned int i;
5716 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005717 if (mSamplingRates[i] != 0) {
5718 port->sample_rates[i] = mSamplingRates[i];
5719 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005720 }
5721 port->num_sample_rates = i;
5722 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005723 if (mChannelMasks[i] != 0) {
5724 port->channel_masks[i] = mChannelMasks[i];
5725 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005726 }
5727 port->num_channel_masks = i;
5728 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005729 if (mFormats[i] != 0) {
5730 port->formats[i] = mFormats[i];
5731 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005732 }
5733 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005734
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005735 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005736
5737 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5738 port->gains[i] = mGains[i]->mGain;
5739 }
5740 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005741}
5742
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005743void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5744 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5745 const uint32_t rate = port->mSamplingRates.itemAt(k);
5746 if (rate != 0) { // skip "dynamic" rates
5747 bool hasRate = false;
5748 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5749 if (rate == mSamplingRates.itemAt(l)) {
5750 hasRate = true;
5751 break;
5752 }
5753 }
5754 if (!hasRate) { // never import a sampling rate twice
5755 mSamplingRates.add(rate);
5756 }
5757 }
5758 }
5759 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5760 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5761 if (mask != 0) { // skip "dynamic" masks
5762 bool hasMask = false;
5763 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5764 if (mask == mChannelMasks.itemAt(l)) {
5765 hasMask = true;
5766 break;
5767 }
5768 }
5769 if (!hasMask) { // never import a channel mask twice
5770 mChannelMasks.add(mask);
5771 }
5772 }
5773 }
5774 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5775 const audio_format_t format = port->mFormats.itemAt(k);
5776 if (format != 0) { // skip "dynamic" formats
5777 bool hasFormat = false;
5778 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5779 if (format == mFormats.itemAt(l)) {
5780 hasFormat = true;
5781 break;
5782 }
5783 }
5784 if (!hasFormat) { // never import a channel mask twice
5785 mFormats.add(format);
5786 }
5787 }
5788 }
5789}
5790
5791void AudioPolicyManager::AudioPort::clearCapabilities() {
5792 mChannelMasks.clear();
5793 mFormats.clear();
5794 mSamplingRates.clear();
5795}
Eric Laurent1c333e22014-05-20 10:48:17 -07005796
5797void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5798{
5799 char *str = strtok(name, "|");
5800
5801 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5802 // rates should be read from the output stream after it is opened for the first time
5803 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5804 mSamplingRates.add(0);
5805 return;
5806 }
5807
5808 while (str != NULL) {
5809 uint32_t rate = atoi(str);
5810 if (rate != 0) {
5811 ALOGV("loadSamplingRates() adding rate %d", rate);
5812 mSamplingRates.add(rate);
5813 }
5814 str = strtok(NULL, "|");
5815 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005816}
5817
5818void AudioPolicyManager::AudioPort::loadFormats(char *name)
5819{
5820 char *str = strtok(name, "|");
5821
5822 // by convention, "0' in the first entry in mFormats indicates the supported formats
5823 // should be read from the output stream after it is opened for the first time
5824 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5825 mFormats.add(AUDIO_FORMAT_DEFAULT);
5826 return;
5827 }
5828
5829 while (str != NULL) {
5830 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5831 ARRAY_SIZE(sFormatNameToEnumTable),
5832 str);
5833 if (format != AUDIO_FORMAT_DEFAULT) {
5834 mFormats.add(format);
5835 }
5836 str = strtok(NULL, "|");
5837 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005838}
5839
5840void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5841{
5842 const char *str = strtok(name, "|");
5843
5844 ALOGV("loadInChannels() %s", name);
5845
5846 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5847 mChannelMasks.add(0);
5848 return;
5849 }
5850
5851 while (str != NULL) {
5852 audio_channel_mask_t channelMask =
5853 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5854 ARRAY_SIZE(sInChannelsNameToEnumTable),
5855 str);
5856 if (channelMask != 0) {
5857 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5858 mChannelMasks.add(channelMask);
5859 }
5860 str = strtok(NULL, "|");
5861 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005862}
5863
5864void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5865{
5866 const char *str = strtok(name, "|");
5867
5868 ALOGV("loadOutChannels() %s", name);
5869
5870 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5871 // masks should be read from the output stream after it is opened for the first time
5872 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5873 mChannelMasks.add(0);
5874 return;
5875 }
5876
5877 while (str != NULL) {
5878 audio_channel_mask_t channelMask =
5879 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5880 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5881 str);
5882 if (channelMask != 0) {
5883 mChannelMasks.add(channelMask);
5884 }
5885 str = strtok(NULL, "|");
5886 }
5887 return;
5888}
5889
Eric Laurent1afeecb2014-05-14 08:52:28 -07005890audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5891{
5892 const char *str = strtok(name, "|");
5893
5894 ALOGV("loadGainMode() %s", name);
5895 audio_gain_mode_t mode = 0;
5896 while (str != NULL) {
5897 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5898 ARRAY_SIZE(sGainModeNameToEnumTable),
5899 str);
5900 str = strtok(NULL, "|");
5901 }
5902 return mode;
5903}
5904
Eric Laurenta121f902014-06-03 13:32:54 -07005905void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005906{
5907 cnode *node = root->first_child;
5908
Eric Laurenta121f902014-06-03 13:32:54 -07005909 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005910
5911 while (node) {
5912 if (strcmp(node->name, GAIN_MODE) == 0) {
5913 gain->mGain.mode = loadGainMode((char *)node->value);
5914 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005915 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005916 gain->mGain.channel_mask =
5917 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5918 ARRAY_SIZE(sInChannelsNameToEnumTable),
5919 (char *)node->value);
5920 } else {
5921 gain->mGain.channel_mask =
5922 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5923 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5924 (char *)node->value);
5925 }
5926 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5927 gain->mGain.min_value = atoi((char *)node->value);
5928 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5929 gain->mGain.max_value = atoi((char *)node->value);
5930 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5931 gain->mGain.default_value = atoi((char *)node->value);
5932 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5933 gain->mGain.step_value = atoi((char *)node->value);
5934 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5935 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5936 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5937 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5938 }
5939 node = node->next;
5940 }
5941
5942 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5943 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5944
5945 if (gain->mGain.mode == 0) {
5946 return;
5947 }
5948 mGains.add(gain);
5949}
5950
5951void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5952{
5953 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005954 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005955 while (node) {
5956 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005957 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005958 node = node->next;
5959 }
5960}
5961
Glenn Kastencbd48022014-07-24 13:46:44 -07005962status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005963{
5964 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5965 if (mSamplingRates[i] == samplingRate) {
5966 return NO_ERROR;
5967 }
5968 }
5969 return BAD_VALUE;
5970}
5971
Glenn Kastencbd48022014-07-24 13:46:44 -07005972status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5973 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005974{
Glenn Kastencbd48022014-07-24 13:46:44 -07005975 // Search for the closest supported sampling rate that is above (preferred)
5976 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5977 // The sampling rates do not need to be sorted in ascending order.
5978 ssize_t maxBelow = -1;
5979 ssize_t minAbove = -1;
5980 uint32_t candidate;
5981 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5982 candidate = mSamplingRates[i];
5983 if (candidate == samplingRate) {
5984 if (updatedSamplingRate != NULL) {
5985 *updatedSamplingRate = candidate;
5986 }
5987 return NO_ERROR;
5988 }
5989 // candidate < desired
5990 if (candidate < samplingRate) {
5991 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5992 maxBelow = i;
5993 }
5994 // candidate > desired
5995 } else {
5996 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5997 minAbove = i;
5998 }
5999 }
6000 }
6001 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6002 // TODO Move these assumptions out.
6003 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6004 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6005 // due to approximation by an int32_t of the
6006 // phase increments
6007 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6008 if (minAbove >= 0) {
6009 candidate = mSamplingRates[minAbove];
6010 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6011 if (updatedSamplingRate != NULL) {
6012 *updatedSamplingRate = candidate;
6013 }
6014 return NO_ERROR;
6015 }
6016 }
6017 // But if we have to up-sample from a lower sampling rate, that's OK.
6018 if (maxBelow >= 0) {
6019 candidate = mSamplingRates[maxBelow];
6020 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6021 if (updatedSamplingRate != NULL) {
6022 *updatedSamplingRate = candidate;
6023 }
6024 return NO_ERROR;
6025 }
6026 }
6027 // leave updatedSamplingRate unmodified
6028 return BAD_VALUE;
6029}
6030
6031status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6032{
6033 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006034 if (mChannelMasks[i] == channelMask) {
6035 return NO_ERROR;
6036 }
6037 }
6038 return BAD_VALUE;
6039}
6040
Glenn Kastencbd48022014-07-24 13:46:44 -07006041status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6042 const
6043{
6044 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6045 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6046 // FIXME Does not handle multi-channel automatic conversions yet
6047 audio_channel_mask_t supported = mChannelMasks[i];
6048 if (supported == channelMask) {
6049 return NO_ERROR;
6050 }
6051 if (isRecordThread) {
6052 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6053 // FIXME Abstract this out to a table.
6054 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6055 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6056 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6057 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6058 return NO_ERROR;
6059 }
6060 }
6061 }
6062 return BAD_VALUE;
6063}
6064
Eric Laurenta121f902014-06-03 13:32:54 -07006065status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6066{
6067 for (size_t i = 0; i < mFormats.size(); i ++) {
6068 if (mFormats[i] == format) {
6069 return NO_ERROR;
6070 }
6071 }
6072 return BAD_VALUE;
6073}
6074
Eric Laurent1e693b52014-07-09 15:03:28 -07006075
6076uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6077{
6078 // special case for uninitialized dynamic profile
6079 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6080 return 0;
6081 }
6082
Eric Laurent828bcff2014-09-07 12:26:06 -07006083 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6084 // channel count / sampling rate combination chosen will be supported by the connected
6085 // sink
6086 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6087 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6088 uint32_t samplingRate = UINT_MAX;
6089 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6090 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6091 samplingRate = mSamplingRates[i];
6092 }
6093 }
6094 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6095 }
6096
Eric Laurent1e693b52014-07-09 15:03:28 -07006097 uint32_t samplingRate = 0;
6098 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6099
6100 // For mixed output and inputs, use max mixer sampling rates. Do not
6101 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006102 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006103 maxRate = UINT_MAX;
6104 }
6105 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6106 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6107 samplingRate = mSamplingRates[i];
6108 }
6109 }
6110 return samplingRate;
6111}
6112
6113audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6114{
6115 // special case for uninitialized dynamic profile
6116 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6117 return AUDIO_CHANNEL_NONE;
6118 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006119 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006120
6121 // For direct outputs, pick minimum channel count: this helps ensuring that the
6122 // channel count / sampling rate combination chosen will be supported by the connected
6123 // sink
6124 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6125 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6126 uint32_t channelCount = UINT_MAX;
6127 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6128 uint32_t cnlCount;
6129 if (mUseInChannelMask) {
6130 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6131 } else {
6132 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6133 }
6134 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6135 channelMask = mChannelMasks[i];
6136 channelCount = cnlCount;
6137 }
6138 }
6139 return channelMask;
6140 }
6141
Eric Laurent1e693b52014-07-09 15:03:28 -07006142 uint32_t channelCount = 0;
6143 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6144
6145 // For mixed output and inputs, use max mixer channel count. Do not
6146 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006147 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006148 maxCount = UINT_MAX;
6149 }
6150 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6151 uint32_t cnlCount;
6152 if (mUseInChannelMask) {
6153 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6154 } else {
6155 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6156 }
6157 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6158 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006159 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006160 }
6161 }
6162 return channelMask;
6163}
6164
Andy Hung9a605382014-07-28 16:16:31 -07006165/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006166const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6167 AUDIO_FORMAT_DEFAULT,
6168 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006169 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006170 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006171 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006172 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006173};
6174
6175int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6176 audio_format_t format2)
6177{
6178 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6179 // compressed format and better than any PCM format. This is by design of pickFormat()
6180 if (!audio_is_linear_pcm(format1)) {
6181 if (!audio_is_linear_pcm(format2)) {
6182 return 0;
6183 }
6184 return 1;
6185 }
6186 if (!audio_is_linear_pcm(format2)) {
6187 return -1;
6188 }
6189
6190 int index1 = -1, index2 = -1;
6191 for (size_t i = 0;
6192 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6193 i ++) {
6194 if (sPcmFormatCompareTable[i] == format1) {
6195 index1 = i;
6196 }
6197 if (sPcmFormatCompareTable[i] == format2) {
6198 index2 = i;
6199 }
6200 }
6201 // format1 not found => index1 < 0 => format2 > format1
6202 // format2 not found => index2 < 0 => format2 < format1
6203 return index1 - index2;
6204}
6205
6206audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6207{
6208 // special case for uninitialized dynamic profile
6209 if (mFormats.size() == 1 && mFormats[0] == 0) {
6210 return AUDIO_FORMAT_DEFAULT;
6211 }
6212
6213 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006214 audio_format_t bestFormat =
6215 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6216 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006217 // For mixed output and inputs, use best mixer output format. Do not
6218 // limit format otherwise
6219 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6220 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006221 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006222 bestFormat = AUDIO_FORMAT_INVALID;
6223 }
6224
6225 for (size_t i = 0; i < mFormats.size(); i ++) {
6226 if ((compareFormats(mFormats[i], format) > 0) &&
6227 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6228 format = mFormats[i];
6229 }
6230 }
6231 return format;
6232}
6233
Eric Laurenta121f902014-06-03 13:32:54 -07006234status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6235 int index) const
6236{
6237 if (index < 0 || (size_t)index >= mGains.size()) {
6238 return BAD_VALUE;
6239 }
6240 return mGains[index]->checkConfig(gainConfig);
6241}
6242
Eric Laurent1afeecb2014-05-14 08:52:28 -07006243void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6244{
6245 const size_t SIZE = 256;
6246 char buffer[SIZE];
6247 String8 result;
6248
6249 if (mName.size() != 0) {
6250 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6251 result.append(buffer);
6252 }
6253
6254 if (mSamplingRates.size() != 0) {
6255 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6256 result.append(buffer);
6257 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006258 if (i == 0 && mSamplingRates[i] == 0) {
6259 snprintf(buffer, SIZE, "Dynamic");
6260 } else {
6261 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6262 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006263 result.append(buffer);
6264 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6265 }
6266 result.append("\n");
6267 }
6268
6269 if (mChannelMasks.size() != 0) {
6270 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6271 result.append(buffer);
6272 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006273 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6274
6275 if (i == 0 && mChannelMasks[i] == 0) {
6276 snprintf(buffer, SIZE, "Dynamic");
6277 } else {
6278 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6279 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006280 result.append(buffer);
6281 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6282 }
6283 result.append("\n");
6284 }
6285
6286 if (mFormats.size() != 0) {
6287 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6288 result.append(buffer);
6289 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006290 const char *formatStr = enumToString(sFormatNameToEnumTable,
6291 ARRAY_SIZE(sFormatNameToEnumTable),
6292 mFormats[i]);
6293 if (i == 0 && strcmp(formatStr, "") == 0) {
6294 snprintf(buffer, SIZE, "Dynamic");
6295 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006296 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006297 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006298 result.append(buffer);
6299 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6300 }
6301 result.append("\n");
6302 }
6303 write(fd, result.string(), result.size());
6304 if (mGains.size() != 0) {
6305 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6306 write(fd, buffer, strlen(buffer) + 1);
6307 result.append(buffer);
6308 for (size_t i = 0; i < mGains.size(); i++) {
6309 mGains[i]->dump(fd, spaces + 2, i);
6310 }
6311 }
6312}
6313
6314// --- AudioGain class implementation
6315
Eric Laurenta121f902014-06-03 13:32:54 -07006316AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006317{
Eric Laurenta121f902014-06-03 13:32:54 -07006318 mIndex = index;
6319 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006320 memset(&mGain, 0, sizeof(struct audio_gain));
6321}
6322
Eric Laurenta121f902014-06-03 13:32:54 -07006323void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6324{
6325 config->index = mIndex;
6326 config->mode = mGain.mode;
6327 config->channel_mask = mGain.channel_mask;
6328 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6329 config->values[0] = mGain.default_value;
6330 } else {
6331 uint32_t numValues;
6332 if (mUseInChannelMask) {
6333 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6334 } else {
6335 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6336 }
6337 for (size_t i = 0; i < numValues; i++) {
6338 config->values[i] = mGain.default_value;
6339 }
6340 }
6341 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6342 config->ramp_duration_ms = mGain.min_ramp_ms;
6343 }
6344}
6345
6346status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6347{
6348 if ((config->mode & ~mGain.mode) != 0) {
6349 return BAD_VALUE;
6350 }
6351 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6352 if ((config->values[0] < mGain.min_value) ||
6353 (config->values[0] > mGain.max_value)) {
6354 return BAD_VALUE;
6355 }
6356 } else {
6357 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6358 return BAD_VALUE;
6359 }
6360 uint32_t numValues;
6361 if (mUseInChannelMask) {
6362 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6363 } else {
6364 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6365 }
6366 for (size_t i = 0; i < numValues; i++) {
6367 if ((config->values[i] < mGain.min_value) ||
6368 (config->values[i] > mGain.max_value)) {
6369 return BAD_VALUE;
6370 }
6371 }
6372 }
6373 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6374 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6375 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6376 return BAD_VALUE;
6377 }
6378 }
6379 return NO_ERROR;
6380}
6381
Eric Laurent1afeecb2014-05-14 08:52:28 -07006382void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6383{
6384 const size_t SIZE = 256;
6385 char buffer[SIZE];
6386 String8 result;
6387
6388 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6389 result.append(buffer);
6390 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6391 result.append(buffer);
6392 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6393 result.append(buffer);
6394 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6395 result.append(buffer);
6396 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6397 result.append(buffer);
6398 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6399 result.append(buffer);
6400 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6401 result.append(buffer);
6402 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6403 result.append(buffer);
6404 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6405 result.append(buffer);
6406
6407 write(fd, result.string(), result.size());
6408}
6409
Eric Laurent1f2f2232014-06-02 12:01:23 -07006410// --- AudioPortConfig class implementation
6411
6412AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6413{
6414 mSamplingRate = 0;
6415 mChannelMask = AUDIO_CHANNEL_NONE;
6416 mFormat = AUDIO_FORMAT_INVALID;
6417 mGain.index = -1;
6418}
6419
Eric Laurenta121f902014-06-03 13:32:54 -07006420status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6421 const struct audio_port_config *config,
6422 struct audio_port_config *backupConfig)
6423{
6424 struct audio_port_config localBackupConfig;
6425 status_t status = NO_ERROR;
6426
6427 localBackupConfig.config_mask = config->config_mask;
6428 toAudioPortConfig(&localBackupConfig);
6429
Marco Nelissen961ec212014-08-25 15:58:39 -07006430 sp<AudioPort> audioport = getAudioPort();
6431 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006432 status = NO_INIT;
6433 goto exit;
6434 }
6435 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006436 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006437 if (status != NO_ERROR) {
6438 goto exit;
6439 }
6440 mSamplingRate = config->sample_rate;
6441 }
6442 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006443 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006444 if (status != NO_ERROR) {
6445 goto exit;
6446 }
6447 mChannelMask = config->channel_mask;
6448 }
6449 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006450 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006451 if (status != NO_ERROR) {
6452 goto exit;
6453 }
6454 mFormat = config->format;
6455 }
6456 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006457 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006458 if (status != NO_ERROR) {
6459 goto exit;
6460 }
6461 mGain = config->gain;
6462 }
6463
6464exit:
6465 if (status != NO_ERROR) {
6466 applyAudioPortConfig(&localBackupConfig);
6467 }
6468 if (backupConfig != NULL) {
6469 *backupConfig = localBackupConfig;
6470 }
6471 return status;
6472}
6473
Eric Laurent1f2f2232014-06-02 12:01:23 -07006474void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6475 struct audio_port_config *dstConfig,
6476 const struct audio_port_config *srcConfig) const
6477{
6478 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6479 dstConfig->sample_rate = mSamplingRate;
6480 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6481 dstConfig->sample_rate = srcConfig->sample_rate;
6482 }
6483 } else {
6484 dstConfig->sample_rate = 0;
6485 }
6486 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6487 dstConfig->channel_mask = mChannelMask;
6488 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6489 dstConfig->channel_mask = srcConfig->channel_mask;
6490 }
6491 } else {
6492 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6493 }
6494 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6495 dstConfig->format = mFormat;
6496 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6497 dstConfig->format = srcConfig->format;
6498 }
6499 } else {
6500 dstConfig->format = AUDIO_FORMAT_INVALID;
6501 }
6502 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6503 dstConfig->gain = mGain;
6504 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6505 dstConfig->gain = srcConfig->gain;
6506 }
6507 } else {
6508 dstConfig->gain.index = -1;
6509 }
6510 if (dstConfig->gain.index != -1) {
6511 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6512 } else {
6513 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6514 }
6515}
6516
Eric Laurent1c333e22014-05-20 10:48:17 -07006517// --- IOProfile class implementation
6518
Eric Laurent1afeecb2014-05-14 08:52:28 -07006519AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006520 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006521 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006522{
6523}
6524
Eric Laurente0720872014-03-11 09:30:41 -07006525AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006526{
6527}
6528
6529// checks if the IO profile is compatible with specified parameters.
6530// Sampling rate, format and channel mask must be specified in order to
6531// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006532bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006533 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006534 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006535 audio_format_t format,
6536 audio_channel_mask_t channelMask,
6537 audio_output_flags_t flags) const
6538{
Glenn Kastencbd48022014-07-24 13:46:44 -07006539 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6540 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6541 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006542
Glenn Kastencbd48022014-07-24 13:46:44 -07006543 if ((mSupportedDevices.types() & device) != device) {
6544 return false;
6545 }
6546
6547 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006548 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006549 }
6550 uint32_t myUpdatedSamplingRate = samplingRate;
6551 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006552 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006553 }
6554 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6555 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006556 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006557 }
6558
6559 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6560 return false;
6561 }
6562
6563 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6564 checkExactChannelMask(channelMask) != NO_ERROR)) {
6565 return false;
6566 }
6567 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6568 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6569 return false;
6570 }
6571
6572 if (isPlaybackThread && (mFlags & flags) != flags) {
6573 return false;
6574 }
6575 // The only input flag that is allowed to be different is the fast flag.
6576 // An existing fast stream is compatible with a normal track request.
6577 // An existing normal stream is compatible with a fast track request,
6578 // but the fast request will be denied by AudioFlinger and converted to normal track.
6579 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6580 ~AUDIO_INPUT_FLAG_FAST)) {
6581 return false;
6582 }
6583
6584 if (updatedSamplingRate != NULL) {
6585 *updatedSamplingRate = myUpdatedSamplingRate;
6586 }
6587 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006588}
6589
Eric Laurente0720872014-03-11 09:30:41 -07006590void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006591{
6592 const size_t SIZE = 256;
6593 char buffer[SIZE];
6594 String8 result;
6595
Eric Laurent1afeecb2014-05-14 08:52:28 -07006596 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006597
Eric Laurente552edb2014-03-10 17:42:56 -07006598 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6599 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006600 snprintf(buffer, SIZE, " - devices:\n");
6601 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006602 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006603 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6604 mSupportedDevices[i]->dump(fd, 6, i);
6605 }
Eric Laurente552edb2014-03-10 17:42:56 -07006606}
6607
Eric Laurentd4692962014-05-05 18:13:44 -07006608void AudioPolicyManager::IOProfile::log()
6609{
6610 const size_t SIZE = 256;
6611 char buffer[SIZE];
6612 String8 result;
6613
6614 ALOGV(" - sampling rates: ");
6615 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6616 ALOGV(" %d", mSamplingRates[i]);
6617 }
6618
6619 ALOGV(" - channel masks: ");
6620 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6621 ALOGV(" 0x%04x", mChannelMasks[i]);
6622 }
6623
6624 ALOGV(" - formats: ");
6625 for (size_t i = 0; i < mFormats.size(); i++) {
6626 ALOGV(" 0x%08x", mFormats[i]);
6627 }
6628
6629 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6630 ALOGV(" - flags: 0x%04x\n", mFlags);
6631}
6632
6633
Eric Laurent3a4311c2014-03-17 12:00:47 -07006634// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006635
Eric Laurent1f2f2232014-06-02 12:01:23 -07006636
6637AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6638 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6639 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6640 AUDIO_PORT_ROLE_SOURCE,
6641 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006642 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006643{
Eric Laurenta121f902014-06-03 13:32:54 -07006644 if (mGains.size() > 0) {
6645 mGains[0]->getDefaultConfig(&mGain);
6646 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006647}
6648
Eric Laurent3a4311c2014-03-17 12:00:47 -07006649bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006650{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006651 // Devices are considered equal if they:
6652 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6653 // - have the same address or one device does not specify the address
6654 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006655 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006656 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006657 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006658 mChannelMask == other->mChannelMask);
6659}
6660
6661void AudioPolicyManager::DeviceVector::refreshTypes()
6662{
Eric Laurent1c333e22014-05-20 10:48:17 -07006663 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006664 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006665 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006666 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006667 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006668}
6669
6670ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6671{
6672 for(size_t i = 0; i < size(); i++) {
6673 if (item->equals(itemAt(i))) {
6674 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006675 }
6676 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006677 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006678}
6679
Eric Laurent3a4311c2014-03-17 12:00:47 -07006680ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006681{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006682 ssize_t ret = indexOf(item);
6683
6684 if (ret < 0) {
6685 ret = SortedVector::add(item);
6686 if (ret >= 0) {
6687 refreshTypes();
6688 }
6689 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006690 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006691 ret = -1;
6692 }
6693 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006694}
6695
Eric Laurent3a4311c2014-03-17 12:00:47 -07006696ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6697{
6698 size_t i;
6699 ssize_t ret = indexOf(item);
6700
6701 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006702 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006703 } else {
6704 ret = SortedVector::removeAt(ret);
6705 if (ret >= 0) {
6706 refreshTypes();
6707 }
6708 }
6709 return ret;
6710}
6711
6712void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6713{
6714 DeviceVector deviceList;
6715
6716 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6717 types &= ~role_bit;
6718
6719 while (types) {
6720 uint32_t i = 31 - __builtin_clz(types);
6721 uint32_t type = 1 << i;
6722 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006723 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006724 }
6725}
6726
Eric Laurent1afeecb2014-05-14 08:52:28 -07006727void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6728 const DeviceVector& declaredDevices)
6729{
6730 char *devName = strtok(name, "|");
6731 while (devName != NULL) {
6732 if (strlen(devName) != 0) {
6733 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6734 ARRAY_SIZE(sDeviceNameToEnumTable),
6735 devName);
6736 if (type != AUDIO_DEVICE_NONE) {
6737 add(new DeviceDescriptor(String8(""), type));
6738 } else {
6739 sp<DeviceDescriptor> deviceDesc =
6740 declaredDevices.getDeviceFromName(String8(devName));
6741 if (deviceDesc != 0) {
6742 add(deviceDesc);
6743 }
6744 }
6745 }
6746 devName = strtok(NULL, "|");
6747 }
6748}
6749
Eric Laurent1c333e22014-05-20 10:48:17 -07006750sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6751 audio_devices_t type, String8 address) const
6752{
6753 sp<DeviceDescriptor> device;
6754 for (size_t i = 0; i < size(); i++) {
6755 if (itemAt(i)->mDeviceType == type) {
6756 device = itemAt(i);
6757 if (itemAt(i)->mAddress = address) {
6758 break;
6759 }
6760 }
6761 }
6762 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6763 type, address.string(), device.get());
6764 return device;
6765}
6766
Eric Laurent6a94d692014-05-20 11:18:06 -07006767sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6768 audio_port_handle_t id) const
6769{
6770 sp<DeviceDescriptor> device;
6771 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006772 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006773 if (itemAt(i)->mId == id) {
6774 device = itemAt(i);
6775 break;
6776 }
6777 }
6778 return device;
6779}
6780
Eric Laurent1c333e22014-05-20 10:48:17 -07006781AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6782 audio_devices_t type) const
6783{
6784 DeviceVector devices;
6785 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6786 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6787 devices.add(itemAt(i));
6788 type &= ~itemAt(i)->mDeviceType;
6789 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6790 itemAt(i)->mDeviceType, itemAt(i).get());
6791 }
6792 }
6793 return devices;
6794}
6795
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006796AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6797 audio_devices_t type, String8 address) const
6798{
6799 DeviceVector devices;
6800 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6801 for (size_t i = 0; i < size(); i++) {
6802 //ALOGV(" at i=%d: device=%x, addr=%s",
6803 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6804 if (itemAt(i)->mDeviceType == type) {
6805 if (itemAt(i)->mAddress == address) {
6806 //ALOGV(" found matching address %s", address.string());
6807 devices.add(itemAt(i));
6808 }
6809 }
6810 }
6811 return devices;
6812}
6813
Eric Laurent1afeecb2014-05-14 08:52:28 -07006814sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6815 const String8& name) const
6816{
6817 sp<DeviceDescriptor> device;
6818 for (size_t i = 0; i < size(); i++) {
6819 if (itemAt(i)->mName == name) {
6820 device = itemAt(i);
6821 break;
6822 }
6823 }
6824 return device;
6825}
6826
Eric Laurent6a94d692014-05-20 11:18:06 -07006827void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6828 struct audio_port_config *dstConfig,
6829 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006830{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006831 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6832 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006833 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006834 }
6835
6836 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6837
Eric Laurent6a94d692014-05-20 11:18:06 -07006838 dstConfig->id = mId;
6839 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006840 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006841 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006842 dstConfig->ext.device.type = mDeviceType;
6843 dstConfig->ext.device.hw_module = mModule->mHandle;
6844 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006845}
6846
6847void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6848{
Eric Laurent83b88082014-06-20 18:31:16 -07006849 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006850 AudioPort::toAudioPort(port);
6851 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006852 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006853 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006854 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006855 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6856}
6857
Eric Laurent1afeecb2014-05-14 08:52:28 -07006858status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006859{
6860 const size_t SIZE = 256;
6861 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006862 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006863
Eric Laurent1afeecb2014-05-14 08:52:28 -07006864 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6865 result.append(buffer);
6866 if (mId != 0) {
6867 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6868 result.append(buffer);
6869 }
6870 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6871 enumToString(sDeviceNameToEnumTable,
6872 ARRAY_SIZE(sDeviceNameToEnumTable),
6873 mDeviceType));
6874 result.append(buffer);
6875 if (mAddress.size() != 0) {
6876 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6877 result.append(buffer);
6878 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006879 write(fd, result.string(), result.size());
6880 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006881
6882 return NO_ERROR;
6883}
6884
Eric Laurent4d416952014-08-10 14:07:09 -07006885status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6886{
6887 const size_t SIZE = 256;
6888 char buffer[SIZE];
6889 String8 result;
6890
6891
6892 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6893 result.append(buffer);
6894 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6895 result.append(buffer);
6896 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6897 result.append(buffer);
6898 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6899 result.append(buffer);
6900 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6901 result.append(buffer);
6902 for (size_t i = 0; i < mPatch.num_sources; i++) {
6903 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6904 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6905 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6906 ARRAY_SIZE(sDeviceNameToEnumTable),
6907 mPatch.sources[i].ext.device.type));
6908 } else {
6909 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6910 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6911 }
6912 result.append(buffer);
6913 }
6914 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6915 result.append(buffer);
6916 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6917 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
6918 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6919 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
6920 ARRAY_SIZE(sDeviceNameToEnumTable),
6921 mPatch.sinks[i].ext.device.type));
6922 } else {
6923 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6924 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
6925 }
6926 result.append(buffer);
6927 }
6928
6929 write(fd, result.string(), result.size());
6930 return NO_ERROR;
6931}
Eric Laurent3a4311c2014-03-17 12:00:47 -07006932
6933// --- audio_policy.conf file parsing
6934
Eric Laurente0720872014-03-11 09:30:41 -07006935audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006936{
6937 uint32_t flag = 0;
6938
6939 // it is OK to cast name to non const here as we are not going to use it after
6940 // strtok() modifies it
6941 char *flagName = strtok(name, "|");
6942 while (flagName != NULL) {
6943 if (strlen(flagName) != 0) {
6944 flag |= stringToEnum(sFlagNameToEnumTable,
6945 ARRAY_SIZE(sFlagNameToEnumTable),
6946 flagName);
6947 }
6948 flagName = strtok(NULL, "|");
6949 }
6950 //force direct flag if offload flag is set: offloading implies a direct output stream
6951 // and all common behaviors are driven by checking only the direct flag
6952 // this should normally be set appropriately in the policy configuration file
6953 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6954 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6955 }
6956
6957 return (audio_output_flags_t)flag;
6958}
6959
Eric Laurente0720872014-03-11 09:30:41 -07006960audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006961{
6962 uint32_t device = 0;
6963
6964 char *devName = strtok(name, "|");
6965 while (devName != NULL) {
6966 if (strlen(devName) != 0) {
6967 device |= stringToEnum(sDeviceNameToEnumTable,
6968 ARRAY_SIZE(sDeviceNameToEnumTable),
6969 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006970 }
Eric Laurente552edb2014-03-10 17:42:56 -07006971 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006972 }
Eric Laurente552edb2014-03-10 17:42:56 -07006973 return device;
6974}
6975
Eric Laurente0720872014-03-11 09:30:41 -07006976void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006977{
Eric Laurente552edb2014-03-10 17:42:56 -07006978 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006979 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006980 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006981
Eric Laurent1afeecb2014-05-14 08:52:28 -07006982 node = config_find(root, DEVICES_TAG);
6983 if (node != NULL) {
6984 node = node->first_child;
6985 while (node) {
6986 ALOGV("loadHwModule() loading device %s", node->name);
6987 status_t tmpStatus = module->loadDevice(node);
6988 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6989 status = tmpStatus;
6990 }
6991 node = node->next;
6992 }
6993 }
6994 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006995 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006996 node = node->first_child;
6997 while (node) {
6998 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006999 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007000 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7001 status = tmpStatus;
7002 }
7003 node = node->next;
7004 }
7005 }
7006 node = config_find(root, INPUTS_TAG);
7007 if (node != NULL) {
7008 node = node->first_child;
7009 while (node) {
7010 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007011 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007012 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7013 status = tmpStatus;
7014 }
7015 node = node->next;
7016 }
7017 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007018 loadGlobalConfig(root, module);
7019
Eric Laurente552edb2014-03-10 17:42:56 -07007020 if (status == NO_ERROR) {
7021 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007022 }
7023}
7024
Eric Laurente0720872014-03-11 09:30:41 -07007025void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007026{
7027 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7028 if (node == NULL) {
7029 return;
7030 }
7031
7032 node = node->first_child;
7033 while (node) {
7034 ALOGV("loadHwModules() loading module %s", node->name);
7035 loadHwModule(node);
7036 node = node->next;
7037 }
7038}
7039
Eric Laurent1f2f2232014-06-02 12:01:23 -07007040void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007041{
7042 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007043
Eric Laurente552edb2014-03-10 17:42:56 -07007044 if (node == NULL) {
7045 return;
7046 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007047 DeviceVector declaredDevices;
7048 if (module != NULL) {
7049 declaredDevices = module->mDeclaredDevices;
7050 }
7051
Eric Laurente552edb2014-03-10 17:42:56 -07007052 node = node->first_child;
7053 while (node) {
7054 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007055 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7056 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007057 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7058 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007059 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007060 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007061 ARRAY_SIZE(sDeviceNameToEnumTable),
7062 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007063 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007064 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007065 } else {
7066 ALOGW("loadGlobalConfig() default device not specified");
7067 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007068 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007069 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007070 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7071 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007072 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007073 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7074 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7075 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007076 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7077 uint32_t major, minor;
7078 sscanf((char *)node->value, "%u.%u", &major, &minor);
7079 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7080 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7081 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007082 }
7083 node = node->next;
7084 }
7085}
7086
Eric Laurente0720872014-03-11 09:30:41 -07007087status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007088{
7089 cnode *root;
7090 char *data;
7091
7092 data = (char *)load_file(path, NULL);
7093 if (data == NULL) {
7094 return -ENODEV;
7095 }
7096 root = config_node("", "");
7097 config_load(root, data);
7098
Eric Laurente552edb2014-03-10 17:42:56 -07007099 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007100 // legacy audio_policy.conf files have one global_configuration section
7101 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007102 config_free(root);
7103 free(root);
7104 free(data);
7105
7106 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7107
7108 return NO_ERROR;
7109}
7110
Eric Laurente0720872014-03-11 09:30:41 -07007111void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007112{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007113 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007114 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007115 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7116 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007117 mAvailableOutputDevices.add(mDefaultOutputDevice);
7118 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007119
7120 module = new HwModule("primary");
7121
Eric Laurent1afeecb2014-05-14 08:52:28 -07007122 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007123 profile->mSamplingRates.add(44100);
7124 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7125 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007126 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007127 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7128 module->mOutputProfiles.add(profile);
7129
Eric Laurent1afeecb2014-05-14 08:52:28 -07007130 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007131 profile->mSamplingRates.add(8000);
7132 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7133 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007134 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007135 module->mInputProfiles.add(profile);
7136
7137 mHwModules.add(module);
7138}
7139
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007140audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7141{
7142 // flags to stream type mapping
7143 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7144 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7145 }
7146 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7147 return AUDIO_STREAM_BLUETOOTH_SCO;
7148 }
7149
7150 // usage to stream type mapping
7151 switch (attr->usage) {
7152 case AUDIO_USAGE_MEDIA:
7153 case AUDIO_USAGE_GAME:
7154 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7155 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7156 return AUDIO_STREAM_MUSIC;
7157 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7158 return AUDIO_STREAM_SYSTEM;
7159 case AUDIO_USAGE_VOICE_COMMUNICATION:
7160 return AUDIO_STREAM_VOICE_CALL;
7161
7162 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7163 return AUDIO_STREAM_DTMF;
7164
7165 case AUDIO_USAGE_ALARM:
7166 return AUDIO_STREAM_ALARM;
7167 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7168 return AUDIO_STREAM_RING;
7169
7170 case AUDIO_USAGE_NOTIFICATION:
7171 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7172 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7173 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7174 case AUDIO_USAGE_NOTIFICATION_EVENT:
7175 return AUDIO_STREAM_NOTIFICATION;
7176
7177 case AUDIO_USAGE_UNKNOWN:
7178 default:
7179 return AUDIO_STREAM_MUSIC;
7180 }
7181}
Eric Laurente552edb2014-03-10 17:42:56 -07007182}; // namespace android