blob: d5f6c1e35ebf43fe51857a3fd1b71e4e376f156b [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 Laurent58f8eb72014-09-12 16:19:41 -07002297 if (srcDeviceDesc == 0) {
2298 return BAD_VALUE;
2299 }
Eric Laurent874c42872014-08-08 15:13:39 -07002300
Eric Laurent6a94d692014-05-20 11:18:06 -07002301 //update source and sink with our own data as the data passed in the patch may
2302 // be incomplete.
2303 struct audio_patch newPatch = *patch;
2304 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
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{
Jon Eklund966095e2014-09-09 15:39:49 -05003673 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3674 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003675 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003676 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3677 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003678 checkOutputForStrategy(STRATEGY_SONIFICATION);
3679 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3680 checkOutputForStrategy(STRATEGY_MEDIA);
3681 checkOutputForStrategy(STRATEGY_DTMF);
3682}
3683
Eric Laurente0720872014-03-11 09:30:41 -07003684audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003685{
Eric Laurente552edb2014-03-10 17:42:56 -07003686 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003687 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003688 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3689 return mOutputs.keyAt(i);
3690 }
3691 }
3692
3693 return 0;
3694}
3695
Eric Laurente0720872014-03-11 09:30:41 -07003696void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003697{
Eric Laurente552edb2014-03-10 17:42:56 -07003698 audio_io_handle_t a2dpOutput = getA2dpOutput();
3699 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003700 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003701 return;
3702 }
3703
Eric Laurent3a4311c2014-03-17 12:00:47 -07003704 bool isScoConnected =
3705 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003706 // suspend A2DP output if:
3707 // (NOT already suspended) &&
3708 // ((SCO device is connected &&
3709 // (forced usage for communication || for record is SCO))) ||
3710 // (phone state is ringing || in call)
3711 //
3712 // restore A2DP output if:
3713 // (Already suspended) &&
3714 // ((SCO device is NOT connected ||
3715 // (forced usage NOT for communication && NOT for record is SCO))) &&
3716 // (phone state is NOT ringing && NOT in call)
3717 //
3718 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003719 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003720 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3721 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3722 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3723 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003724
3725 mpClientInterface->restoreOutput(a2dpOutput);
3726 mA2dpSuspended = false;
3727 }
3728 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003729 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003730 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3731 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3732 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3733 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003734
3735 mpClientInterface->suspendOutput(a2dpOutput);
3736 mA2dpSuspended = true;
3737 }
3738 }
3739}
3740
Eric Laurent1c333e22014-05-20 10:48:17 -07003741audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003742{
3743 audio_devices_t device = AUDIO_DEVICE_NONE;
3744
Eric Laurent1f2f2232014-06-02 12:01:23 -07003745 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003746
3747 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3748 if (index >= 0) {
3749 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3750 if (patchDesc->mUid != mUidCached) {
3751 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3752 outputDesc->device(), outputDesc->mPatchHandle);
3753 return outputDesc->device();
3754 }
3755 }
3756
Eric Laurente552edb2014-03-10 17:42:56 -07003757 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003758 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003759 // use device for strategy enforced audible
3760 // 2: we are in call or the strategy phone is active on the output:
3761 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003762 // 3: the strategy for enforced audible is active but not enforced on the output:
3763 // use the device for strategy enforced audible
3764 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003765 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003766 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003767 // use device for strategy "respectful" sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003768 // 6: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003769 // use device for strategy media
Jon Eklund966095e2014-09-09 15:39:49 -05003770 // 7: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003771 // use device for strategy DTMF
Jon Eklund966095e2014-09-09 15:39:49 -05003772 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3773 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003774 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3775 } else if (isInCall() ||
3776 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3777 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003778 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3779 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003780 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3781 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3782 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3783 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3784 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3785 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3786 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3787 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3788 }
3789
Eric Laurent1c333e22014-05-20 10:48:17 -07003790 ALOGV("getNewOutputDevice() selected device %x", device);
3791 return device;
3792}
3793
3794audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3795{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003796 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003797
3798 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3799 if (index >= 0) {
3800 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3801 if (patchDesc->mUid != mUidCached) {
3802 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3803 inputDesc->mDevice, inputDesc->mPatchHandle);
3804 return inputDesc->mDevice;
3805 }
3806 }
3807
Eric Laurent1c333e22014-05-20 10:48:17 -07003808 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3809
3810 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003811 return device;
3812}
3813
Eric Laurente0720872014-03-11 09:30:41 -07003814uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003815 return (uint32_t)getStrategy(stream);
3816}
3817
Eric Laurente0720872014-03-11 09:30:41 -07003818audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003819 // By checking the range of stream before calling getStrategy, we avoid
3820 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3821 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003822 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003823 return AUDIO_DEVICE_NONE;
3824 }
3825 audio_devices_t devices;
3826 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3827 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3828 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3829 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003830 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003831 if (outputDesc->isStrategyActive(strategy)) {
3832 devices = outputDesc->device();
3833 break;
3834 }
Eric Laurente552edb2014-03-10 17:42:56 -07003835 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003836
3837 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
3838 and doesn't really need to.*/
3839 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
3840 devices |= AUDIO_DEVICE_OUT_SPEAKER;
3841 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3842 }
3843
Eric Laurente552edb2014-03-10 17:42:56 -07003844 return devices;
3845}
3846
Eric Laurente0720872014-03-11 09:30:41 -07003847AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003848 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003849 // stream to strategy mapping
3850 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003851 case AUDIO_STREAM_VOICE_CALL:
3852 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003853 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003854 case AUDIO_STREAM_RING:
3855 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003856 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003857 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003858 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003859 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003860 return STRATEGY_DTMF;
3861 default:
3862 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003863 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003864 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3865 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003866 case AUDIO_STREAM_TTS:
3867 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003868 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003869 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003870 return STRATEGY_ENFORCED_AUDIBLE;
3871 }
3872}
3873
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003874uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3875 // flags to strategy mapping
3876 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3877 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3878 }
3879
3880 // usage to strategy mapping
3881 switch (attr->usage) {
3882 case AUDIO_USAGE_MEDIA:
3883 case AUDIO_USAGE_GAME:
3884 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3885 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3886 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3887 return (uint32_t) STRATEGY_MEDIA;
3888
3889 case AUDIO_USAGE_VOICE_COMMUNICATION:
3890 return (uint32_t) STRATEGY_PHONE;
3891
3892 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3893 return (uint32_t) STRATEGY_DTMF;
3894
3895 case AUDIO_USAGE_ALARM:
3896 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3897 return (uint32_t) STRATEGY_SONIFICATION;
3898
3899 case AUDIO_USAGE_NOTIFICATION:
3900 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3901 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3902 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3903 case AUDIO_USAGE_NOTIFICATION_EVENT:
3904 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3905
3906 case AUDIO_USAGE_UNKNOWN:
3907 default:
3908 return (uint32_t) STRATEGY_MEDIA;
3909 }
3910}
3911
Eric Laurente0720872014-03-11 09:30:41 -07003912void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003913 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003914 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003915 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3916 updateDevicesAndOutputs();
3917 break;
3918 default:
3919 break;
3920 }
3921}
3922
Eric Laurente0720872014-03-11 09:30:41 -07003923audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003924 bool fromCache)
3925{
3926 uint32_t device = AUDIO_DEVICE_NONE;
3927
3928 if (fromCache) {
3929 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3930 strategy, mDeviceForStrategy[strategy]);
3931 return mDeviceForStrategy[strategy];
3932 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003933 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003934 switch (strategy) {
3935
3936 case STRATEGY_SONIFICATION_RESPECTFUL:
3937 if (isInCall()) {
3938 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003939 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003940 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3941 // while media is playing on a remote device, use the the sonification behavior.
3942 // Note that we test this usecase before testing if media is playing because
3943 // the isStreamActive() method only informs about the activity of a stream, not
3944 // if it's for local playback. Note also that we use the same delay between both tests
3945 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05003946 //user "safe" speaker if available instead of normal speaker to avoid triggering
3947 //other acoustic safety mechanisms for notification
3948 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
3949 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003950 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003951 // while media is playing (or has recently played), use the same device
3952 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3953 } else {
3954 // when media is not playing anymore, fall back on the sonification behavior
3955 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05003956 //user "safe" speaker if available instead of normal speaker to avoid triggering
3957 //other acoustic safety mechanisms for notification
3958 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
3959 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07003960 }
3961
3962 break;
3963
3964 case STRATEGY_DTMF:
3965 if (!isInCall()) {
3966 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3967 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3968 break;
3969 }
3970 // when in call, DTMF and PHONE strategies follow the same rules
3971 // FALL THROUGH
3972
3973 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07003974 // Force use of only devices on primary output if:
3975 // - in call AND
3976 // - cannot route from voice call RX OR
3977 // - audio HAL version is < 3.0 and TX device is on the primary HW module
3978 if (mPhoneState == AUDIO_MODE_IN_CALL) {
3979 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
3980 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
3981 if (((mAvailableInputDevices.types() &
3982 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
3983 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07003984 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07003985 AUDIO_DEVICE_API_VERSION_3_0))) {
3986 availableOutputDeviceTypes = availablePrimaryOutputDevices();
3987 }
3988 }
Eric Laurente552edb2014-03-10 17:42:56 -07003989 // for phone strategy, we first consider the forced use and then the available devices by order
3990 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003991 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3992 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003993 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003994 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003995 if (device) break;
3996 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003997 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003998 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003999 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004000 if (device) break;
4001 // if SCO device is requested but no SCO device is available, fall back to default case
4002 // FALL THROUGH
4003
4004 default: // FORCE_NONE
4005 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004006 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004007 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004008 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004009 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004010 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004011 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004012 if (device) break;
4013 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004014 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004015 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004016 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004017 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004018 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4019 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004020 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004021 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004022 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004023 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004024 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004025 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004026 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004027 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004028 if (device) break;
4029 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004030 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004031 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004032 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004033 if (device == AUDIO_DEVICE_NONE) {
4034 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4035 }
4036 break;
4037
Eric Laurent3b73df72014-03-11 09:06:29 -07004038 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004039 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4040 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004041 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004042 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004043 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004044 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004045 if (device) break;
4046 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004047 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004048 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004049 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004050 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004051 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004052 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004053 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004054 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004055 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004056 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004057 if (device) break;
4058 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004059 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4060 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004061 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004062 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004063 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004064 if (device == AUDIO_DEVICE_NONE) {
4065 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4066 }
4067 break;
4068 }
4069 break;
4070
4071 case STRATEGY_SONIFICATION:
4072
4073 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4074 // handleIncallSonification().
4075 if (isInCall()) {
4076 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4077 break;
4078 }
4079 // FALL THROUGH
4080
4081 case STRATEGY_ENFORCED_AUDIBLE:
4082 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4083 // except:
4084 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4085 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4086
4087 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004088 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004089 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004090 if (device == AUDIO_DEVICE_NONE) {
4091 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4092 }
4093 }
4094 // The second device used for sonification is the same as the device used by media strategy
4095 // FALL THROUGH
4096
4097 case STRATEGY_MEDIA: {
4098 uint32_t device2 = AUDIO_DEVICE_NONE;
4099 if (strategy != STRATEGY_SONIFICATION) {
4100 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004101 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004102 }
4103 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004104 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004105 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004106 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004107 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004108 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004109 }
4110 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004111 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004112 }
4113 }
4114 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004115 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004116 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004117 if ((device2 == AUDIO_DEVICE_NONE)) {
4118 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4119 }
Eric Laurente552edb2014-03-10 17:42:56 -07004120 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004121 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004122 }
4123 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004124 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004125 }
4126 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004127 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004128 }
4129 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004130 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004131 }
4132 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4133 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004134 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004135 }
4136 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004137 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004138 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004139 }
4140 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004141 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004142 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004143 int device3 = AUDIO_DEVICE_NONE;
4144 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004145 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004146 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4147 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004148 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004149 }
Eric Laurente552edb2014-03-10 17:42:56 -07004150
Jungshik Jang839e4f32014-06-26 17:23:40 +09004151 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004152 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4153 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4154 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004155
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004156 // If hdmi system audio mode is on, remove speaker out of output list.
4157 if ((strategy == STRATEGY_MEDIA) &&
4158 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4159 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4160 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4161 }
4162
Eric Laurente552edb2014-03-10 17:42:56 -07004163 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004164 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004165 if (device == AUDIO_DEVICE_NONE) {
4166 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4167 }
4168 } break;
4169
4170 default:
4171 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4172 break;
4173 }
4174
4175 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4176 return device;
4177}
4178
Eric Laurente0720872014-03-11 09:30:41 -07004179void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004180{
4181 for (int i = 0; i < NUM_STRATEGIES; i++) {
4182 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4183 }
4184 mPreviousOutputs = mOutputs;
4185}
4186
Eric Laurent1f2f2232014-06-02 12:01:23 -07004187uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004188 audio_devices_t prevDevice,
4189 uint32_t delayMs)
4190{
4191 // mute/unmute strategies using an incompatible device combination
4192 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4193 // if unmuting, unmute only after the specified delay
4194 if (outputDesc->isDuplicated()) {
4195 return 0;
4196 }
4197
4198 uint32_t muteWaitMs = 0;
4199 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004200 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004201
4202 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4203 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4204 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4205 bool doMute = false;
4206
4207 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4208 doMute = true;
4209 outputDesc->mStrategyMutedByDevice[i] = true;
4210 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4211 doMute = true;
4212 outputDesc->mStrategyMutedByDevice[i] = false;
4213 }
Eric Laurent99401132014-05-07 19:48:15 -07004214 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004215 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004216 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004217 // skip output if it does not share any device with current output
4218 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4219 == AUDIO_DEVICE_NONE) {
4220 continue;
4221 }
4222 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4223 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4224 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4225 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4226 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004227 if (mute) {
4228 // FIXME: should not need to double latency if volume could be applied
4229 // immediately by the audioflinger mixer. We must account for the delay
4230 // between now and the next time the audioflinger thread for this output
4231 // will process a buffer (which corresponds to one buffer size,
4232 // usually 1/2 or 1/4 of the latency).
4233 if (muteWaitMs < desc->latency() * 2) {
4234 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004235 }
4236 }
4237 }
4238 }
4239 }
4240 }
4241
Eric Laurent99401132014-05-07 19:48:15 -07004242 // temporary mute output if device selection changes to avoid volume bursts due to
4243 // different per device volumes
4244 if (outputDesc->isActive() && (device != prevDevice)) {
4245 if (muteWaitMs < outputDesc->latency() * 2) {
4246 muteWaitMs = outputDesc->latency() * 2;
4247 }
4248 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4249 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004250 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004251 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004252 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004253 muteWaitMs *2, device);
4254 }
4255 }
4256 }
4257
Eric Laurente552edb2014-03-10 17:42:56 -07004258 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4259 if (muteWaitMs > delayMs) {
4260 muteWaitMs -= delayMs;
4261 usleep(muteWaitMs * 1000);
4262 return muteWaitMs;
4263 }
4264 return 0;
4265}
4266
Eric Laurente0720872014-03-11 09:30:41 -07004267uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004268 audio_devices_t device,
4269 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004270 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004271 audio_patch_handle_t *patchHandle,
4272 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004273{
4274 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004275 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004276 AudioParameter param;
4277 uint32_t muteWaitMs;
4278
4279 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004280 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4281 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004282 return muteWaitMs;
4283 }
4284 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4285 // output profile
4286 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004287 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004288 return 0;
4289 }
4290
4291 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004292 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004293
4294 audio_devices_t prevDevice = outputDesc->mDevice;
4295
4296 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4297
4298 if (device != AUDIO_DEVICE_NONE) {
4299 outputDesc->mDevice = device;
4300 }
4301 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4302
4303 // Do not change the routing if:
4304 // - the requested device is AUDIO_DEVICE_NONE
4305 // - the requested device is the same as current device and force is not specified.
4306 // Doing this check here allows the caller to call setOutputDevice() without conditions
4307 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4308 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4309 return muteWaitMs;
4310 }
4311
4312 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004313
Eric Laurente552edb2014-03-10 17:42:56 -07004314 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004315 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004316 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004317 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004318 DeviceVector deviceList = (address == NULL) ?
4319 mAvailableOutputDevices.getDevicesFromType(device)
4320 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004321 if (!deviceList.isEmpty()) {
4322 struct audio_patch patch;
4323 outputDesc->toAudioPortConfig(&patch.sources[0]);
4324 patch.num_sources = 1;
4325 patch.num_sinks = 0;
4326 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4327 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004328 patch.num_sinks++;
4329 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004330 ssize_t index;
4331 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4332 index = mAudioPatches.indexOfKey(*patchHandle);
4333 } else {
4334 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4335 }
4336 sp< AudioPatch> patchDesc;
4337 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4338 if (index >= 0) {
4339 patchDesc = mAudioPatches.valueAt(index);
4340 afPatchHandle = patchDesc->mAfPatchHandle;
4341 }
4342
Eric Laurent1c333e22014-05-20 10:48:17 -07004343 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004344 &afPatchHandle,
4345 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004346 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4347 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004348 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004349 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004350 if (index < 0) {
4351 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4352 &patch, mUidCached);
4353 addAudioPatch(patchDesc->mHandle, patchDesc);
4354 } else {
4355 patchDesc->mPatch = patch;
4356 }
4357 patchDesc->mAfPatchHandle = afPatchHandle;
4358 patchDesc->mUid = mUidCached;
4359 if (patchHandle) {
4360 *patchHandle = patchDesc->mHandle;
4361 }
4362 outputDesc->mPatchHandle = patchDesc->mHandle;
4363 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004364 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004365 }
4366 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004367
4368 // inform all input as well
4369 for (size_t i = 0; i < mInputs.size(); i++) {
4370 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4371 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4372 AudioParameter inputCmd = AudioParameter();
4373 ALOGV("%s: inform input %d of device:%d", __func__,
4374 inputDescriptor->mIoHandle, device);
4375 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4376 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4377 inputCmd.toString(),
4378 delayMs);
4379 }
4380 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004381 }
Eric Laurente552edb2014-03-10 17:42:56 -07004382
4383 // update stream volumes according to new device
4384 applyStreamVolumes(output, device, delayMs);
4385
4386 return muteWaitMs;
4387}
4388
Eric Laurent1c333e22014-05-20 10:48:17 -07004389status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004390 int delayMs,
4391 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004392{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004393 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004394 ssize_t index;
4395 if (patchHandle) {
4396 index = mAudioPatches.indexOfKey(*patchHandle);
4397 } else {
4398 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4399 }
4400 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004401 return INVALID_OPERATION;
4402 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004403 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4404 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004405 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4406 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004407 removeAudioPatch(patchDesc->mHandle);
4408 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004409 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004410 return status;
4411}
4412
4413status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4414 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004415 bool force,
4416 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004417{
4418 status_t status = NO_ERROR;
4419
Eric Laurent1f2f2232014-06-02 12:01:23 -07004420 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004421 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4422 inputDesc->mDevice = device;
4423
4424 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4425 if (!deviceList.isEmpty()) {
4426 struct audio_patch patch;
4427 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004428 // AUDIO_SOURCE_HOTWORD is for internal use only:
4429 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004430 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4431 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004432 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4433 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004434 patch.num_sinks = 1;
4435 //only one input device for now
4436 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004437 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004438 ssize_t index;
4439 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4440 index = mAudioPatches.indexOfKey(*patchHandle);
4441 } else {
4442 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4443 }
4444 sp< AudioPatch> patchDesc;
4445 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4446 if (index >= 0) {
4447 patchDesc = mAudioPatches.valueAt(index);
4448 afPatchHandle = patchDesc->mAfPatchHandle;
4449 }
4450
Eric Laurent1c333e22014-05-20 10:48:17 -07004451 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004452 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004453 0);
4454 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004455 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004456 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004457 if (index < 0) {
4458 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4459 &patch, mUidCached);
4460 addAudioPatch(patchDesc->mHandle, patchDesc);
4461 } else {
4462 patchDesc->mPatch = patch;
4463 }
4464 patchDesc->mAfPatchHandle = afPatchHandle;
4465 patchDesc->mUid = mUidCached;
4466 if (patchHandle) {
4467 *patchHandle = patchDesc->mHandle;
4468 }
4469 inputDesc->mPatchHandle = patchDesc->mHandle;
4470 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004471 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004472 }
4473 }
4474 }
4475 return status;
4476}
4477
Eric Laurent6a94d692014-05-20 11:18:06 -07004478status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4479 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004480{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004481 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004482 ssize_t index;
4483 if (patchHandle) {
4484 index = mAudioPatches.indexOfKey(*patchHandle);
4485 } else {
4486 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4487 }
4488 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004489 return INVALID_OPERATION;
4490 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004491 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4492 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004493 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4494 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004495 removeAudioPatch(patchDesc->mHandle);
4496 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004497 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004498 return status;
4499}
4500
4501sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004502 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004503 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004504 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004505 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004506{
4507 // Choose an input profile based on the requested capture parameters: select the first available
4508 // profile supporting all requested parameters.
4509
4510 for (size_t i = 0; i < mHwModules.size(); i++)
4511 {
4512 if (mHwModules[i]->mHandle == 0) {
4513 continue;
4514 }
4515 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4516 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004517 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004518 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004519 if (profile->isCompatibleProfile(device, samplingRate,
4520 &samplingRate /*updatedSamplingRate*/,
4521 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004522 return profile;
4523 }
4524 }
4525 }
4526 return NULL;
4527}
4528
Eric Laurente0720872014-03-11 09:30:41 -07004529audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004530{
4531 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004532 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4533 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004534 switch (inputSource) {
4535 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004536 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004537 device = AUDIO_DEVICE_IN_VOICE_CALL;
4538 break;
4539 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004540 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004541
4542 case AUDIO_SOURCE_DEFAULT:
4543 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004544 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4545 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004546 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4547 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4548 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4549 device = AUDIO_DEVICE_IN_USB_DEVICE;
4550 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4551 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004552 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004553 break;
4554
4555 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4556 // Allow only use of devices on primary input if in call and HAL does not support routing
4557 // to voice call path.
4558 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4559 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4560 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4561 }
4562
4563 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4564 case AUDIO_POLICY_FORCE_BT_SCO:
4565 // if SCO device is requested but no SCO device is available, fall back to default case
4566 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4567 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4568 break;
4569 }
4570 // FALL THROUGH
4571
4572 default: // FORCE_NONE
4573 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4574 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4575 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4576 device = AUDIO_DEVICE_IN_USB_DEVICE;
4577 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4578 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4579 }
4580 break;
4581
4582 case AUDIO_POLICY_FORCE_SPEAKER:
4583 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4584 device = AUDIO_DEVICE_IN_BACK_MIC;
4585 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4586 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4587 }
4588 break;
4589 }
4590 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004591
Eric Laurente552edb2014-03-10 17:42:56 -07004592 case AUDIO_SOURCE_VOICE_RECOGNITION:
4593 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004594 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004595 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004596 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004597 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004598 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004599 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4600 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004601 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004602 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4603 }
4604 break;
4605 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004606 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004607 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004608 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004609 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4610 }
4611 break;
4612 case AUDIO_SOURCE_VOICE_DOWNLINK:
4613 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004614 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004615 device = AUDIO_DEVICE_IN_VOICE_CALL;
4616 }
4617 break;
4618 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004619 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004620 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4621 }
4622 break;
4623 default:
4624 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4625 break;
4626 }
4627 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4628 return device;
4629}
4630
Eric Laurente0720872014-03-11 09:30:41 -07004631bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004632{
4633 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4634 device &= ~AUDIO_DEVICE_BIT_IN;
4635 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4636 return true;
4637 }
4638 return false;
4639}
4640
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004641bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4642 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4643}
4644
Eric Laurente0720872014-03-11 09:30:41 -07004645audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004646{
4647 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004648 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004649 if ((input_descriptor->mRefCount > 0)
4650 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4651 return mInputs.keyAt(i);
4652 }
4653 }
4654 return 0;
4655}
4656
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004657uint32_t AudioPolicyManager::activeInputsCount() const
4658{
4659 uint32_t count = 0;
4660 for (size_t i = 0; i < mInputs.size(); i++) {
4661 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4662 if (desc->mRefCount > 0) {
4663 return count++;
4664 }
4665 }
4666 return count;
4667}
4668
Eric Laurente552edb2014-03-10 17:42:56 -07004669
Eric Laurente0720872014-03-11 09:30:41 -07004670audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004671{
4672 if (device == AUDIO_DEVICE_NONE) {
4673 // this happens when forcing a route update and no track is active on an output.
4674 // In this case the returned category is not important.
4675 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004676 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004677 // Multiple device selection is either:
4678 // - speaker + one other device: give priority to speaker in this case.
4679 // - one A2DP device + another device: happens with duplicated output. In this case
4680 // retain the device on the A2DP output as the other must not correspond to an active
4681 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004682 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004683 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4684 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004685 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4686 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4687 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4688 device = AUDIO_DEVICE_OUT_AUX_LINE;
4689 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4690 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004691 } else {
4692 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4693 }
4694 }
4695
Jon Eklund11c9fb12014-06-23 14:47:03 -05004696 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4697 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4698 device = AUDIO_DEVICE_OUT_SPEAKER;
4699
Eric Laurent3b73df72014-03-11 09:06:29 -07004700 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004701 "getDeviceForVolume() invalid device combination: %08x",
4702 device);
4703
4704 return device;
4705}
4706
Eric Laurente0720872014-03-11 09:30:41 -07004707AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004708{
4709 switch(getDeviceForVolume(device)) {
4710 case AUDIO_DEVICE_OUT_EARPIECE:
4711 return DEVICE_CATEGORY_EARPIECE;
4712 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4713 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4714 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4715 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4716 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4717 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4718 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004719 case AUDIO_DEVICE_OUT_LINE:
4720 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4721 /*USB? Remote submix?*/
4722 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004723 case AUDIO_DEVICE_OUT_SPEAKER:
4724 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4725 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004726 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4727 case AUDIO_DEVICE_OUT_USB_DEVICE:
4728 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4729 default:
4730 return DEVICE_CATEGORY_SPEAKER;
4731 }
4732}
4733
Eric Laurente0720872014-03-11 09:30:41 -07004734float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004735 int indexInUi)
4736{
4737 device_category deviceCategory = getDeviceCategory(device);
4738 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4739
4740 // the volume index in the UI is relative to the min and max volume indices for this stream type
4741 int nbSteps = 1 + curve[VOLMAX].mIndex -
4742 curve[VOLMIN].mIndex;
4743 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4744 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4745
4746 // find what part of the curve this index volume belongs to, or if it's out of bounds
4747 int segment = 0;
4748 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4749 return 0.0f;
4750 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4751 segment = 0;
4752 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4753 segment = 1;
4754 } else if (volIdx <= curve[VOLMAX].mIndex) {
4755 segment = 2;
4756 } else { // out of bounds
4757 return 1.0f;
4758 }
4759
4760 // linear interpolation in the attenuation table in dB
4761 float decibels = curve[segment].mDBAttenuation +
4762 ((float)(volIdx - curve[segment].mIndex)) *
4763 ( (curve[segment+1].mDBAttenuation -
4764 curve[segment].mDBAttenuation) /
4765 ((float)(curve[segment+1].mIndex -
4766 curve[segment].mIndex)) );
4767
4768 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4769
4770 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4771 curve[segment].mIndex, volIdx,
4772 curve[segment+1].mIndex,
4773 curve[segment].mDBAttenuation,
4774 decibels,
4775 curve[segment+1].mDBAttenuation,
4776 amplification);
4777
4778 return amplification;
4779}
4780
Eric Laurente0720872014-03-11 09:30:41 -07004781const AudioPolicyManager::VolumeCurvePoint
4782 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004783 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4784};
4785
Eric Laurente0720872014-03-11 09:30:41 -07004786const AudioPolicyManager::VolumeCurvePoint
4787 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004788 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4789};
4790
Eric Laurente0720872014-03-11 09:30:41 -07004791const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004792 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4793 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4794};
4795
4796const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004797 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004798 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4799};
4800
Eric Laurente0720872014-03-11 09:30:41 -07004801const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004802 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004803 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004804};
4805
4806const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004807 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004808 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4809};
4810
Eric Laurente0720872014-03-11 09:30:41 -07004811const AudioPolicyManager::VolumeCurvePoint
4812 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004813 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4814};
4815
4816// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4817// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4818// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4819// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4820
Eric Laurente0720872014-03-11 09:30:41 -07004821const AudioPolicyManager::VolumeCurvePoint
4822 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004823 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4824};
4825
Eric Laurente0720872014-03-11 09:30:41 -07004826const AudioPolicyManager::VolumeCurvePoint
4827 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004828 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4829};
4830
Eric Laurente0720872014-03-11 09:30:41 -07004831const AudioPolicyManager::VolumeCurvePoint
4832 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004833 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4834};
4835
Eric Laurente0720872014-03-11 09:30:41 -07004836const AudioPolicyManager::VolumeCurvePoint
4837 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004838 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4839};
4840
Eric Laurente0720872014-03-11 09:30:41 -07004841const AudioPolicyManager::VolumeCurvePoint
4842 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004843 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4844};
4845
Eric Laurente0720872014-03-11 09:30:41 -07004846const AudioPolicyManager::VolumeCurvePoint
4847 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4848 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004849 { // AUDIO_STREAM_VOICE_CALL
4850 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4851 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004852 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4853 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004854 },
4855 { // AUDIO_STREAM_SYSTEM
4856 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4857 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004858 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4859 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004860 },
4861 { // AUDIO_STREAM_RING
4862 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4863 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004864 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4865 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004866 },
4867 { // AUDIO_STREAM_MUSIC
4868 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4869 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004870 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4871 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004872 },
4873 { // AUDIO_STREAM_ALARM
4874 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4875 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004876 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4877 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004878 },
4879 { // AUDIO_STREAM_NOTIFICATION
4880 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4881 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004882 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4883 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004884 },
4885 { // AUDIO_STREAM_BLUETOOTH_SCO
4886 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4887 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004888 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4889 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004890 },
4891 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4892 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4893 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004894 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4895 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004896 },
4897 { // AUDIO_STREAM_DTMF
4898 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4899 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004900 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4901 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004902 },
4903 { // AUDIO_STREAM_TTS
4904 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4905 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004906 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4907 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004908 },
4909};
4910
Eric Laurente0720872014-03-11 09:30:41 -07004911void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004912{
4913 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4914 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4915 mStreams[i].mVolumeCurve[j] =
4916 sVolumeProfiles[i][j];
4917 }
4918 }
4919
4920 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4921 if (mSpeakerDrcEnabled) {
4922 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4923 sDefaultSystemVolumeCurveDrc;
4924 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4925 sSpeakerSonificationVolumeCurveDrc;
4926 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4927 sSpeakerSonificationVolumeCurveDrc;
4928 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4929 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004930 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4931 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004932 }
4933}
4934
Eric Laurente0720872014-03-11 09:30:41 -07004935float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004936 int index,
4937 audio_io_handle_t output,
4938 audio_devices_t device)
4939{
4940 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004941 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004942 StreamDescriptor &streamDesc = mStreams[stream];
4943
4944 if (device == AUDIO_DEVICE_NONE) {
4945 device = outputDesc->device();
4946 }
4947
Eric Laurente552edb2014-03-10 17:42:56 -07004948 volume = volIndexToAmpl(device, streamDesc, index);
4949
4950 // if a headset is connected, apply the following rules to ring tones and notifications
4951 // to avoid sound level bursts in user's ears:
4952 // - always attenuate ring tones and notifications volume by 6dB
4953 // - if music is playing, always limit the volume to current music volume,
4954 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004955 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004956 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4957 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4958 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4959 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4960 ((stream_strategy == STRATEGY_SONIFICATION)
4961 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004962 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004963 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004964 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004965 streamDesc.mCanBeMuted) {
4966 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4967 // when the phone is ringing we must consider that music could have been paused just before
4968 // by the music application and behave as if music was active if the last music track was
4969 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004970 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004971 mLimitRingtoneVolume) {
4972 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004973 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4974 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004975 output,
4976 musicDevice);
4977 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4978 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4979 if (volume > minVol) {
4980 volume = minVol;
4981 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4982 }
4983 }
4984 }
4985
4986 return volume;
4987}
4988
Eric Laurente0720872014-03-11 09:30:41 -07004989status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004990 int index,
4991 audio_io_handle_t output,
4992 audio_devices_t device,
4993 int delayMs,
4994 bool force)
4995{
4996
4997 // do not change actual stream volume if the stream is muted
4998 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4999 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5000 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5001 return NO_ERROR;
5002 }
5003
5004 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005005 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5006 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5007 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5008 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005009 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005010 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005011 return INVALID_OPERATION;
5012 }
5013
5014 float volume = computeVolume(stream, index, output, device);
5015 // We actually change the volume if:
5016 // - the float value returned by computeVolume() changed
5017 // - the force flag is set
5018 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5019 force) {
5020 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5021 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5022 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5023 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005024 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5025 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005026 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005027 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005028 }
5029
Eric Laurent3b73df72014-03-11 09:06:29 -07005030 if (stream == AUDIO_STREAM_VOICE_CALL ||
5031 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005032 float voiceVolume;
5033 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005034 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005035 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5036 } else {
5037 voiceVolume = 1.0;
5038 }
5039
5040 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5041 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5042 mLastVoiceVolume = voiceVolume;
5043 }
5044 }
5045
5046 return NO_ERROR;
5047}
5048
Eric Laurente0720872014-03-11 09:30:41 -07005049void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005050 audio_devices_t device,
5051 int delayMs,
5052 bool force)
5053{
5054 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5055
Eric Laurent3b73df72014-03-11 09:06:29 -07005056 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5057 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005058 mStreams[stream].getVolumeIndex(device),
5059 output,
5060 device,
5061 delayMs,
5062 force);
5063 }
5064}
5065
Eric Laurente0720872014-03-11 09:30:41 -07005066void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005067 bool on,
5068 audio_io_handle_t output,
5069 int delayMs,
5070 audio_devices_t device)
5071{
5072 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005073 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5074 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5075 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005076 }
5077 }
5078}
5079
Eric Laurente0720872014-03-11 09:30:41 -07005080void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005081 bool on,
5082 audio_io_handle_t output,
5083 int delayMs,
5084 audio_devices_t device)
5085{
5086 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005087 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005088 if (device == AUDIO_DEVICE_NONE) {
5089 device = outputDesc->device();
5090 }
5091
5092 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5093 stream, on, output, outputDesc->mMuteCount[stream], device);
5094
5095 if (on) {
5096 if (outputDesc->mMuteCount[stream] == 0) {
5097 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005098 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5099 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005100 checkAndSetVolume(stream, 0, output, device, delayMs);
5101 }
5102 }
5103 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5104 outputDesc->mMuteCount[stream]++;
5105 } else {
5106 if (outputDesc->mMuteCount[stream] == 0) {
5107 ALOGV("setStreamMute() unmuting non muted stream!");
5108 return;
5109 }
5110 if (--outputDesc->mMuteCount[stream] == 0) {
5111 checkAndSetVolume(stream,
5112 streamDesc.getVolumeIndex(device),
5113 output,
5114 device,
5115 delayMs);
5116 }
5117 }
5118}
5119
Eric Laurente0720872014-03-11 09:30:41 -07005120void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005121 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005122{
5123 // if the stream pertains to sonification strategy and we are in call we must
5124 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5125 // in the device used for phone strategy and play the tone if the selected device does not
5126 // interfere with the device used for phone strategy
5127 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5128 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005129 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005130 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5131 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005132 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005133 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5134 stream, starting, outputDesc->mDevice, stateChange);
5135 if (outputDesc->mRefCount[stream]) {
5136 int muteCount = 1;
5137 if (stateChange) {
5138 muteCount = outputDesc->mRefCount[stream];
5139 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005140 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005141 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5142 for (int i = 0; i < muteCount; i++) {
5143 setStreamMute(stream, starting, mPrimaryOutput);
5144 }
5145 } else {
5146 ALOGV("handleIncallSonification() high visibility");
5147 if (outputDesc->device() &
5148 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5149 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5150 for (int i = 0; i < muteCount; i++) {
5151 setStreamMute(stream, starting, mPrimaryOutput);
5152 }
5153 }
5154 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005155 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5156 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005157 } else {
5158 mpClientInterface->stopTone();
5159 }
5160 }
5161 }
5162 }
5163}
5164
Eric Laurente0720872014-03-11 09:30:41 -07005165bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005166{
5167 return isStateInCall(mPhoneState);
5168}
5169
Eric Laurente0720872014-03-11 09:30:41 -07005170bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005171 return ((state == AUDIO_MODE_IN_CALL) ||
5172 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005173}
5174
Eric Laurente0720872014-03-11 09:30:41 -07005175uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005176{
5177 return MAX_EFFECTS_CPU_LOAD;
5178}
5179
Eric Laurente0720872014-03-11 09:30:41 -07005180uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005181{
5182 return MAX_EFFECTS_MEMORY;
5183}
5184
Eric Laurent6a94d692014-05-20 11:18:06 -07005185
Eric Laurente552edb2014-03-10 17:42:56 -07005186// --- AudioOutputDescriptor class implementation
5187
Eric Laurente0720872014-03-11 09:30:41 -07005188AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005189 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005190 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005191 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005192 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5193{
5194 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005195 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005196 mRefCount[i] = 0;
5197 mCurVolume[i] = -1.0;
5198 mMuteCount[i] = 0;
5199 mStopTime[i] = 0;
5200 }
5201 for (int i = 0; i < NUM_STRATEGIES; i++) {
5202 mStrategyMutedByDevice[i] = false;
5203 }
5204 if (profile != NULL) {
Eric Laurentd8622372014-07-27 13:47:31 -07005205 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005206 mSamplingRate = profile->pickSamplingRate();
5207 mFormat = profile->pickFormat();
5208 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005209 if (profile->mGains.size() > 0) {
5210 profile->mGains[0]->getDefaultConfig(&mGain);
5211 }
Eric Laurente552edb2014-03-10 17:42:56 -07005212 }
5213}
5214
Eric Laurente0720872014-03-11 09:30:41 -07005215audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005216{
5217 if (isDuplicated()) {
5218 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5219 } else {
5220 return mDevice;
5221 }
5222}
5223
Eric Laurente0720872014-03-11 09:30:41 -07005224uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005225{
5226 if (isDuplicated()) {
5227 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5228 } else {
5229 return mLatency;
5230 }
5231}
5232
Eric Laurente0720872014-03-11 09:30:41 -07005233bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005234 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005235{
5236 if (isDuplicated()) {
5237 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5238 } else if (outputDesc->isDuplicated()){
5239 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5240 } else {
5241 return (mProfile->mModule == outputDesc->mProfile->mModule);
5242 }
5243}
5244
Eric Laurente0720872014-03-11 09:30:41 -07005245void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005246 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005247{
5248 // forward usage count change to attached outputs
5249 if (isDuplicated()) {
5250 mOutput1->changeRefCount(stream, delta);
5251 mOutput2->changeRefCount(stream, delta);
5252 }
5253 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005254 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5255 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005256 mRefCount[stream] = 0;
5257 return;
5258 }
5259 mRefCount[stream] += delta;
5260 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5261}
5262
Eric Laurente0720872014-03-11 09:30:41 -07005263audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005264{
5265 if (isDuplicated()) {
5266 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5267 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005268 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005269 }
5270}
5271
Eric Laurente0720872014-03-11 09:30:41 -07005272bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005273{
5274 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5275}
5276
Eric Laurente0720872014-03-11 09:30:41 -07005277bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005278 uint32_t inPastMs,
5279 nsecs_t sysTime) const
5280{
5281 if ((sysTime == 0) && (inPastMs != 0)) {
5282 sysTime = systemTime();
5283 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005284 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5285 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005286 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005287 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005288 return true;
5289 }
5290 }
5291 return false;
5292}
5293
Eric Laurente0720872014-03-11 09:30:41 -07005294bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005295 uint32_t inPastMs,
5296 nsecs_t sysTime) const
5297{
5298 if (mRefCount[stream] != 0) {
5299 return true;
5300 }
5301 if (inPastMs == 0) {
5302 return false;
5303 }
5304 if (sysTime == 0) {
5305 sysTime = systemTime();
5306 }
5307 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5308 return true;
5309 }
5310 return false;
5311}
5312
Eric Laurent1c333e22014-05-20 10:48:17 -07005313void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 struct audio_port_config *dstConfig,
5315 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005316{
Eric Laurent84c70242014-06-23 08:46:27 -07005317 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5318
Eric Laurent1f2f2232014-06-02 12:01:23 -07005319 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5320 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5321 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005322 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005323 }
5324 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5325
Eric Laurent6a94d692014-05-20 11:18:06 -07005326 dstConfig->id = mId;
5327 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5328 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005329 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5330 dstConfig->ext.mix.handle = mIoHandle;
5331 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005332}
5333
5334void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5335 struct audio_port *port) const
5336{
Eric Laurent84c70242014-06-23 08:46:27 -07005337 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005338 mProfile->toAudioPort(port);
5339 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005340 toAudioPortConfig(&port->active_config);
5341 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005342 port->ext.mix.handle = mIoHandle;
5343 port->ext.mix.latency_class =
5344 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5345}
Eric Laurente552edb2014-03-10 17:42:56 -07005346
Eric Laurente0720872014-03-11 09:30:41 -07005347status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005348{
5349 const size_t SIZE = 256;
5350 char buffer[SIZE];
5351 String8 result;
5352
Eric Laurent4d416952014-08-10 14:07:09 -07005353 snprintf(buffer, SIZE, " ID: %d\n", mId);
5354 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005355 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5356 result.append(buffer);
5357 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5358 result.append(buffer);
5359 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5360 result.append(buffer);
5361 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5362 result.append(buffer);
5363 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5364 result.append(buffer);
5365 snprintf(buffer, SIZE, " Devices %08x\n", device());
5366 result.append(buffer);
5367 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5368 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005369 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5370 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5371 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005372 result.append(buffer);
5373 }
5374 write(fd, result.string(), result.size());
5375
5376 return NO_ERROR;
5377}
5378
5379// --- AudioInputDescriptor class implementation
5380
Eric Laurent1c333e22014-05-20 10:48:17 -07005381AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005382 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005383 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005384 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005385{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005386 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005387 mSamplingRate = profile->pickSamplingRate();
5388 mFormat = profile->pickFormat();
5389 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005390 if (profile->mGains.size() > 0) {
5391 profile->mGains[0]->getDefaultConfig(&mGain);
5392 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005393 }
Eric Laurente552edb2014-03-10 17:42:56 -07005394}
5395
Eric Laurent1c333e22014-05-20 10:48:17 -07005396void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005397 struct audio_port_config *dstConfig,
5398 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005399{
Eric Laurent84c70242014-06-23 08:46:27 -07005400 ALOG_ASSERT(mProfile != 0,
5401 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005402 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5403 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5404 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005405 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005406 }
5407
5408 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5409
Eric Laurent6a94d692014-05-20 11:18:06 -07005410 dstConfig->id = mId;
5411 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5412 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005413 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5414 dstConfig->ext.mix.handle = mIoHandle;
5415 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005416}
5417
5418void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5419 struct audio_port *port) const
5420{
Eric Laurent84c70242014-06-23 08:46:27 -07005421 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5422
Eric Laurent1c333e22014-05-20 10:48:17 -07005423 mProfile->toAudioPort(port);
5424 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005425 toAudioPortConfig(&port->active_config);
5426 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005427 port->ext.mix.handle = mIoHandle;
5428 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5429}
5430
Eric Laurente0720872014-03-11 09:30:41 -07005431status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005432{
5433 const size_t SIZE = 256;
5434 char buffer[SIZE];
5435 String8 result;
5436
Eric Laurent4d416952014-08-10 14:07:09 -07005437 snprintf(buffer, SIZE, " ID: %d\n", mId);
5438 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005439 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5440 result.append(buffer);
5441 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5442 result.append(buffer);
5443 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5444 result.append(buffer);
5445 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5446 result.append(buffer);
5447 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5448 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005449 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5450 result.append(buffer);
5451
Eric Laurente552edb2014-03-10 17:42:56 -07005452 write(fd, result.string(), result.size());
5453
5454 return NO_ERROR;
5455}
5456
5457// --- StreamDescriptor class implementation
5458
Eric Laurente0720872014-03-11 09:30:41 -07005459AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005460 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5461{
5462 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5463}
5464
Eric Laurente0720872014-03-11 09:30:41 -07005465int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005466{
Eric Laurente0720872014-03-11 09:30:41 -07005467 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005468 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5469 if (mIndexCur.indexOfKey(device) < 0) {
5470 device = AUDIO_DEVICE_OUT_DEFAULT;
5471 }
5472 return mIndexCur.valueFor(device);
5473}
5474
Eric Laurente0720872014-03-11 09:30:41 -07005475void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005476{
5477 const size_t SIZE = 256;
5478 char buffer[SIZE];
5479 String8 result;
5480
5481 snprintf(buffer, SIZE, "%s %02d %02d ",
5482 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5483 result.append(buffer);
5484 for (size_t i = 0; i < mIndexCur.size(); i++) {
5485 snprintf(buffer, SIZE, "%04x : %02d, ",
5486 mIndexCur.keyAt(i),
5487 mIndexCur.valueAt(i));
5488 result.append(buffer);
5489 }
5490 result.append("\n");
5491
5492 write(fd, result.string(), result.size());
5493}
5494
5495// --- EffectDescriptor class implementation
5496
Eric Laurente0720872014-03-11 09:30:41 -07005497status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005498{
5499 const size_t SIZE = 256;
5500 char buffer[SIZE];
5501 String8 result;
5502
5503 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5504 result.append(buffer);
5505 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5506 result.append(buffer);
5507 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5508 result.append(buffer);
5509 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5510 result.append(buffer);
5511 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5512 result.append(buffer);
5513 write(fd, result.string(), result.size());
5514
5515 return NO_ERROR;
5516}
5517
Eric Laurent1c333e22014-05-20 10:48:17 -07005518// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005519
Eric Laurente0720872014-03-11 09:30:41 -07005520AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005521 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5522 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005523{
5524}
5525
Eric Laurente0720872014-03-11 09:30:41 -07005526AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005527{
5528 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005529 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005530 }
5531 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005532 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005533 }
5534 free((void *)mName);
5535}
5536
Eric Laurent1afeecb2014-05-14 08:52:28 -07005537status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5538{
5539 cnode *node = root->first_child;
5540
5541 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5542
5543 while (node) {
5544 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5545 profile->loadSamplingRates((char *)node->value);
5546 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5547 profile->loadFormats((char *)node->value);
5548 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5549 profile->loadInChannels((char *)node->value);
5550 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5551 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5552 mDeclaredDevices);
5553 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5554 profile->loadGains(node);
5555 }
5556 node = node->next;
5557 }
5558 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5559 "loadInput() invalid supported devices");
5560 ALOGW_IF(profile->mChannelMasks.size() == 0,
5561 "loadInput() invalid supported channel masks");
5562 ALOGW_IF(profile->mSamplingRates.size() == 0,
5563 "loadInput() invalid supported sampling rates");
5564 ALOGW_IF(profile->mFormats.size() == 0,
5565 "loadInput() invalid supported formats");
5566 if (!profile->mSupportedDevices.isEmpty() &&
5567 (profile->mChannelMasks.size() != 0) &&
5568 (profile->mSamplingRates.size() != 0) &&
5569 (profile->mFormats.size() != 0)) {
5570
5571 ALOGV("loadInput() adding input Supported Devices %04x",
5572 profile->mSupportedDevices.types());
5573
5574 mInputProfiles.add(profile);
5575 return NO_ERROR;
5576 } else {
5577 return BAD_VALUE;
5578 }
5579}
5580
5581status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5582{
5583 cnode *node = root->first_child;
5584
5585 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5586
5587 while (node) {
5588 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5589 profile->loadSamplingRates((char *)node->value);
5590 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5591 profile->loadFormats((char *)node->value);
5592 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5593 profile->loadOutChannels((char *)node->value);
5594 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5595 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5596 mDeclaredDevices);
5597 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5598 profile->mFlags = parseFlagNames((char *)node->value);
5599 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5600 profile->loadGains(node);
5601 }
5602 node = node->next;
5603 }
5604 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5605 "loadOutput() invalid supported devices");
5606 ALOGW_IF(profile->mChannelMasks.size() == 0,
5607 "loadOutput() invalid supported channel masks");
5608 ALOGW_IF(profile->mSamplingRates.size() == 0,
5609 "loadOutput() invalid supported sampling rates");
5610 ALOGW_IF(profile->mFormats.size() == 0,
5611 "loadOutput() invalid supported formats");
5612 if (!profile->mSupportedDevices.isEmpty() &&
5613 (profile->mChannelMasks.size() != 0) &&
5614 (profile->mSamplingRates.size() != 0) &&
5615 (profile->mFormats.size() != 0)) {
5616
5617 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5618 profile->mSupportedDevices.types(), profile->mFlags);
5619
5620 mOutputProfiles.add(profile);
5621 return NO_ERROR;
5622 } else {
5623 return BAD_VALUE;
5624 }
5625}
5626
5627status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5628{
5629 cnode *node = root->first_child;
5630
5631 audio_devices_t type = AUDIO_DEVICE_NONE;
5632 while (node) {
5633 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5634 type = parseDeviceNames((char *)node->value);
5635 break;
5636 }
5637 node = node->next;
5638 }
5639 if (type == AUDIO_DEVICE_NONE ||
5640 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5641 ALOGW("loadDevice() bad type %08x", type);
5642 return BAD_VALUE;
5643 }
5644 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5645 deviceDesc->mModule = this;
5646
5647 node = root->first_child;
5648 while (node) {
5649 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5650 deviceDesc->mAddress = String8((char *)node->value);
5651 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5652 if (audio_is_input_device(type)) {
5653 deviceDesc->loadInChannels((char *)node->value);
5654 } else {
5655 deviceDesc->loadOutChannels((char *)node->value);
5656 }
5657 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5658 deviceDesc->loadGains(node);
5659 }
5660 node = node->next;
5661 }
5662
5663 ALOGV("loadDevice() adding device name %s type %08x address %s",
5664 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5665
5666 mDeclaredDevices.add(deviceDesc);
5667
5668 return NO_ERROR;
5669}
5670
Eric Laurente0720872014-03-11 09:30:41 -07005671void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005672{
5673 const size_t SIZE = 256;
5674 char buffer[SIZE];
5675 String8 result;
5676
5677 snprintf(buffer, SIZE, " - name: %s\n", mName);
5678 result.append(buffer);
5679 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5680 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005681 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5682 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005683 write(fd, result.string(), result.size());
5684 if (mOutputProfiles.size()) {
5685 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5686 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005687 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005688 write(fd, buffer, strlen(buffer));
5689 mOutputProfiles[i]->dump(fd);
5690 }
5691 }
5692 if (mInputProfiles.size()) {
5693 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5694 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005695 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005696 write(fd, buffer, strlen(buffer));
5697 mInputProfiles[i]->dump(fd);
5698 }
5699 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005700 if (mDeclaredDevices.size()) {
5701 write(fd, " - devices:\n", strlen(" - devices:\n"));
5702 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5703 mDeclaredDevices[i]->dump(fd, 4, i);
5704 }
5705 }
Eric Laurente552edb2014-03-10 17:42:56 -07005706}
5707
Eric Laurent1c333e22014-05-20 10:48:17 -07005708// --- AudioPort class implementation
5709
Eric Laurenta121f902014-06-03 13:32:54 -07005710
5711AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5712 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005713 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005714{
5715 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5716 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5717}
5718
Eric Laurent1c333e22014-05-20 10:48:17 -07005719void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5720{
5721 port->role = mRole;
5722 port->type = mType;
5723 unsigned int i;
5724 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005725 if (mSamplingRates[i] != 0) {
5726 port->sample_rates[i] = mSamplingRates[i];
5727 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005728 }
5729 port->num_sample_rates = i;
5730 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005731 if (mChannelMasks[i] != 0) {
5732 port->channel_masks[i] = mChannelMasks[i];
5733 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005734 }
5735 port->num_channel_masks = i;
5736 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005737 if (mFormats[i] != 0) {
5738 port->formats[i] = mFormats[i];
5739 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005740 }
5741 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005742
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005743 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005744
5745 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5746 port->gains[i] = mGains[i]->mGain;
5747 }
5748 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005749}
5750
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005751void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5752 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5753 const uint32_t rate = port->mSamplingRates.itemAt(k);
5754 if (rate != 0) { // skip "dynamic" rates
5755 bool hasRate = false;
5756 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5757 if (rate == mSamplingRates.itemAt(l)) {
5758 hasRate = true;
5759 break;
5760 }
5761 }
5762 if (!hasRate) { // never import a sampling rate twice
5763 mSamplingRates.add(rate);
5764 }
5765 }
5766 }
5767 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5768 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5769 if (mask != 0) { // skip "dynamic" masks
5770 bool hasMask = false;
5771 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5772 if (mask == mChannelMasks.itemAt(l)) {
5773 hasMask = true;
5774 break;
5775 }
5776 }
5777 if (!hasMask) { // never import a channel mask twice
5778 mChannelMasks.add(mask);
5779 }
5780 }
5781 }
5782 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5783 const audio_format_t format = port->mFormats.itemAt(k);
5784 if (format != 0) { // skip "dynamic" formats
5785 bool hasFormat = false;
5786 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5787 if (format == mFormats.itemAt(l)) {
5788 hasFormat = true;
5789 break;
5790 }
5791 }
5792 if (!hasFormat) { // never import a channel mask twice
5793 mFormats.add(format);
5794 }
5795 }
5796 }
5797}
5798
5799void AudioPolicyManager::AudioPort::clearCapabilities() {
5800 mChannelMasks.clear();
5801 mFormats.clear();
5802 mSamplingRates.clear();
5803}
Eric Laurent1c333e22014-05-20 10:48:17 -07005804
5805void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5806{
5807 char *str = strtok(name, "|");
5808
5809 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5810 // rates should be read from the output stream after it is opened for the first time
5811 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5812 mSamplingRates.add(0);
5813 return;
5814 }
5815
5816 while (str != NULL) {
5817 uint32_t rate = atoi(str);
5818 if (rate != 0) {
5819 ALOGV("loadSamplingRates() adding rate %d", rate);
5820 mSamplingRates.add(rate);
5821 }
5822 str = strtok(NULL, "|");
5823 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005824}
5825
5826void AudioPolicyManager::AudioPort::loadFormats(char *name)
5827{
5828 char *str = strtok(name, "|");
5829
5830 // by convention, "0' in the first entry in mFormats indicates the supported formats
5831 // should be read from the output stream after it is opened for the first time
5832 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5833 mFormats.add(AUDIO_FORMAT_DEFAULT);
5834 return;
5835 }
5836
5837 while (str != NULL) {
5838 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5839 ARRAY_SIZE(sFormatNameToEnumTable),
5840 str);
5841 if (format != AUDIO_FORMAT_DEFAULT) {
5842 mFormats.add(format);
5843 }
5844 str = strtok(NULL, "|");
5845 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005846}
5847
5848void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5849{
5850 const char *str = strtok(name, "|");
5851
5852 ALOGV("loadInChannels() %s", name);
5853
5854 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5855 mChannelMasks.add(0);
5856 return;
5857 }
5858
5859 while (str != NULL) {
5860 audio_channel_mask_t channelMask =
5861 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5862 ARRAY_SIZE(sInChannelsNameToEnumTable),
5863 str);
5864 if (channelMask != 0) {
5865 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5866 mChannelMasks.add(channelMask);
5867 }
5868 str = strtok(NULL, "|");
5869 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005870}
5871
5872void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5873{
5874 const char *str = strtok(name, "|");
5875
5876 ALOGV("loadOutChannels() %s", name);
5877
5878 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5879 // masks should be read from the output stream after it is opened for the first time
5880 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5881 mChannelMasks.add(0);
5882 return;
5883 }
5884
5885 while (str != NULL) {
5886 audio_channel_mask_t channelMask =
5887 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5888 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5889 str);
5890 if (channelMask != 0) {
5891 mChannelMasks.add(channelMask);
5892 }
5893 str = strtok(NULL, "|");
5894 }
5895 return;
5896}
5897
Eric Laurent1afeecb2014-05-14 08:52:28 -07005898audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5899{
5900 const char *str = strtok(name, "|");
5901
5902 ALOGV("loadGainMode() %s", name);
5903 audio_gain_mode_t mode = 0;
5904 while (str != NULL) {
5905 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5906 ARRAY_SIZE(sGainModeNameToEnumTable),
5907 str);
5908 str = strtok(NULL, "|");
5909 }
5910 return mode;
5911}
5912
Eric Laurenta121f902014-06-03 13:32:54 -07005913void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005914{
5915 cnode *node = root->first_child;
5916
Eric Laurenta121f902014-06-03 13:32:54 -07005917 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005918
5919 while (node) {
5920 if (strcmp(node->name, GAIN_MODE) == 0) {
5921 gain->mGain.mode = loadGainMode((char *)node->value);
5922 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005923 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005924 gain->mGain.channel_mask =
5925 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5926 ARRAY_SIZE(sInChannelsNameToEnumTable),
5927 (char *)node->value);
5928 } else {
5929 gain->mGain.channel_mask =
5930 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5931 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5932 (char *)node->value);
5933 }
5934 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5935 gain->mGain.min_value = atoi((char *)node->value);
5936 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5937 gain->mGain.max_value = atoi((char *)node->value);
5938 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5939 gain->mGain.default_value = atoi((char *)node->value);
5940 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5941 gain->mGain.step_value = atoi((char *)node->value);
5942 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5943 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5944 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5945 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5946 }
5947 node = node->next;
5948 }
5949
5950 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5951 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5952
5953 if (gain->mGain.mode == 0) {
5954 return;
5955 }
5956 mGains.add(gain);
5957}
5958
5959void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5960{
5961 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005962 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005963 while (node) {
5964 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005965 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005966 node = node->next;
5967 }
5968}
5969
Glenn Kastencbd48022014-07-24 13:46:44 -07005970status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005971{
5972 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5973 if (mSamplingRates[i] == samplingRate) {
5974 return NO_ERROR;
5975 }
5976 }
5977 return BAD_VALUE;
5978}
5979
Glenn Kastencbd48022014-07-24 13:46:44 -07005980status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5981 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005982{
Glenn Kastencbd48022014-07-24 13:46:44 -07005983 // Search for the closest supported sampling rate that is above (preferred)
5984 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5985 // The sampling rates do not need to be sorted in ascending order.
5986 ssize_t maxBelow = -1;
5987 ssize_t minAbove = -1;
5988 uint32_t candidate;
5989 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5990 candidate = mSamplingRates[i];
5991 if (candidate == samplingRate) {
5992 if (updatedSamplingRate != NULL) {
5993 *updatedSamplingRate = candidate;
5994 }
5995 return NO_ERROR;
5996 }
5997 // candidate < desired
5998 if (candidate < samplingRate) {
5999 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6000 maxBelow = i;
6001 }
6002 // candidate > desired
6003 } else {
6004 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6005 minAbove = i;
6006 }
6007 }
6008 }
6009 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6010 // TODO Move these assumptions out.
6011 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6012 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6013 // due to approximation by an int32_t of the
6014 // phase increments
6015 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6016 if (minAbove >= 0) {
6017 candidate = mSamplingRates[minAbove];
6018 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6019 if (updatedSamplingRate != NULL) {
6020 *updatedSamplingRate = candidate;
6021 }
6022 return NO_ERROR;
6023 }
6024 }
6025 // But if we have to up-sample from a lower sampling rate, that's OK.
6026 if (maxBelow >= 0) {
6027 candidate = mSamplingRates[maxBelow];
6028 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6029 if (updatedSamplingRate != NULL) {
6030 *updatedSamplingRate = candidate;
6031 }
6032 return NO_ERROR;
6033 }
6034 }
6035 // leave updatedSamplingRate unmodified
6036 return BAD_VALUE;
6037}
6038
6039status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6040{
6041 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006042 if (mChannelMasks[i] == channelMask) {
6043 return NO_ERROR;
6044 }
6045 }
6046 return BAD_VALUE;
6047}
6048
Glenn Kastencbd48022014-07-24 13:46:44 -07006049status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6050 const
6051{
6052 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6053 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6054 // FIXME Does not handle multi-channel automatic conversions yet
6055 audio_channel_mask_t supported = mChannelMasks[i];
6056 if (supported == channelMask) {
6057 return NO_ERROR;
6058 }
6059 if (isRecordThread) {
6060 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6061 // FIXME Abstract this out to a table.
6062 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6063 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6064 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6065 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6066 return NO_ERROR;
6067 }
6068 }
6069 }
6070 return BAD_VALUE;
6071}
6072
Eric Laurenta121f902014-06-03 13:32:54 -07006073status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6074{
6075 for (size_t i = 0; i < mFormats.size(); i ++) {
6076 if (mFormats[i] == format) {
6077 return NO_ERROR;
6078 }
6079 }
6080 return BAD_VALUE;
6081}
6082
Eric Laurent1e693b52014-07-09 15:03:28 -07006083
6084uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6085{
6086 // special case for uninitialized dynamic profile
6087 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6088 return 0;
6089 }
6090
Eric Laurent828bcff2014-09-07 12:26:06 -07006091 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6092 // channel count / sampling rate combination chosen will be supported by the connected
6093 // sink
6094 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6095 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6096 uint32_t samplingRate = UINT_MAX;
6097 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6098 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6099 samplingRate = mSamplingRates[i];
6100 }
6101 }
6102 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6103 }
6104
Eric Laurent1e693b52014-07-09 15:03:28 -07006105 uint32_t samplingRate = 0;
6106 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6107
6108 // For mixed output and inputs, use max mixer sampling rates. Do not
6109 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006110 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006111 maxRate = UINT_MAX;
6112 }
6113 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6114 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6115 samplingRate = mSamplingRates[i];
6116 }
6117 }
6118 return samplingRate;
6119}
6120
6121audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6122{
6123 // special case for uninitialized dynamic profile
6124 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6125 return AUDIO_CHANNEL_NONE;
6126 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006127 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006128
6129 // For direct outputs, pick minimum channel count: this helps ensuring that the
6130 // channel count / sampling rate combination chosen will be supported by the connected
6131 // sink
6132 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6133 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6134 uint32_t channelCount = UINT_MAX;
6135 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6136 uint32_t cnlCount;
6137 if (mUseInChannelMask) {
6138 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6139 } else {
6140 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6141 }
6142 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6143 channelMask = mChannelMasks[i];
6144 channelCount = cnlCount;
6145 }
6146 }
6147 return channelMask;
6148 }
6149
Eric Laurent1e693b52014-07-09 15:03:28 -07006150 uint32_t channelCount = 0;
6151 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6152
6153 // For mixed output and inputs, use max mixer channel count. Do not
6154 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006155 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006156 maxCount = UINT_MAX;
6157 }
6158 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6159 uint32_t cnlCount;
6160 if (mUseInChannelMask) {
6161 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6162 } else {
6163 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6164 }
6165 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6166 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006167 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006168 }
6169 }
6170 return channelMask;
6171}
6172
Andy Hung9a605382014-07-28 16:16:31 -07006173/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006174const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6175 AUDIO_FORMAT_DEFAULT,
6176 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006177 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006178 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006179 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006180 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006181};
6182
6183int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6184 audio_format_t format2)
6185{
6186 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6187 // compressed format and better than any PCM format. This is by design of pickFormat()
6188 if (!audio_is_linear_pcm(format1)) {
6189 if (!audio_is_linear_pcm(format2)) {
6190 return 0;
6191 }
6192 return 1;
6193 }
6194 if (!audio_is_linear_pcm(format2)) {
6195 return -1;
6196 }
6197
6198 int index1 = -1, index2 = -1;
6199 for (size_t i = 0;
6200 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6201 i ++) {
6202 if (sPcmFormatCompareTable[i] == format1) {
6203 index1 = i;
6204 }
6205 if (sPcmFormatCompareTable[i] == format2) {
6206 index2 = i;
6207 }
6208 }
6209 // format1 not found => index1 < 0 => format2 > format1
6210 // format2 not found => index2 < 0 => format2 < format1
6211 return index1 - index2;
6212}
6213
6214audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6215{
6216 // special case for uninitialized dynamic profile
6217 if (mFormats.size() == 1 && mFormats[0] == 0) {
6218 return AUDIO_FORMAT_DEFAULT;
6219 }
6220
6221 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006222 audio_format_t bestFormat =
6223 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6224 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006225 // For mixed output and inputs, use best mixer output format. Do not
6226 // limit format otherwise
6227 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6228 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006229 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006230 bestFormat = AUDIO_FORMAT_INVALID;
6231 }
6232
6233 for (size_t i = 0; i < mFormats.size(); i ++) {
6234 if ((compareFormats(mFormats[i], format) > 0) &&
6235 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6236 format = mFormats[i];
6237 }
6238 }
6239 return format;
6240}
6241
Eric Laurenta121f902014-06-03 13:32:54 -07006242status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6243 int index) const
6244{
6245 if (index < 0 || (size_t)index >= mGains.size()) {
6246 return BAD_VALUE;
6247 }
6248 return mGains[index]->checkConfig(gainConfig);
6249}
6250
Eric Laurent1afeecb2014-05-14 08:52:28 -07006251void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6252{
6253 const size_t SIZE = 256;
6254 char buffer[SIZE];
6255 String8 result;
6256
6257 if (mName.size() != 0) {
6258 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6259 result.append(buffer);
6260 }
6261
6262 if (mSamplingRates.size() != 0) {
6263 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6264 result.append(buffer);
6265 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006266 if (i == 0 && mSamplingRates[i] == 0) {
6267 snprintf(buffer, SIZE, "Dynamic");
6268 } else {
6269 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6270 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006271 result.append(buffer);
6272 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6273 }
6274 result.append("\n");
6275 }
6276
6277 if (mChannelMasks.size() != 0) {
6278 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6279 result.append(buffer);
6280 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006281 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6282
6283 if (i == 0 && mChannelMasks[i] == 0) {
6284 snprintf(buffer, SIZE, "Dynamic");
6285 } else {
6286 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6287 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006288 result.append(buffer);
6289 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6290 }
6291 result.append("\n");
6292 }
6293
6294 if (mFormats.size() != 0) {
6295 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6296 result.append(buffer);
6297 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006298 const char *formatStr = enumToString(sFormatNameToEnumTable,
6299 ARRAY_SIZE(sFormatNameToEnumTable),
6300 mFormats[i]);
6301 if (i == 0 && strcmp(formatStr, "") == 0) {
6302 snprintf(buffer, SIZE, "Dynamic");
6303 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006304 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006305 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006306 result.append(buffer);
6307 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6308 }
6309 result.append("\n");
6310 }
6311 write(fd, result.string(), result.size());
6312 if (mGains.size() != 0) {
6313 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6314 write(fd, buffer, strlen(buffer) + 1);
6315 result.append(buffer);
6316 for (size_t i = 0; i < mGains.size(); i++) {
6317 mGains[i]->dump(fd, spaces + 2, i);
6318 }
6319 }
6320}
6321
6322// --- AudioGain class implementation
6323
Eric Laurenta121f902014-06-03 13:32:54 -07006324AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006325{
Eric Laurenta121f902014-06-03 13:32:54 -07006326 mIndex = index;
6327 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006328 memset(&mGain, 0, sizeof(struct audio_gain));
6329}
6330
Eric Laurenta121f902014-06-03 13:32:54 -07006331void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6332{
6333 config->index = mIndex;
6334 config->mode = mGain.mode;
6335 config->channel_mask = mGain.channel_mask;
6336 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6337 config->values[0] = mGain.default_value;
6338 } else {
6339 uint32_t numValues;
6340 if (mUseInChannelMask) {
6341 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6342 } else {
6343 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6344 }
6345 for (size_t i = 0; i < numValues; i++) {
6346 config->values[i] = mGain.default_value;
6347 }
6348 }
6349 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6350 config->ramp_duration_ms = mGain.min_ramp_ms;
6351 }
6352}
6353
6354status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6355{
6356 if ((config->mode & ~mGain.mode) != 0) {
6357 return BAD_VALUE;
6358 }
6359 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6360 if ((config->values[0] < mGain.min_value) ||
6361 (config->values[0] > mGain.max_value)) {
6362 return BAD_VALUE;
6363 }
6364 } else {
6365 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6366 return BAD_VALUE;
6367 }
6368 uint32_t numValues;
6369 if (mUseInChannelMask) {
6370 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6371 } else {
6372 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6373 }
6374 for (size_t i = 0; i < numValues; i++) {
6375 if ((config->values[i] < mGain.min_value) ||
6376 (config->values[i] > mGain.max_value)) {
6377 return BAD_VALUE;
6378 }
6379 }
6380 }
6381 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6382 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6383 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6384 return BAD_VALUE;
6385 }
6386 }
6387 return NO_ERROR;
6388}
6389
Eric Laurent1afeecb2014-05-14 08:52:28 -07006390void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6391{
6392 const size_t SIZE = 256;
6393 char buffer[SIZE];
6394 String8 result;
6395
6396 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6397 result.append(buffer);
6398 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6399 result.append(buffer);
6400 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6401 result.append(buffer);
6402 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6403 result.append(buffer);
6404 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6405 result.append(buffer);
6406 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6407 result.append(buffer);
6408 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6409 result.append(buffer);
6410 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6411 result.append(buffer);
6412 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6413 result.append(buffer);
6414
6415 write(fd, result.string(), result.size());
6416}
6417
Eric Laurent1f2f2232014-06-02 12:01:23 -07006418// --- AudioPortConfig class implementation
6419
6420AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6421{
6422 mSamplingRate = 0;
6423 mChannelMask = AUDIO_CHANNEL_NONE;
6424 mFormat = AUDIO_FORMAT_INVALID;
6425 mGain.index = -1;
6426}
6427
Eric Laurenta121f902014-06-03 13:32:54 -07006428status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6429 const struct audio_port_config *config,
6430 struct audio_port_config *backupConfig)
6431{
6432 struct audio_port_config localBackupConfig;
6433 status_t status = NO_ERROR;
6434
6435 localBackupConfig.config_mask = config->config_mask;
6436 toAudioPortConfig(&localBackupConfig);
6437
Marco Nelissen961ec212014-08-25 15:58:39 -07006438 sp<AudioPort> audioport = getAudioPort();
6439 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006440 status = NO_INIT;
6441 goto exit;
6442 }
6443 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006444 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006445 if (status != NO_ERROR) {
6446 goto exit;
6447 }
6448 mSamplingRate = config->sample_rate;
6449 }
6450 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006451 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006452 if (status != NO_ERROR) {
6453 goto exit;
6454 }
6455 mChannelMask = config->channel_mask;
6456 }
6457 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006458 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006459 if (status != NO_ERROR) {
6460 goto exit;
6461 }
6462 mFormat = config->format;
6463 }
6464 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006465 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006466 if (status != NO_ERROR) {
6467 goto exit;
6468 }
6469 mGain = config->gain;
6470 }
6471
6472exit:
6473 if (status != NO_ERROR) {
6474 applyAudioPortConfig(&localBackupConfig);
6475 }
6476 if (backupConfig != NULL) {
6477 *backupConfig = localBackupConfig;
6478 }
6479 return status;
6480}
6481
Eric Laurent1f2f2232014-06-02 12:01:23 -07006482void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6483 struct audio_port_config *dstConfig,
6484 const struct audio_port_config *srcConfig) const
6485{
6486 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6487 dstConfig->sample_rate = mSamplingRate;
6488 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6489 dstConfig->sample_rate = srcConfig->sample_rate;
6490 }
6491 } else {
6492 dstConfig->sample_rate = 0;
6493 }
6494 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6495 dstConfig->channel_mask = mChannelMask;
6496 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6497 dstConfig->channel_mask = srcConfig->channel_mask;
6498 }
6499 } else {
6500 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6501 }
6502 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6503 dstConfig->format = mFormat;
6504 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6505 dstConfig->format = srcConfig->format;
6506 }
6507 } else {
6508 dstConfig->format = AUDIO_FORMAT_INVALID;
6509 }
6510 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6511 dstConfig->gain = mGain;
6512 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6513 dstConfig->gain = srcConfig->gain;
6514 }
6515 } else {
6516 dstConfig->gain.index = -1;
6517 }
6518 if (dstConfig->gain.index != -1) {
6519 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6520 } else {
6521 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6522 }
6523}
6524
Eric Laurent1c333e22014-05-20 10:48:17 -07006525// --- IOProfile class implementation
6526
Eric Laurent1afeecb2014-05-14 08:52:28 -07006527AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006528 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006529 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006530{
6531}
6532
Eric Laurente0720872014-03-11 09:30:41 -07006533AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006534{
6535}
6536
6537// checks if the IO profile is compatible with specified parameters.
6538// Sampling rate, format and channel mask must be specified in order to
6539// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006540bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006541 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006542 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006543 audio_format_t format,
6544 audio_channel_mask_t channelMask,
6545 audio_output_flags_t flags) const
6546{
Glenn Kastencbd48022014-07-24 13:46:44 -07006547 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6548 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6549 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006550
Glenn Kastencbd48022014-07-24 13:46:44 -07006551 if ((mSupportedDevices.types() & device) != device) {
6552 return false;
6553 }
6554
6555 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006556 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006557 }
6558 uint32_t myUpdatedSamplingRate = samplingRate;
6559 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006560 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006561 }
6562 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6563 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006564 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006565 }
6566
6567 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6568 return false;
6569 }
6570
6571 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6572 checkExactChannelMask(channelMask) != NO_ERROR)) {
6573 return false;
6574 }
6575 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6576 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6577 return false;
6578 }
6579
6580 if (isPlaybackThread && (mFlags & flags) != flags) {
6581 return false;
6582 }
6583 // The only input flag that is allowed to be different is the fast flag.
6584 // An existing fast stream is compatible with a normal track request.
6585 // An existing normal stream is compatible with a fast track request,
6586 // but the fast request will be denied by AudioFlinger and converted to normal track.
6587 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6588 ~AUDIO_INPUT_FLAG_FAST)) {
6589 return false;
6590 }
6591
6592 if (updatedSamplingRate != NULL) {
6593 *updatedSamplingRate = myUpdatedSamplingRate;
6594 }
6595 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006596}
6597
Eric Laurente0720872014-03-11 09:30:41 -07006598void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006599{
6600 const size_t SIZE = 256;
6601 char buffer[SIZE];
6602 String8 result;
6603
Eric Laurent1afeecb2014-05-14 08:52:28 -07006604 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006605
Eric Laurente552edb2014-03-10 17:42:56 -07006606 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6607 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006608 snprintf(buffer, SIZE, " - devices:\n");
6609 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006610 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006611 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6612 mSupportedDevices[i]->dump(fd, 6, i);
6613 }
Eric Laurente552edb2014-03-10 17:42:56 -07006614}
6615
Eric Laurentd4692962014-05-05 18:13:44 -07006616void AudioPolicyManager::IOProfile::log()
6617{
6618 const size_t SIZE = 256;
6619 char buffer[SIZE];
6620 String8 result;
6621
6622 ALOGV(" - sampling rates: ");
6623 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6624 ALOGV(" %d", mSamplingRates[i]);
6625 }
6626
6627 ALOGV(" - channel masks: ");
6628 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6629 ALOGV(" 0x%04x", mChannelMasks[i]);
6630 }
6631
6632 ALOGV(" - formats: ");
6633 for (size_t i = 0; i < mFormats.size(); i++) {
6634 ALOGV(" 0x%08x", mFormats[i]);
6635 }
6636
6637 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6638 ALOGV(" - flags: 0x%04x\n", mFlags);
6639}
6640
6641
Eric Laurent3a4311c2014-03-17 12:00:47 -07006642// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006643
Eric Laurent1f2f2232014-06-02 12:01:23 -07006644
6645AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6646 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6647 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6648 AUDIO_PORT_ROLE_SOURCE,
6649 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006650 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006651{
Eric Laurenta121f902014-06-03 13:32:54 -07006652 if (mGains.size() > 0) {
6653 mGains[0]->getDefaultConfig(&mGain);
6654 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006655}
6656
Eric Laurent3a4311c2014-03-17 12:00:47 -07006657bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006658{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006659 // Devices are considered equal if they:
6660 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6661 // - have the same address or one device does not specify the address
6662 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006663 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006664 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006665 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006666 mChannelMask == other->mChannelMask);
6667}
6668
6669void AudioPolicyManager::DeviceVector::refreshTypes()
6670{
Eric Laurent1c333e22014-05-20 10:48:17 -07006671 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006672 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006673 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006674 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006675 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006676}
6677
6678ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6679{
6680 for(size_t i = 0; i < size(); i++) {
6681 if (item->equals(itemAt(i))) {
6682 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006683 }
6684 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006685 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006686}
6687
Eric Laurent3a4311c2014-03-17 12:00:47 -07006688ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006689{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006690 ssize_t ret = indexOf(item);
6691
6692 if (ret < 0) {
6693 ret = SortedVector::add(item);
6694 if (ret >= 0) {
6695 refreshTypes();
6696 }
6697 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006698 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006699 ret = -1;
6700 }
6701 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006702}
6703
Eric Laurent3a4311c2014-03-17 12:00:47 -07006704ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6705{
6706 size_t i;
6707 ssize_t ret = indexOf(item);
6708
6709 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006710 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006711 } else {
6712 ret = SortedVector::removeAt(ret);
6713 if (ret >= 0) {
6714 refreshTypes();
6715 }
6716 }
6717 return ret;
6718}
6719
6720void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6721{
6722 DeviceVector deviceList;
6723
6724 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6725 types &= ~role_bit;
6726
6727 while (types) {
6728 uint32_t i = 31 - __builtin_clz(types);
6729 uint32_t type = 1 << i;
6730 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006731 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006732 }
6733}
6734
Eric Laurent1afeecb2014-05-14 08:52:28 -07006735void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6736 const DeviceVector& declaredDevices)
6737{
6738 char *devName = strtok(name, "|");
6739 while (devName != NULL) {
6740 if (strlen(devName) != 0) {
6741 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6742 ARRAY_SIZE(sDeviceNameToEnumTable),
6743 devName);
6744 if (type != AUDIO_DEVICE_NONE) {
6745 add(new DeviceDescriptor(String8(""), type));
6746 } else {
6747 sp<DeviceDescriptor> deviceDesc =
6748 declaredDevices.getDeviceFromName(String8(devName));
6749 if (deviceDesc != 0) {
6750 add(deviceDesc);
6751 }
6752 }
6753 }
6754 devName = strtok(NULL, "|");
6755 }
6756}
6757
Eric Laurent1c333e22014-05-20 10:48:17 -07006758sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6759 audio_devices_t type, String8 address) const
6760{
6761 sp<DeviceDescriptor> device;
6762 for (size_t i = 0; i < size(); i++) {
6763 if (itemAt(i)->mDeviceType == type) {
6764 device = itemAt(i);
6765 if (itemAt(i)->mAddress = address) {
6766 break;
6767 }
6768 }
6769 }
6770 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6771 type, address.string(), device.get());
6772 return device;
6773}
6774
Eric Laurent6a94d692014-05-20 11:18:06 -07006775sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6776 audio_port_handle_t id) const
6777{
6778 sp<DeviceDescriptor> device;
6779 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006780 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006781 if (itemAt(i)->mId == id) {
6782 device = itemAt(i);
6783 break;
6784 }
6785 }
6786 return device;
6787}
6788
Eric Laurent1c333e22014-05-20 10:48:17 -07006789AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6790 audio_devices_t type) const
6791{
6792 DeviceVector devices;
6793 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6794 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6795 devices.add(itemAt(i));
6796 type &= ~itemAt(i)->mDeviceType;
6797 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6798 itemAt(i)->mDeviceType, itemAt(i).get());
6799 }
6800 }
6801 return devices;
6802}
6803
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006804AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6805 audio_devices_t type, String8 address) const
6806{
6807 DeviceVector devices;
6808 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6809 for (size_t i = 0; i < size(); i++) {
6810 //ALOGV(" at i=%d: device=%x, addr=%s",
6811 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6812 if (itemAt(i)->mDeviceType == type) {
6813 if (itemAt(i)->mAddress == address) {
6814 //ALOGV(" found matching address %s", address.string());
6815 devices.add(itemAt(i));
6816 }
6817 }
6818 }
6819 return devices;
6820}
6821
Eric Laurent1afeecb2014-05-14 08:52:28 -07006822sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6823 const String8& name) const
6824{
6825 sp<DeviceDescriptor> device;
6826 for (size_t i = 0; i < size(); i++) {
6827 if (itemAt(i)->mName == name) {
6828 device = itemAt(i);
6829 break;
6830 }
6831 }
6832 return device;
6833}
6834
Eric Laurent6a94d692014-05-20 11:18:06 -07006835void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6836 struct audio_port_config *dstConfig,
6837 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006838{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006839 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6840 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006841 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006842 }
6843
6844 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6845
Eric Laurent6a94d692014-05-20 11:18:06 -07006846 dstConfig->id = mId;
6847 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006848 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006849 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006850 dstConfig->ext.device.type = mDeviceType;
6851 dstConfig->ext.device.hw_module = mModule->mHandle;
6852 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006853}
6854
6855void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6856{
Eric Laurent83b88082014-06-20 18:31:16 -07006857 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006858 AudioPort::toAudioPort(port);
6859 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006860 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006861 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006862 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006863 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6864}
6865
Eric Laurent1afeecb2014-05-14 08:52:28 -07006866status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006867{
6868 const size_t SIZE = 256;
6869 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006870 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006871
Eric Laurent1afeecb2014-05-14 08:52:28 -07006872 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6873 result.append(buffer);
6874 if (mId != 0) {
6875 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6876 result.append(buffer);
6877 }
6878 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6879 enumToString(sDeviceNameToEnumTable,
6880 ARRAY_SIZE(sDeviceNameToEnumTable),
6881 mDeviceType));
6882 result.append(buffer);
6883 if (mAddress.size() != 0) {
6884 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6885 result.append(buffer);
6886 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006887 write(fd, result.string(), result.size());
6888 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006889
6890 return NO_ERROR;
6891}
6892
Eric Laurent4d416952014-08-10 14:07:09 -07006893status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6894{
6895 const size_t SIZE = 256;
6896 char buffer[SIZE];
6897 String8 result;
6898
6899
6900 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6901 result.append(buffer);
6902 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6903 result.append(buffer);
6904 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6905 result.append(buffer);
6906 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6907 result.append(buffer);
6908 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6909 result.append(buffer);
6910 for (size_t i = 0; i < mPatch.num_sources; i++) {
6911 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6912 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6913 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6914 ARRAY_SIZE(sDeviceNameToEnumTable),
6915 mPatch.sources[i].ext.device.type));
6916 } else {
6917 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6918 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6919 }
6920 result.append(buffer);
6921 }
6922 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6923 result.append(buffer);
6924 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6925 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
6926 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6927 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
6928 ARRAY_SIZE(sDeviceNameToEnumTable),
6929 mPatch.sinks[i].ext.device.type));
6930 } else {
6931 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6932 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
6933 }
6934 result.append(buffer);
6935 }
6936
6937 write(fd, result.string(), result.size());
6938 return NO_ERROR;
6939}
Eric Laurent3a4311c2014-03-17 12:00:47 -07006940
6941// --- audio_policy.conf file parsing
6942
Eric Laurente0720872014-03-11 09:30:41 -07006943audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006944{
6945 uint32_t flag = 0;
6946
6947 // it is OK to cast name to non const here as we are not going to use it after
6948 // strtok() modifies it
6949 char *flagName = strtok(name, "|");
6950 while (flagName != NULL) {
6951 if (strlen(flagName) != 0) {
6952 flag |= stringToEnum(sFlagNameToEnumTable,
6953 ARRAY_SIZE(sFlagNameToEnumTable),
6954 flagName);
6955 }
6956 flagName = strtok(NULL, "|");
6957 }
6958 //force direct flag if offload flag is set: offloading implies a direct output stream
6959 // and all common behaviors are driven by checking only the direct flag
6960 // this should normally be set appropriately in the policy configuration file
6961 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6962 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6963 }
6964
6965 return (audio_output_flags_t)flag;
6966}
6967
Eric Laurente0720872014-03-11 09:30:41 -07006968audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006969{
6970 uint32_t device = 0;
6971
6972 char *devName = strtok(name, "|");
6973 while (devName != NULL) {
6974 if (strlen(devName) != 0) {
6975 device |= stringToEnum(sDeviceNameToEnumTable,
6976 ARRAY_SIZE(sDeviceNameToEnumTable),
6977 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006978 }
Eric Laurente552edb2014-03-10 17:42:56 -07006979 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006980 }
Eric Laurente552edb2014-03-10 17:42:56 -07006981 return device;
6982}
6983
Eric Laurente0720872014-03-11 09:30:41 -07006984void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006985{
Eric Laurente552edb2014-03-10 17:42:56 -07006986 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006987 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006988 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006989
Eric Laurent1afeecb2014-05-14 08:52:28 -07006990 node = config_find(root, DEVICES_TAG);
6991 if (node != NULL) {
6992 node = node->first_child;
6993 while (node) {
6994 ALOGV("loadHwModule() loading device %s", node->name);
6995 status_t tmpStatus = module->loadDevice(node);
6996 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6997 status = tmpStatus;
6998 }
6999 node = node->next;
7000 }
7001 }
7002 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007003 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007004 node = node->first_child;
7005 while (node) {
7006 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007007 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007008 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7009 status = tmpStatus;
7010 }
7011 node = node->next;
7012 }
7013 }
7014 node = config_find(root, INPUTS_TAG);
7015 if (node != NULL) {
7016 node = node->first_child;
7017 while (node) {
7018 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007019 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007020 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7021 status = tmpStatus;
7022 }
7023 node = node->next;
7024 }
7025 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007026 loadGlobalConfig(root, module);
7027
Eric Laurente552edb2014-03-10 17:42:56 -07007028 if (status == NO_ERROR) {
7029 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007030 }
7031}
7032
Eric Laurente0720872014-03-11 09:30:41 -07007033void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007034{
7035 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7036 if (node == NULL) {
7037 return;
7038 }
7039
7040 node = node->first_child;
7041 while (node) {
7042 ALOGV("loadHwModules() loading module %s", node->name);
7043 loadHwModule(node);
7044 node = node->next;
7045 }
7046}
7047
Eric Laurent1f2f2232014-06-02 12:01:23 -07007048void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007049{
7050 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007051
Eric Laurente552edb2014-03-10 17:42:56 -07007052 if (node == NULL) {
7053 return;
7054 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007055 DeviceVector declaredDevices;
7056 if (module != NULL) {
7057 declaredDevices = module->mDeclaredDevices;
7058 }
7059
Eric Laurente552edb2014-03-10 17:42:56 -07007060 node = node->first_child;
7061 while (node) {
7062 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007063 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7064 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007065 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7066 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007067 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007068 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007069 ARRAY_SIZE(sDeviceNameToEnumTable),
7070 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007071 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007072 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007073 } else {
7074 ALOGW("loadGlobalConfig() default device not specified");
7075 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007076 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007077 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007078 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7079 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007080 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007081 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7082 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7083 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007084 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7085 uint32_t major, minor;
7086 sscanf((char *)node->value, "%u.%u", &major, &minor);
7087 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7088 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7089 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007090 }
7091 node = node->next;
7092 }
7093}
7094
Eric Laurente0720872014-03-11 09:30:41 -07007095status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007096{
7097 cnode *root;
7098 char *data;
7099
7100 data = (char *)load_file(path, NULL);
7101 if (data == NULL) {
7102 return -ENODEV;
7103 }
7104 root = config_node("", "");
7105 config_load(root, data);
7106
Eric Laurente552edb2014-03-10 17:42:56 -07007107 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007108 // legacy audio_policy.conf files have one global_configuration section
7109 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007110 config_free(root);
7111 free(root);
7112 free(data);
7113
7114 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7115
7116 return NO_ERROR;
7117}
7118
Eric Laurente0720872014-03-11 09:30:41 -07007119void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007120{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007121 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007122 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007123 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7124 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007125 mAvailableOutputDevices.add(mDefaultOutputDevice);
7126 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007127
7128 module = new HwModule("primary");
7129
Eric Laurent1afeecb2014-05-14 08:52:28 -07007130 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007131 profile->mSamplingRates.add(44100);
7132 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7133 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007134 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007135 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7136 module->mOutputProfiles.add(profile);
7137
Eric Laurent1afeecb2014-05-14 08:52:28 -07007138 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007139 profile->mSamplingRates.add(8000);
7140 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7141 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007142 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007143 module->mInputProfiles.add(profile);
7144
7145 mHwModules.add(module);
7146}
7147
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007148audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7149{
7150 // flags to stream type mapping
7151 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7152 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7153 }
7154 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7155 return AUDIO_STREAM_BLUETOOTH_SCO;
7156 }
7157
7158 // usage to stream type mapping
7159 switch (attr->usage) {
7160 case AUDIO_USAGE_MEDIA:
7161 case AUDIO_USAGE_GAME:
7162 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7163 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7164 return AUDIO_STREAM_MUSIC;
7165 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7166 return AUDIO_STREAM_SYSTEM;
7167 case AUDIO_USAGE_VOICE_COMMUNICATION:
7168 return AUDIO_STREAM_VOICE_CALL;
7169
7170 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7171 return AUDIO_STREAM_DTMF;
7172
7173 case AUDIO_USAGE_ALARM:
7174 return AUDIO_STREAM_ALARM;
7175 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7176 return AUDIO_STREAM_RING;
7177
7178 case AUDIO_USAGE_NOTIFICATION:
7179 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7180 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7181 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7182 case AUDIO_USAGE_NOTIFICATION_EVENT:
7183 return AUDIO_STREAM_NOTIFICATION;
7184
7185 case AUDIO_USAGE_UNKNOWN:
7186 default:
7187 return AUDIO_STREAM_MUSIC;
7188 }
7189}
Eric Laurente552edb2014-03-10 17:42:56 -07007190}; // namespace android