blob: d0b990f08170d4474b99dd83515f283c3c3aad1f [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
Eric Laurent5dbe4712014-09-19 19:04:57 -0700115const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700116 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
Eric Laurent5dbe4712014-09-19 19:04:57 -0700125const StringToEnum sInputFlagNameToEnumTable[] = {
126 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
128};
129
Eric Laurent3a4311c2014-03-17 12:00:47 -0700130const StringToEnum sFormatNameToEnumTable[] = {
131 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
137 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
152 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
153 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
154 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155};
156
157const StringToEnum sOutChannelsNameToEnumTable[] = {
158 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
163};
164
165const StringToEnum sInChannelsNameToEnumTable[] = {
166 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
169};
170
Eric Laurent1afeecb2014-05-14 08:52:28 -0700171const StringToEnum sGainModeNameToEnumTable[] = {
172 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
173 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
174 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
175};
176
Eric Laurent3a4311c2014-03-17 12:00:47 -0700177
178uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
179 size_t size,
180 const char *name)
181{
182 for (size_t i = 0; i < size; i++) {
183 if (strcmp(table[i].name, name) == 0) {
184 ALOGV("stringToEnum() found %s", table[i].name);
185 return table[i].value;
186 }
187 }
188 return 0;
189}
190
191const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
192 size_t size,
193 uint32_t value)
194{
195 for (size_t i = 0; i < size; i++) {
196 if (table[i].value == value) {
197 return table[i].name;
198 }
199 }
200 return "";
201}
202
203bool AudioPolicyManager::stringToBool(const char *value)
204{
205 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
206}
207
208
209// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700210// AudioPolicyInterface implementation
211// ----------------------------------------------------------------------------
212
213
Eric Laurente0720872014-03-11 09:30:41 -0700214status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700216 const char *device_address)
217{
Eric Laurent22226012014-08-01 17:00:54 -0700218 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700219
Eric Laurent22226012014-08-01 17:00:54 -0700220 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
221 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700222
223 // connect/disconnect only 1 device at a time
224 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
225
Eric Laurente552edb2014-03-10 17:42:56 -0700226 // handle output devices
227 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700228 SortedVector <audio_io_handle_t> outputs;
229
Eric Laurent1afeecb2014-05-14 08:52:28 -0700230 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
231 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700232 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
233
Eric Laurente552edb2014-03-10 17:42:56 -0700234 // save a copy of the opened output descriptors before any output is opened or closed
235 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
236 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700237 switch (state)
238 {
239 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700240 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700241 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700242 ALOGW("setDeviceConnectionState() device already connected: %x", device);
243 return INVALID_OPERATION;
244 }
245 ALOGV("setDeviceConnectionState() connecting device %x", device);
246
Eric Laurente552edb2014-03-10 17:42:56 -0700247 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700248 index = mAvailableOutputDevices.add(devDesc);
249 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700250 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700251 if (module == 0) {
252 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
253 device);
254 mAvailableOutputDevices.remove(devDesc);
255 return INVALID_OPERATION;
256 }
257 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700258 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700259 } else {
260 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700261 }
262
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700263 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700264 mAvailableOutputDevices.remove(devDesc);
265 return INVALID_OPERATION;
266 }
267 // outputs should never be empty here
268 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
269 "checkOutputsForDevice() returned no outputs but status OK");
270 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
271 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700272 break;
273 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700274 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700275 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700276 ALOGW("setDeviceConnectionState() device not connected: %x", device);
277 return INVALID_OPERATION;
278 }
279
Paul McLean5c477aa2014-08-20 16:47:57 -0700280 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
281
282 // Set Disconnect to HALs
283 AudioParameter param = AudioParameter(address);
284 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
285 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
286
Eric Laurente552edb2014-03-10 17:42:56 -0700287 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700288 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700289
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700290 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700291 } break;
292
293 default:
294 ALOGE("setDeviceConnectionState() invalid state: %x", state);
295 return BAD_VALUE;
296 }
297
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
299 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700300 checkA2dpSuspend();
301 checkOutputForAllStrategies();
302 // outputs must be closed after checkOutputForAllStrategies() is executed
303 if (!outputs.isEmpty()) {
304 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700305 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700306 // close unused outputs after device disconnection or direct outputs that have been
307 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700308 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700309 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
310 (desc->mDirectOpenCount == 0))) {
311 closeOutput(outputs[i]);
312 }
313 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700314 // check again after closing A2DP output to reset mA2dpSuspended if needed
315 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700316 }
317
318 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700319 if (mPhoneState == AUDIO_MODE_IN_CALL) {
320 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
321 updateCallRouting(newDevice);
322 }
Eric Laurente552edb2014-03-10 17:42:56 -0700323 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 audio_io_handle_t output = mOutputs.keyAt(i);
325 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
326 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
327 true /*fromCache*/);
328 // do not force device change on duplicated output because if device is 0, it will
329 // also force a device 0 for the two outputs it is duplicated to which may override
330 // a valid device selection on those outputs.
331 bool force = !mOutputs.valueAt(i)->isDuplicated()
332 && (!deviceDistinguishesOnAddress(device)
333 // always force when disconnecting (a non-duplicated device)
334 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
335 setOutputDevice(output, newDevice, force, 0);
336 }
Eric Laurente552edb2014-03-10 17:42:56 -0700337 }
338
Eric Laurent72aa32f2014-05-30 18:51:48 -0700339 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700340 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700341 } // end if is output device
342
Eric Laurente552edb2014-03-10 17:42:56 -0700343 // handle input devices
344 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700345 SortedVector <audio_io_handle_t> inputs;
346
Eric Laurent1afeecb2014-05-14 08:52:28 -0700347 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
348 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700350 switch (state)
351 {
352 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700353 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700355 ALOGW("setDeviceConnectionState() device already connected: %d", device);
356 return INVALID_OPERATION;
357 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700358 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700359 if (module == NULL) {
360 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
361 device);
362 return INVALID_OPERATION;
363 }
Eric Laurentd4692962014-05-05 18:13:44 -0700364 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
365 return INVALID_OPERATION;
366 }
367
Eric Laurent3a4311c2014-03-17 12:00:47 -0700368 index = mAvailableInputDevices.add(devDesc);
369 if (index >= 0) {
370 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700371 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700372 } else {
373 return NO_MEMORY;
374 }
Eric Laurentd4692962014-05-05 18:13:44 -0700375 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700376
377 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700378 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700379 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700380 ALOGW("setDeviceConnectionState() device not connected: %d", device);
381 return INVALID_OPERATION;
382 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700383
384 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
385
386 // Set Disconnect to HALs
387 AudioParameter param = AudioParameter(address);
388 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
389 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
390
Eric Laurentd4692962014-05-05 18:13:44 -0700391 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700392 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700393
Eric Laurentd4692962014-05-05 18:13:44 -0700394 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700395
396 default:
397 ALOGE("setDeviceConnectionState() invalid state: %x", state);
398 return BAD_VALUE;
399 }
400
Eric Laurentd4692962014-05-05 18:13:44 -0700401 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700402
Eric Laurentc2730ba2014-07-20 15:47:07 -0700403 if (mPhoneState == AUDIO_MODE_IN_CALL) {
404 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
405 updateCallRouting(newDevice);
406 }
407
Eric Laurentb52c1522014-05-20 11:27:36 -0700408 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700409 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 ALOGW("setDeviceConnectionState() invalid device: %x", device);
413 return BAD_VALUE;
414}
415
Eric Laurente0720872014-03-11 09:30:41 -0700416audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700417 const char *device_address)
418{
Eric Laurent3b73df72014-03-11 09:06:29 -0700419 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700420 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700421 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700422 ssize_t index;
423 DeviceVector *deviceVector;
424
Eric Laurente552edb2014-03-10 17:42:56 -0700425 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700426 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700427 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700428 deviceVector = &mAvailableInputDevices;
429 } else {
430 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
431 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700432 }
433
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 index = deviceVector->indexOf(devDesc);
435 if (index >= 0) {
436 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
437 } else {
438 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
439 }
Eric Laurente552edb2014-03-10 17:42:56 -0700440}
441
Eric Laurentc2730ba2014-07-20 15:47:07 -0700442void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
443{
444 bool createTxPatch = false;
445 struct audio_patch patch;
446 patch.num_sources = 1;
447 patch.num_sinks = 1;
448 status_t status;
449 audio_patch_handle_t afPatchHandle;
450 DeviceVector deviceList;
451
452 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
453 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
454
455 // release existing RX patch if any
456 if (mCallRxPatch != 0) {
457 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
458 mCallRxPatch.clear();
459 }
460 // release TX patch if any
461 if (mCallTxPatch != 0) {
462 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
463 mCallTxPatch.clear();
464 }
465
466 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
467 // via setOutputDevice() on primary output.
468 // Otherwise, create two audio patches for TX and RX path.
469 if (availablePrimaryOutputDevices() & rxDevice) {
470 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
471 // If the TX device is also on the primary HW module, setOutputDevice() will take care
472 // of it due to legacy implementation. If not, create a patch.
473 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
474 == AUDIO_DEVICE_NONE) {
475 createTxPatch = true;
476 }
477 } else {
478 // create RX path audio patch
479 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
480 ALOG_ASSERT(!deviceList.isEmpty(),
481 "updateCallRouting() selected device not in output device list");
482 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
483 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
484 ALOG_ASSERT(!deviceList.isEmpty(),
485 "updateCallRouting() no telephony RX device");
486 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
487
488 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
489 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
490
491 // request to reuse existing output stream if one is already opened to reach the RX device
492 SortedVector<audio_io_handle_t> outputs =
493 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700494 audio_io_handle_t output = selectOutput(outputs,
495 AUDIO_OUTPUT_FLAG_NONE,
496 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700497 if (output != AUDIO_IO_HANDLE_NONE) {
498 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
499 ALOG_ASSERT(!outputDesc->isDuplicated(),
500 "updateCallRouting() RX device output is duplicated");
501 outputDesc->toAudioPortConfig(&patch.sources[1]);
502 patch.num_sources = 2;
503 }
504
505 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
506 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
507 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
508 status);
509 if (status == NO_ERROR) {
510 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
511 &patch, mUidCached);
512 mCallRxPatch->mAfPatchHandle = afPatchHandle;
513 mCallRxPatch->mUid = mUidCached;
514 }
515 createTxPatch = true;
516 }
517 if (createTxPatch) {
518
519 struct audio_patch patch;
520 patch.num_sources = 1;
521 patch.num_sinks = 1;
522 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
523 ALOG_ASSERT(!deviceList.isEmpty(),
524 "updateCallRouting() selected device not in input device list");
525 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
526 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
527 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
528 ALOG_ASSERT(!deviceList.isEmpty(),
529 "updateCallRouting() no telephony TX device");
530 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
531 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
532
533 SortedVector<audio_io_handle_t> outputs =
534 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700535 audio_io_handle_t output = selectOutput(outputs,
536 AUDIO_OUTPUT_FLAG_NONE,
537 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700538 // request to reuse existing output stream if one is already opened to reach the TX
539 // path output device
540 if (output != AUDIO_IO_HANDLE_NONE) {
541 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
542 ALOG_ASSERT(!outputDesc->isDuplicated(),
543 "updateCallRouting() RX device output is duplicated");
544 outputDesc->toAudioPortConfig(&patch.sources[1]);
545 patch.num_sources = 2;
546 }
547
548 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
549 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
550 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
551 status);
552 if (status == NO_ERROR) {
553 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
554 &patch, mUidCached);
555 mCallTxPatch->mAfPatchHandle = afPatchHandle;
556 mCallTxPatch->mUid = mUidCached;
557 }
558 }
559}
560
Eric Laurente0720872014-03-11 09:30:41 -0700561void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700562{
563 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700564 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700565 ALOGW("setPhoneState() invalid state %d", state);
566 return;
567 }
568
569 if (state == mPhoneState ) {
570 ALOGW("setPhoneState() setting same state %d", state);
571 return;
572 }
573
574 // if leaving call state, handle special case of active streams
575 // pertaining to sonification strategy see handleIncallSonification()
576 if (isInCall()) {
577 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700578 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
579 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700580 }
581 }
582
583 // store previous phone state for management of sonification strategy below
584 int oldState = mPhoneState;
585 mPhoneState = state;
586 bool force = false;
587
588 // are we entering or starting a call
589 if (!isStateInCall(oldState) && isStateInCall(state)) {
590 ALOGV(" Entering call in setPhoneState()");
591 // force routing command to audio hardware when starting a call
592 // even if no device change is needed
593 force = true;
594 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
595 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
596 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
597 }
598 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
599 ALOGV(" Exiting call in setPhoneState()");
600 // force routing command to audio hardware when exiting a call
601 // even if no device change is needed
602 force = true;
603 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
604 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
605 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
606 }
607 } else if (isStateInCall(state) && (state != oldState)) {
608 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
609 // force routing command to audio hardware when switching between telephony and VoIP
610 // even if no device change is needed
611 force = true;
612 }
613
614 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700615 checkA2dpSuspend();
616 checkOutputForAllStrategies();
617 updateDevicesAndOutputs();
618
Eric Laurent1f2f2232014-06-02 12:01:23 -0700619 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700620
Eric Laurente552edb2014-03-10 17:42:56 -0700621 int delayMs = 0;
622 if (isStateInCall(state)) {
623 nsecs_t sysTime = systemTime();
624 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700625 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700626 // mute media and sonification strategies and delay device switch by the largest
627 // latency of any output where either strategy is active.
628 // This avoid sending the ring tone or music tail into the earpiece or headset.
629 if ((desc->isStrategyActive(STRATEGY_MEDIA,
630 SONIFICATION_HEADSET_MUSIC_DELAY,
631 sysTime) ||
632 desc->isStrategyActive(STRATEGY_SONIFICATION,
633 SONIFICATION_HEADSET_MUSIC_DELAY,
634 sysTime)) &&
635 (delayMs < (int)desc->mLatency*2)) {
636 delayMs = desc->mLatency*2;
637 }
638 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
639 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
640 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
641 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
642 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
643 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
644 }
645 }
646
Eric Laurentc2730ba2014-07-20 15:47:07 -0700647 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
648 // the device returned is not necessarily reachable via this output
649 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
650 // force routing command to audio hardware when ending call
651 // even if no device change is needed
652 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
653 rxDevice = hwOutputDesc->device();
654 }
Eric Laurente552edb2014-03-10 17:42:56 -0700655
Eric Laurentc2730ba2014-07-20 15:47:07 -0700656 if (state == AUDIO_MODE_IN_CALL) {
657 updateCallRouting(rxDevice, delayMs);
658 } else if (oldState == AUDIO_MODE_IN_CALL) {
659 if (mCallRxPatch != 0) {
660 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
661 mCallRxPatch.clear();
662 }
663 if (mCallTxPatch != 0) {
664 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
665 mCallTxPatch.clear();
666 }
667 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
668 } else {
669 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
670 }
Eric Laurente552edb2014-03-10 17:42:56 -0700671 // if entering in call state, handle special case of active streams
672 // pertaining to sonification strategy see handleIncallSonification()
673 if (isStateInCall(state)) {
674 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700675 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
676 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700677 }
678 }
679
680 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700681 if (state == AUDIO_MODE_RINGTONE &&
682 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700683 mLimitRingtoneVolume = true;
684 } else {
685 mLimitRingtoneVolume = false;
686 }
687}
688
Eric Laurente0720872014-03-11 09:30:41 -0700689void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700690 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700691{
692 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
693
694 bool forceVolumeReeval = false;
695 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700696 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
697 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
698 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700699 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
700 return;
701 }
702 forceVolumeReeval = true;
703 mForceUse[usage] = config;
704 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700705 case AUDIO_POLICY_FORCE_FOR_MEDIA:
706 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
707 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
708 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
709 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900710 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700711 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
712 return;
713 }
714 mForceUse[usage] = config;
715 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700716 case AUDIO_POLICY_FORCE_FOR_RECORD:
717 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
718 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700719 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
720 return;
721 }
722 mForceUse[usage] = config;
723 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700724 case AUDIO_POLICY_FORCE_FOR_DOCK:
725 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
726 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
727 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
728 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
729 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700730 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
731 }
732 forceVolumeReeval = true;
733 mForceUse[usage] = config;
734 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700735 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
736 if (config != AUDIO_POLICY_FORCE_NONE &&
737 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700738 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
739 }
740 forceVolumeReeval = true;
741 mForceUse[usage] = config;
742 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900743 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
744 if (config != AUDIO_POLICY_FORCE_NONE &&
745 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
746 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
747 }
748 mForceUse[usage] = config;
749 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700750 default:
751 ALOGW("setForceUse() invalid usage %d", usage);
752 break;
753 }
754
755 // check for device and output changes triggered by new force usage
756 checkA2dpSuspend();
757 checkOutputForAllStrategies();
758 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700759 if (mPhoneState == AUDIO_MODE_IN_CALL) {
760 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
761 updateCallRouting(newDevice);
762 }
Eric Laurente552edb2014-03-10 17:42:56 -0700763 for (size_t i = 0; i < mOutputs.size(); i++) {
764 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700765 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700766 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
767 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
768 }
Eric Laurente552edb2014-03-10 17:42:56 -0700769 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
770 applyStreamVolumes(output, newDevice, 0, true);
771 }
772 }
773
774 audio_io_handle_t activeInput = getActiveInput();
775 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700776 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700777 }
778
779}
780
Eric Laurente0720872014-03-11 09:30:41 -0700781audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700782{
783 return mForceUse[usage];
784}
785
Eric Laurente0720872014-03-11 09:30:41 -0700786void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700787{
788 ALOGV("setSystemProperty() property %s, value %s", property, value);
789}
790
791// Find a direct output profile compatible with the parameters passed, even if the input flags do
792// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700793sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700794 audio_devices_t device,
795 uint32_t samplingRate,
796 audio_format_t format,
797 audio_channel_mask_t channelMask,
798 audio_output_flags_t flags)
799{
800 for (size_t i = 0; i < mHwModules.size(); i++) {
801 if (mHwModules[i]->mHandle == 0) {
802 continue;
803 }
804 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700805 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700806 bool found = profile->isCompatibleProfile(device, samplingRate,
807 NULL /*updatedSamplingRate*/, format, channelMask,
808 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
809 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700810 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
811 return profile;
812 }
Eric Laurente552edb2014-03-10 17:42:56 -0700813 }
814 }
815 return 0;
816}
817
Eric Laurente0720872014-03-11 09:30:41 -0700818audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700819 uint32_t samplingRate,
820 audio_format_t format,
821 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700822 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700823 const audio_offload_info_t *offloadInfo)
824{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700825
Eric Laurent3b73df72014-03-11 09:06:29 -0700826 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700827 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
828 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
829 device, stream, samplingRate, format, channelMask, flags);
830
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700831 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
832 offloadInfo);
833}
834
835audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
836 uint32_t samplingRate,
837 audio_format_t format,
838 audio_channel_mask_t channelMask,
839 audio_output_flags_t flags,
840 const audio_offload_info_t *offloadInfo)
841{
842 if (attr == NULL) {
843 ALOGE("getOutputForAttr() called with NULL audio attributes");
844 return 0;
845 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700846 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
847 attr->usage, attr->content_type, attr->tags, attr->flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848
849 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
850 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
851 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700852
853 if ((attr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
854 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
855 }
856
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700857 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
858 device, samplingRate, format, channelMask, flags);
859
860 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
861 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
862 offloadInfo);
863}
864
865audio_io_handle_t AudioPolicyManager::getOutputForDevice(
866 audio_devices_t device,
867 audio_stream_type_t stream,
868 uint32_t samplingRate,
869 audio_format_t format,
870 audio_channel_mask_t channelMask,
871 audio_output_flags_t flags,
872 const audio_offload_info_t *offloadInfo)
873{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700874 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700875 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700876 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700877
Eric Laurente552edb2014-03-10 17:42:56 -0700878#ifdef AUDIO_POLICY_TEST
879 if (mCurOutput != 0) {
880 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
881 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
882
883 if (mTestOutputs[mCurOutput] == 0) {
884 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700885 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700886 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700887 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700888 outputDesc->mFlags =
889 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700890 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700891 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
892 config.sample_rate = mTestSamplingRate;
893 config.channel_mask = mTestChannels;
894 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700895 if (offloadInfo != NULL) {
896 config.offload_info = *offloadInfo;
897 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700898 status = mpClientInterface->openOutput(0,
899 &mTestOutputs[mCurOutput],
900 &config,
901 &outputDesc->mDevice,
902 String8(""),
903 &outputDesc->mLatency,
904 outputDesc->mFlags);
905 if (status == NO_ERROR) {
906 outputDesc->mSamplingRate = config.sample_rate;
907 outputDesc->mFormat = config.format;
908 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700909 AudioParameter outputCmd = AudioParameter();
910 outputCmd.addInt(String8("set_id"),mCurOutput);
911 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
912 addOutput(mTestOutputs[mCurOutput], outputDesc);
913 }
914 }
915 return mTestOutputs[mCurOutput];
916 }
917#endif //AUDIO_POLICY_TEST
918
919 // open a direct output if required by specified parameters
920 //force direct flag if offload flag is set: offloading implies a direct output stream
921 // and all common behaviors are driven by checking only the direct flag
922 // this should normally be set appropriately in the policy configuration file
923 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700924 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700925 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700926 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
927 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
928 }
Eric Laurente552edb2014-03-10 17:42:56 -0700929
Eric Laurentb732cf52014-09-24 19:08:21 -0700930 sp<IOProfile> profile;
931
932 // skip direct output selection if the request can obviously be attached to a mixed output
933 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
934 audio_channel_count_from_out_mask(channelMask) <= 2) {
935 goto non_direct_output;
936 }
937
Eric Laurente552edb2014-03-10 17:42:56 -0700938 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
939 // creating an offloaded track and tearing it down immediately after start when audioflinger
940 // detects there is an active non offloadable effect.
941 // FIXME: We should check the audio session here but we do not have it in this context.
942 // This may prevent offloading in rare situations where effects are left active by apps
943 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700944
Eric Laurente552edb2014-03-10 17:42:56 -0700945 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
946 !isNonOffloadableEffectEnabled()) {
947 profile = getProfileForDirectOutput(device,
948 samplingRate,
949 format,
950 channelMask,
951 (audio_output_flags_t)flags);
952 }
953
Eric Laurent1c333e22014-05-20 10:48:17 -0700954 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700955 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700956
957 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700958 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700959 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
960 outputDesc = desc;
961 // reuse direct output if currently open and configured with same parameters
962 if ((samplingRate == outputDesc->mSamplingRate) &&
963 (format == outputDesc->mFormat) &&
964 (channelMask == outputDesc->mChannelMask)) {
965 outputDesc->mDirectOpenCount++;
966 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
967 return mOutputs.keyAt(i);
968 }
969 }
970 }
971 // close direct output if currently open and configured with different parameters
972 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700973 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700974 }
975 outputDesc = new AudioOutputDescriptor(profile);
976 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700977 outputDesc->mLatency = 0;
978 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700979 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
980 config.sample_rate = samplingRate;
981 config.channel_mask = channelMask;
982 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700983 if (offloadInfo != NULL) {
984 config.offload_info = *offloadInfo;
985 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700986 status = mpClientInterface->openOutput(profile->mModule->mHandle,
987 &output,
988 &config,
989 &outputDesc->mDevice,
990 String8(""),
991 &outputDesc->mLatency,
992 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700993
994 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700995 if (status != NO_ERROR ||
996 (samplingRate != 0 && samplingRate != config.sample_rate) ||
997 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
998 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700999 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1000 "format %d %d, channelMask %04x %04x", output, samplingRate,
1001 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1002 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001003 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001004 mpClientInterface->closeOutput(output);
1005 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001006 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001007 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001008 outputDesc->mSamplingRate = config.sample_rate;
1009 outputDesc->mChannelMask = config.channel_mask;
1010 outputDesc->mFormat = config.format;
1011 outputDesc->mRefCount[stream] = 0;
1012 outputDesc->mStopTime[stream] = 0;
1013 outputDesc->mDirectOpenCount = 1;
1014
Eric Laurente552edb2014-03-10 17:42:56 -07001015 audio_io_handle_t srcOutput = getOutputForEffect();
1016 addOutput(output, outputDesc);
1017 audio_io_handle_t dstOutput = getOutputForEffect();
1018 if (dstOutput == output) {
1019 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1020 }
1021 mPreviousOutputs = mOutputs;
1022 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001023 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001024 return output;
1025 }
1026
Eric Laurentb732cf52014-09-24 19:08:21 -07001027non_direct_output:
1028
Eric Laurente552edb2014-03-10 17:42:56 -07001029 // ignoring channel mask due to downmix capability in mixer
1030
1031 // open a non direct output
1032
1033 // for non direct outputs, only PCM is supported
1034 if (audio_is_linear_pcm(format)) {
1035 // get which output is suitable for the specified stream. The actual
1036 // routing change will happen when startOutput() will be called
1037 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1038
Eric Laurent8838a382014-09-08 16:44:28 -07001039 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1040 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1041 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001042 }
1043 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1044 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1045
1046 ALOGV("getOutput() returns output %d", output);
1047
1048 return output;
1049}
1050
Eric Laurente0720872014-03-11 09:30:41 -07001051audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001052 audio_output_flags_t flags,
1053 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001054{
1055 // select one output among several that provide a path to a particular device or set of
1056 // devices (the list was previously build by getOutputsForDevice()).
1057 // The priority is as follows:
1058 // 1: the output with the highest number of requested policy flags
1059 // 2: the primary output
1060 // 3: the first output in the list
1061
1062 if (outputs.size() == 0) {
1063 return 0;
1064 }
1065 if (outputs.size() == 1) {
1066 return outputs[0];
1067 }
1068
1069 int maxCommonFlags = 0;
1070 audio_io_handle_t outputFlags = 0;
1071 audio_io_handle_t outputPrimary = 0;
1072
1073 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001074 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001075 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001076 // if a valid format is specified, skip output if not compatible
1077 if (format != AUDIO_FORMAT_INVALID) {
1078 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1079 if (format != outputDesc->mFormat) {
1080 continue;
1081 }
1082 } else if (!audio_is_linear_pcm(format)) {
1083 continue;
1084 }
1085 }
1086
Eric Laurent3b73df72014-03-11 09:06:29 -07001087 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001088 if (commonFlags > maxCommonFlags) {
1089 outputFlags = outputs[i];
1090 maxCommonFlags = commonFlags;
1091 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1092 }
1093 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1094 outputPrimary = outputs[i];
1095 }
1096 }
1097 }
1098
1099 if (outputFlags != 0) {
1100 return outputFlags;
1101 }
1102 if (outputPrimary != 0) {
1103 return outputPrimary;
1104 }
1105
1106 return outputs[0];
1107}
1108
Eric Laurente0720872014-03-11 09:30:41 -07001109status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001110 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001111 int session)
1112{
1113 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1114 ssize_t index = mOutputs.indexOfKey(output);
1115 if (index < 0) {
1116 ALOGW("startOutput() unknown output %d", output);
1117 return BAD_VALUE;
1118 }
1119
Eric Laurent1f2f2232014-06-02 12:01:23 -07001120 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001121
1122 // increment usage count for this stream on the requested output:
1123 // NOTE that the usage count is the same for duplicated output and hardware output which is
1124 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1125 outputDesc->changeRefCount(stream, 1);
1126
1127 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001128 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001129 routing_strategy strategy = getStrategy(stream);
1130 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1131 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1132 uint32_t waitMs = 0;
1133 bool force = false;
1134 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001135 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001136 if (desc != outputDesc) {
1137 // force a device change if any other output is managed by the same hw
1138 // module and has a current device selection that differs from selected device.
1139 // In this case, the audio HAL must receive the new device selection so that it can
1140 // change the device currently selected by the other active output.
1141 if (outputDesc->sharesHwModuleWith(desc) &&
1142 desc->device() != newDevice) {
1143 force = true;
1144 }
1145 // wait for audio on other active outputs to be presented when starting
1146 // a notification so that audio focus effect can propagate.
1147 uint32_t latency = desc->latency();
1148 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1149 waitMs = latency;
1150 }
1151 }
1152 }
1153 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1154
1155 // handle special case for sonification while in call
1156 if (isInCall()) {
1157 handleIncallSonification(stream, true, false);
1158 }
1159
1160 // apply volume rules for current stream and device if necessary
1161 checkAndSetVolume(stream,
1162 mStreams[stream].getVolumeIndex(newDevice),
1163 output,
1164 newDevice);
1165
1166 // update the outputs if starting an output with a stream that can affect notification
1167 // routing
1168 handleNotificationRoutingForStream(stream);
1169 if (waitMs > muteWaitMs) {
1170 usleep((waitMs - muteWaitMs) * 2 * 1000);
1171 }
1172 }
1173 return NO_ERROR;
1174}
1175
1176
Eric Laurente0720872014-03-11 09:30:41 -07001177status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001178 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001179 int session)
1180{
1181 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1182 ssize_t index = mOutputs.indexOfKey(output);
1183 if (index < 0) {
1184 ALOGW("stopOutput() unknown output %d", output);
1185 return BAD_VALUE;
1186 }
1187
Eric Laurent1f2f2232014-06-02 12:01:23 -07001188 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001189
1190 // handle special case for sonification while in call
1191 if (isInCall()) {
1192 handleIncallSonification(stream, false, false);
1193 }
1194
1195 if (outputDesc->mRefCount[stream] > 0) {
1196 // decrement usage count of this stream on the output
1197 outputDesc->changeRefCount(stream, -1);
1198 // store time at which the stream was stopped - see isStreamActive()
1199 if (outputDesc->mRefCount[stream] == 0) {
1200 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001201 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001202 // delay the device switch by twice the latency because stopOutput() is executed when
1203 // the track stop() command is received and at that time the audio track buffer can
1204 // still contain data that needs to be drained. The latency only covers the audio HAL
1205 // and kernel buffers. Also the latency does not always include additional delay in the
1206 // audio path (audio DSP, CODEC ...)
1207 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1208
1209 // force restoring the device selection on other active outputs if it differs from the
1210 // one being selected for this output
1211 for (size_t i = 0; i < mOutputs.size(); i++) {
1212 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001213 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001214 if (curOutput != output &&
1215 desc->isActive() &&
1216 outputDesc->sharesHwModuleWith(desc) &&
1217 (newDevice != desc->device())) {
1218 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001219 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001220 true,
1221 outputDesc->mLatency*2);
1222 }
1223 }
1224 // update the outputs if stopping one with a stream that can affect notification routing
1225 handleNotificationRoutingForStream(stream);
1226 }
1227 return NO_ERROR;
1228 } else {
1229 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1230 return INVALID_OPERATION;
1231 }
1232}
1233
Eric Laurente0720872014-03-11 09:30:41 -07001234void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001235{
1236 ALOGV("releaseOutput() %d", output);
1237 ssize_t index = mOutputs.indexOfKey(output);
1238 if (index < 0) {
1239 ALOGW("releaseOutput() releasing unknown output %d", output);
1240 return;
1241 }
1242
1243#ifdef AUDIO_POLICY_TEST
1244 int testIndex = testOutputIndex(output);
1245 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001246 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001247 if (outputDesc->isActive()) {
1248 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001249 mOutputs.removeItem(output);
1250 mTestOutputs[testIndex] = 0;
1251 }
1252 return;
1253 }
1254#endif //AUDIO_POLICY_TEST
1255
Eric Laurent1f2f2232014-06-02 12:01:23 -07001256 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001257 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001258 if (desc->mDirectOpenCount <= 0) {
1259 ALOGW("releaseOutput() invalid open count %d for output %d",
1260 desc->mDirectOpenCount, output);
1261 return;
1262 }
1263 if (--desc->mDirectOpenCount == 0) {
1264 closeOutput(output);
1265 // If effects where present on the output, audioflinger moved them to the primary
1266 // output by default: move them back to the appropriate output.
1267 audio_io_handle_t dstOutput = getOutputForEffect();
1268 if (dstOutput != mPrimaryOutput) {
1269 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1270 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001271 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001272 }
1273 }
1274}
1275
1276
Eric Laurente0720872014-03-11 09:30:41 -07001277audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001278 uint32_t samplingRate,
1279 audio_format_t format,
1280 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001281 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001282 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001283{
Eric Laurent4dc68062014-07-28 17:26:49 -07001284 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001285 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001286 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001287
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001288 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001289
1290 if (device == AUDIO_DEVICE_NONE) {
1291 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001292 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001293 }
1294
1295 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001296 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001297 case AUDIO_SOURCE_VOICE_UPLINK:
1298 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1299 break;
1300 case AUDIO_SOURCE_VOICE_DOWNLINK:
1301 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1302 break;
1303 case AUDIO_SOURCE_VOICE_CALL:
1304 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1305 break;
1306 default:
1307 break;
1308 }
1309
Eric Laurent5dbe4712014-09-19 19:04:57 -07001310 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1311 bool isSoundTrigger = false;
1312 audio_source_t halInputSource = inputSource;
1313 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1314 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1315 if (index >= 0) {
1316 input = mSoundTriggerSessions.valueFor(session);
1317 isSoundTrigger = true;
1318 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1319 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1320 } else {
1321 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1322 }
1323 }
1324
Eric Laurent1c333e22014-05-20 10:48:17 -07001325 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001326 samplingRate,
1327 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001328 channelMask,
1329 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001330 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001331 //retry without flags
1332 audio_input_flags_t log_flags = flags;
1333 flags = AUDIO_INPUT_FLAG_NONE;
1334 profile = getInputProfile(device,
1335 samplingRate,
1336 format,
1337 channelMask,
1338 flags);
1339 if (profile == 0) {
1340 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1341 "channelMask 0x%X, flags %#x",
1342 device, samplingRate, format, channelMask, log_flags);
1343 return AUDIO_IO_HANDLE_NONE;
1344 }
Eric Laurente552edb2014-03-10 17:42:56 -07001345 }
1346
1347 if (profile->mModule->mHandle == 0) {
1348 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001349 return AUDIO_IO_HANDLE_NONE;
1350 }
1351
1352 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1353 config.sample_rate = samplingRate;
1354 config.channel_mask = channelMask;
1355 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001356
Eric Laurentcf2c0212014-07-25 16:20:43 -07001357 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1358 &input,
1359 &config,
1360 &device,
1361 String8(""),
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001362 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001363 flags);
1364
1365 // only accept input with the exact requested set of parameters
1366 if (status != NO_ERROR ||
1367 (samplingRate != config.sample_rate) ||
1368 (format != config.format) ||
1369 (channelMask != config.channel_mask)) {
1370 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1371 samplingRate, format, channelMask);
1372 if (input != AUDIO_IO_HANDLE_NONE) {
1373 mpClientInterface->closeInput(input);
1374 }
1375 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001376 }
1377
Eric Laurent1f2f2232014-06-02 12:01:23 -07001378 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001379 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001380 inputDesc->mRefCount = 0;
1381 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001382 inputDesc->mSamplingRate = samplingRate;
1383 inputDesc->mFormat = format;
1384 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001385 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001386 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001387 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001388
Eric Laurentd4692962014-05-05 18:13:44 -07001389 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001390 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001391 return input;
1392}
1393
Eric Laurent4dc68062014-07-28 17:26:49 -07001394status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1395 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001396{
1397 ALOGV("startInput() input %d", input);
1398 ssize_t index = mInputs.indexOfKey(input);
1399 if (index < 0) {
1400 ALOGW("startInput() unknown input %d", input);
1401 return BAD_VALUE;
1402 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001403 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001404
Eric Laurent4dc68062014-07-28 17:26:49 -07001405 index = inputDesc->mSessions.indexOf(session);
1406 if (index < 0) {
1407 ALOGW("startInput() unknown session %d on input %d", session, input);
1408 return BAD_VALUE;
1409 }
1410
Glenn Kasten74a8e252014-07-24 14:09:55 -07001411 // virtual input devices are compatible with other input devices
1412 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1413
1414 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001415 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001416 if (activeInput != 0 && activeInput != input) {
1417
1418 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1419 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001420 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001421 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001422 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001423 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1424 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001425 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001426 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001427 return INVALID_OPERATION;
1428 }
1429 }
1430 }
1431
Glenn Kasten74a8e252014-07-24 14:09:55 -07001432 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001433 if (activeInputsCount() == 0) {
1434 SoundTrigger::setCaptureState(true);
1435 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001436 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001437
Glenn Kasten74a8e252014-07-24 14:09:55 -07001438 // Automatically enable the remote submix output when input is started.
1439 // For remote submix (a virtual device), we open only one input per capture request.
1440 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1441 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1442 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1443 }
Eric Laurente552edb2014-03-10 17:42:56 -07001444 }
1445
Eric Laurente552edb2014-03-10 17:42:56 -07001446 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1447
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001448 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001449 return NO_ERROR;
1450}
1451
Eric Laurent4dc68062014-07-28 17:26:49 -07001452status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1453 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001454{
1455 ALOGV("stopInput() input %d", input);
1456 ssize_t index = mInputs.indexOfKey(input);
1457 if (index < 0) {
1458 ALOGW("stopInput() unknown input %d", input);
1459 return BAD_VALUE;
1460 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001461 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001462
Eric Laurent4dc68062014-07-28 17:26:49 -07001463 index = inputDesc->mSessions.indexOf(session);
1464 if (index < 0) {
1465 ALOGW("stopInput() unknown session %d on input %d", session, input);
1466 return BAD_VALUE;
1467 }
1468
Eric Laurente552edb2014-03-10 17:42:56 -07001469 if (inputDesc->mRefCount == 0) {
1470 ALOGW("stopInput() input %d already stopped", input);
1471 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001472 }
1473
1474 inputDesc->mRefCount--;
1475 if (inputDesc->mRefCount == 0) {
1476
Eric Laurente552edb2014-03-10 17:42:56 -07001477 // automatically disable the remote submix output when input is stopped
1478 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1479 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001480 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001481 }
1482
Eric Laurent1c333e22014-05-20 10:48:17 -07001483 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001484
1485 if (activeInputsCount() == 0) {
1486 SoundTrigger::setCaptureState(false);
1487 }
Eric Laurente552edb2014-03-10 17:42:56 -07001488 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001489 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001490}
1491
Eric Laurent4dc68062014-07-28 17:26:49 -07001492void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1493 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001494{
1495 ALOGV("releaseInput() %d", input);
1496 ssize_t index = mInputs.indexOfKey(input);
1497 if (index < 0) {
1498 ALOGW("releaseInput() releasing unknown input %d", input);
1499 return;
1500 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001501 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1502 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001503
1504 index = inputDesc->mSessions.indexOf(session);
1505 if (index < 0) {
1506 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1507 return;
1508 }
1509 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001510 if (inputDesc->mOpenRefCount == 0) {
1511 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1512 return;
1513 }
1514 inputDesc->mOpenRefCount--;
1515 if (inputDesc->mOpenRefCount > 0) {
1516 ALOGV("releaseInput() exit > 0");
1517 return;
1518 }
1519
Eric Laurent05b90f82014-08-27 15:32:29 -07001520 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001521 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001522 ALOGV("releaseInput() exit");
1523}
1524
Eric Laurentd4692962014-05-05 18:13:44 -07001525void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001526 bool patchRemoved = false;
1527
Eric Laurentd4692962014-05-05 18:13:44 -07001528 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001529 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1530 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1531 if (patch_index >= 0) {
1532 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1533 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1534 mAudioPatches.removeItemsAt(patch_index);
1535 patchRemoved = true;
1536 }
Eric Laurentd4692962014-05-05 18:13:44 -07001537 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1538 }
1539 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001540 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001541
1542 if (patchRemoved) {
1543 mpClientInterface->onAudioPatchListUpdate();
1544 }
Eric Laurentd4692962014-05-05 18:13:44 -07001545}
1546
Eric Laurente0720872014-03-11 09:30:41 -07001547void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001548 int indexMin,
1549 int indexMax)
1550{
1551 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1552 if (indexMin < 0 || indexMin >= indexMax) {
1553 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1554 return;
1555 }
1556 mStreams[stream].mIndexMin = indexMin;
1557 mStreams[stream].mIndexMax = indexMax;
1558}
1559
Eric Laurente0720872014-03-11 09:30:41 -07001560status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001561 int index,
1562 audio_devices_t device)
1563{
1564
1565 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1566 return BAD_VALUE;
1567 }
1568 if (!audio_is_output_device(device)) {
1569 return BAD_VALUE;
1570 }
1571
1572 // Force max volume if stream cannot be muted
1573 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1574
1575 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1576 stream, device, index);
1577
1578 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1579 // clear all device specific values
1580 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1581 mStreams[stream].mIndexCur.clear();
1582 }
1583 mStreams[stream].mIndexCur.add(device, index);
1584
1585 // compute and apply stream volume on all outputs according to connected device
1586 status_t status = NO_ERROR;
1587 for (size_t i = 0; i < mOutputs.size(); i++) {
1588 audio_devices_t curDevice =
1589 getDeviceForVolume(mOutputs.valueAt(i)->device());
1590 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1591 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1592 if (volStatus != NO_ERROR) {
1593 status = volStatus;
1594 }
1595 }
1596 }
1597 return status;
1598}
1599
Eric Laurente0720872014-03-11 09:30:41 -07001600status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001601 int *index,
1602 audio_devices_t device)
1603{
1604 if (index == NULL) {
1605 return BAD_VALUE;
1606 }
1607 if (!audio_is_output_device(device)) {
1608 return BAD_VALUE;
1609 }
1610 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1611 // the strategy the stream belongs to.
1612 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1613 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1614 }
1615 device = getDeviceForVolume(device);
1616
1617 *index = mStreams[stream].getVolumeIndex(device);
1618 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1619 return NO_ERROR;
1620}
1621
Eric Laurente0720872014-03-11 09:30:41 -07001622audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001623 const SortedVector<audio_io_handle_t>& outputs)
1624{
1625 // select one output among several suitable for global effects.
1626 // The priority is as follows:
1627 // 1: An offloaded output. If the effect ends up not being offloadable,
1628 // AudioFlinger will invalidate the track and the offloaded output
1629 // will be closed causing the effect to be moved to a PCM output.
1630 // 2: A deep buffer output
1631 // 3: the first output in the list
1632
1633 if (outputs.size() == 0) {
1634 return 0;
1635 }
1636
1637 audio_io_handle_t outputOffloaded = 0;
1638 audio_io_handle_t outputDeepBuffer = 0;
1639
1640 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001641 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001642 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001643 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1644 outputOffloaded = outputs[i];
1645 }
1646 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1647 outputDeepBuffer = outputs[i];
1648 }
1649 }
1650
1651 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1652 outputOffloaded, outputDeepBuffer);
1653 if (outputOffloaded != 0) {
1654 return outputOffloaded;
1655 }
1656 if (outputDeepBuffer != 0) {
1657 return outputDeepBuffer;
1658 }
1659
1660 return outputs[0];
1661}
1662
Eric Laurente0720872014-03-11 09:30:41 -07001663audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001664{
1665 // apply simple rule where global effects are attached to the same output as MUSIC streams
1666
Eric Laurent3b73df72014-03-11 09:06:29 -07001667 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001668 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1669 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1670
1671 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1672 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1673 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1674
1675 return output;
1676}
1677
Eric Laurente0720872014-03-11 09:30:41 -07001678status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001679 audio_io_handle_t io,
1680 uint32_t strategy,
1681 int session,
1682 int id)
1683{
1684 ssize_t index = mOutputs.indexOfKey(io);
1685 if (index < 0) {
1686 index = mInputs.indexOfKey(io);
1687 if (index < 0) {
1688 ALOGW("registerEffect() unknown io %d", io);
1689 return INVALID_OPERATION;
1690 }
1691 }
1692
1693 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1694 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1695 desc->name, desc->memoryUsage);
1696 return INVALID_OPERATION;
1697 }
1698 mTotalEffectsMemory += desc->memoryUsage;
1699 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1700 desc->name, io, strategy, session, id);
1701 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1702
Eric Laurent1f2f2232014-06-02 12:01:23 -07001703 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1704 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1705 effectDesc->mIo = io;
1706 effectDesc->mStrategy = (routing_strategy)strategy;
1707 effectDesc->mSession = session;
1708 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001709
Eric Laurent1f2f2232014-06-02 12:01:23 -07001710 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001711
1712 return NO_ERROR;
1713}
1714
Eric Laurente0720872014-03-11 09:30:41 -07001715status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001716{
1717 ssize_t index = mEffects.indexOfKey(id);
1718 if (index < 0) {
1719 ALOGW("unregisterEffect() unknown effect ID %d", id);
1720 return INVALID_OPERATION;
1721 }
1722
Eric Laurent1f2f2232014-06-02 12:01:23 -07001723 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001724
Eric Laurent1f2f2232014-06-02 12:01:23 -07001725 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001726
Eric Laurent1f2f2232014-06-02 12:01:23 -07001727 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001728 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001729 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1730 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001731 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001732 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001733 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001734 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001735
1736 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001737
1738 return NO_ERROR;
1739}
1740
Eric Laurente0720872014-03-11 09:30:41 -07001741status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001742{
1743 ssize_t index = mEffects.indexOfKey(id);
1744 if (index < 0) {
1745 ALOGW("unregisterEffect() unknown effect ID %d", id);
1746 return INVALID_OPERATION;
1747 }
1748
1749 return setEffectEnabled(mEffects.valueAt(index), enabled);
1750}
1751
Eric Laurent1f2f2232014-06-02 12:01:23 -07001752status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001753{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001754 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001755 ALOGV("setEffectEnabled(%s) effect already %s",
1756 enabled?"true":"false", enabled?"enabled":"disabled");
1757 return INVALID_OPERATION;
1758 }
1759
1760 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001761 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001762 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001763 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001764 return INVALID_OPERATION;
1765 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001766 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001767 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1768 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001769 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001770 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001771 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1772 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001773 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001774 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001775 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1776 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001777 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001778 return NO_ERROR;
1779}
1780
Eric Laurente0720872014-03-11 09:30:41 -07001781bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001782{
1783 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001784 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1785 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1786 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001787 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001788 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001789 return true;
1790 }
1791 }
1792 return false;
1793}
1794
Eric Laurente0720872014-03-11 09:30:41 -07001795bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001796{
1797 nsecs_t sysTime = systemTime();
1798 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001799 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001800 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001801 return true;
1802 }
1803 }
1804 return false;
1805}
1806
Eric Laurente0720872014-03-11 09:30:41 -07001807bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001808 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001809{
1810 nsecs_t sysTime = systemTime();
1811 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001812 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001813 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001814 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001815 return true;
1816 }
1817 }
1818 return false;
1819}
1820
Eric Laurente0720872014-03-11 09:30:41 -07001821bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001822{
1823 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001824 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001825 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001826 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001827 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1828 && (inputDescriptor->mRefCount > 0)) {
1829 return true;
1830 }
1831 }
1832 return false;
1833}
1834
1835
Eric Laurente0720872014-03-11 09:30:41 -07001836status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001837{
1838 const size_t SIZE = 256;
1839 char buffer[SIZE];
1840 String8 result;
1841
1842 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1843 result.append(buffer);
1844
1845 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1846 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001847 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1848 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001849 snprintf(buffer, SIZE, " Force use for communications %d\n",
1850 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001851 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001852 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001853 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001854 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001855 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001856 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001857 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001858 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001859 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001860 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1861 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1862 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001863
Eric Laurent3a4311c2014-03-17 12:00:47 -07001864 snprintf(buffer, SIZE, " Available output devices:\n");
1865 result.append(buffer);
1866 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001867 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001868 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001869 }
1870 snprintf(buffer, SIZE, "\n Available input devices:\n");
1871 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001872 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001873 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001874 }
Eric Laurente552edb2014-03-10 17:42:56 -07001875
1876 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1877 write(fd, buffer, strlen(buffer));
1878 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001879 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001880 write(fd, buffer, strlen(buffer));
1881 mHwModules[i]->dump(fd);
1882 }
1883
1884 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1885 write(fd, buffer, strlen(buffer));
1886 for (size_t i = 0; i < mOutputs.size(); i++) {
1887 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1888 write(fd, buffer, strlen(buffer));
1889 mOutputs.valueAt(i)->dump(fd);
1890 }
1891
1892 snprintf(buffer, SIZE, "\nInputs dump:\n");
1893 write(fd, buffer, strlen(buffer));
1894 for (size_t i = 0; i < mInputs.size(); i++) {
1895 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1896 write(fd, buffer, strlen(buffer));
1897 mInputs.valueAt(i)->dump(fd);
1898 }
1899
1900 snprintf(buffer, SIZE, "\nStreams dump:\n");
1901 write(fd, buffer, strlen(buffer));
1902 snprintf(buffer, SIZE,
1903 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1904 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001905 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001906 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001907 write(fd, buffer, strlen(buffer));
1908 mStreams[i].dump(fd);
1909 }
1910
1911 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1912 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1913 write(fd, buffer, strlen(buffer));
1914
1915 snprintf(buffer, SIZE, "Registered effects:\n");
1916 write(fd, buffer, strlen(buffer));
1917 for (size_t i = 0; i < mEffects.size(); i++) {
1918 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1919 write(fd, buffer, strlen(buffer));
1920 mEffects.valueAt(i)->dump(fd);
1921 }
1922
Eric Laurent4d416952014-08-10 14:07:09 -07001923 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1924 write(fd, buffer, strlen(buffer));
1925 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1926 mAudioPatches[i]->dump(fd, 2, i);
1927 }
Eric Laurente552edb2014-03-10 17:42:56 -07001928
1929 return NO_ERROR;
1930}
1931
1932// This function checks for the parameters which can be offloaded.
1933// This can be enhanced depending on the capability of the DSP and policy
1934// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001935bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001936{
1937 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001938 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001939 offloadInfo.sample_rate, offloadInfo.channel_mask,
1940 offloadInfo.format,
1941 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1942 offloadInfo.has_video);
1943
1944 // Check if offload has been disabled
1945 char propValue[PROPERTY_VALUE_MAX];
1946 if (property_get("audio.offload.disable", propValue, "0")) {
1947 if (atoi(propValue) != 0) {
1948 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1949 return false;
1950 }
1951 }
1952
1953 // Check if stream type is music, then only allow offload as of now.
1954 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1955 {
1956 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1957 return false;
1958 }
1959
1960 //TODO: enable audio offloading with video when ready
1961 if (offloadInfo.has_video)
1962 {
1963 ALOGV("isOffloadSupported: has_video == true, returning false");
1964 return false;
1965 }
1966
1967 //If duration is less than minimum value defined in property, return false
1968 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1969 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1970 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1971 return false;
1972 }
1973 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1974 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1975 return false;
1976 }
1977
1978 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1979 // creating an offloaded track and tearing it down immediately after start when audioflinger
1980 // detects there is an active non offloadable effect.
1981 // FIXME: We should check the audio session here but we do not have it in this context.
1982 // This may prevent offloading in rare situations where effects are left active by apps
1983 // in the background.
1984 if (isNonOffloadableEffectEnabled()) {
1985 return false;
1986 }
1987
1988 // See if there is a profile to support this.
1989 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001990 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001991 offloadInfo.sample_rate,
1992 offloadInfo.format,
1993 offloadInfo.channel_mask,
1994 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001995 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1996 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001997}
1998
Eric Laurent6a94d692014-05-20 11:18:06 -07001999status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2000 audio_port_type_t type,
2001 unsigned int *num_ports,
2002 struct audio_port *ports,
2003 unsigned int *generation)
2004{
2005 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2006 generation == NULL) {
2007 return BAD_VALUE;
2008 }
2009 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2010 if (ports == NULL) {
2011 *num_ports = 0;
2012 }
2013
2014 size_t portsWritten = 0;
2015 size_t portsMax = *num_ports;
2016 *num_ports = 0;
2017 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2018 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2019 for (size_t i = 0;
2020 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2021 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2022 }
2023 *num_ports += mAvailableOutputDevices.size();
2024 }
2025 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2026 for (size_t i = 0;
2027 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2028 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2029 }
2030 *num_ports += mAvailableInputDevices.size();
2031 }
2032 }
2033 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2034 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2035 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2036 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2037 }
2038 *num_ports += mInputs.size();
2039 }
2040 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002041 size_t numOutputs = 0;
2042 for (size_t i = 0; i < mOutputs.size(); i++) {
2043 if (!mOutputs[i]->isDuplicated()) {
2044 numOutputs++;
2045 if (portsWritten < portsMax) {
2046 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2047 }
2048 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002049 }
Eric Laurent84c70242014-06-23 08:46:27 -07002050 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002051 }
2052 }
2053 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002054 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002055 return NO_ERROR;
2056}
2057
2058status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2059{
2060 return NO_ERROR;
2061}
2062
Eric Laurent1f2f2232014-06-02 12:01:23 -07002063sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002064 audio_port_handle_t id) const
2065{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002066 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002067 for (size_t i = 0; i < mOutputs.size(); i++) {
2068 outputDesc = mOutputs.valueAt(i);
2069 if (outputDesc->mId == id) {
2070 break;
2071 }
2072 }
2073 return outputDesc;
2074}
2075
Eric Laurent1f2f2232014-06-02 12:01:23 -07002076sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002077 audio_port_handle_t id) const
2078{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002079 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002080 for (size_t i = 0; i < mInputs.size(); i++) {
2081 inputDesc = mInputs.valueAt(i);
2082 if (inputDesc->mId == id) {
2083 break;
2084 }
2085 }
2086 return inputDesc;
2087}
2088
Eric Laurent1f2f2232014-06-02 12:01:23 -07002089sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2090 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002091{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002092 sp <HwModule> module;
2093
Eric Laurent6a94d692014-05-20 11:18:06 -07002094 for (size_t i = 0; i < mHwModules.size(); i++) {
2095 if (mHwModules[i]->mHandle == 0) {
2096 continue;
2097 }
2098 if (audio_is_output_device(device)) {
2099 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2100 {
2101 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2102 return mHwModules[i];
2103 }
2104 }
2105 } else {
2106 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2107 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2108 device & ~AUDIO_DEVICE_BIT_IN) {
2109 return mHwModules[i];
2110 }
2111 }
2112 }
2113 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002114 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002115}
2116
Eric Laurent1f2f2232014-06-02 12:01:23 -07002117sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002118{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002119 sp <HwModule> module;
2120
Eric Laurent1afeecb2014-05-14 08:52:28 -07002121 for (size_t i = 0; i < mHwModules.size(); i++)
2122 {
2123 if (strcmp(mHwModules[i]->mName, name) == 0) {
2124 return mHwModules[i];
2125 }
2126 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002127 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002128}
2129
Eric Laurentc2730ba2014-07-20 15:47:07 -07002130audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2131{
2132 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2133 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2134 return devices & mAvailableOutputDevices.types();
2135}
2136
2137audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2138{
2139 audio_module_handle_t primaryHandle =
2140 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2141 audio_devices_t devices = AUDIO_DEVICE_NONE;
2142 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2143 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2144 devices |= mAvailableInputDevices[i]->mDeviceType;
2145 }
2146 }
2147 return devices;
2148}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002149
Eric Laurent6a94d692014-05-20 11:18:06 -07002150status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2151 audio_patch_handle_t *handle,
2152 uid_t uid)
2153{
2154 ALOGV("createAudioPatch()");
2155
2156 if (handle == NULL || patch == NULL) {
2157 return BAD_VALUE;
2158 }
2159 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2160
Eric Laurent874c42872014-08-08 15:13:39 -07002161 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2162 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2163 return BAD_VALUE;
2164 }
2165 // only one source per audio patch supported for now
2166 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002167 return INVALID_OPERATION;
2168 }
Eric Laurent874c42872014-08-08 15:13:39 -07002169
2170 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002171 return INVALID_OPERATION;
2172 }
Eric Laurent874c42872014-08-08 15:13:39 -07002173 for (size_t i = 0; i < patch->num_sinks; i++) {
2174 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2175 return INVALID_OPERATION;
2176 }
2177 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002178
2179 sp<AudioPatch> patchDesc;
2180 ssize_t index = mAudioPatches.indexOfKey(*handle);
2181
Eric Laurent6a94d692014-05-20 11:18:06 -07002182 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2183 patch->sources[0].role,
2184 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002185#if LOG_NDEBUG == 0
2186 for (size_t i = 0; i < patch->num_sinks; i++) {
2187 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2188 patch->sinks[i].role,
2189 patch->sinks[i].type);
2190 }
2191#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002192
2193 if (index >= 0) {
2194 patchDesc = mAudioPatches.valueAt(index);
2195 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2196 mUidCached, patchDesc->mUid, uid);
2197 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2198 return INVALID_OPERATION;
2199 }
2200 } else {
2201 *handle = 0;
2202 }
2203
2204 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002205 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002206 if (outputDesc == NULL) {
2207 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2208 return BAD_VALUE;
2209 }
Eric Laurent84c70242014-06-23 08:46:27 -07002210 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2211 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002212 if (patchDesc != 0) {
2213 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2214 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2215 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2216 return BAD_VALUE;
2217 }
2218 }
Eric Laurent874c42872014-08-08 15:13:39 -07002219 DeviceVector devices;
2220 for (size_t i = 0; i < patch->num_sinks; i++) {
2221 // Only support mix to devices connection
2222 // TODO add support for mix to mix connection
2223 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2224 ALOGV("createAudioPatch() source mix but sink is not a device");
2225 return INVALID_OPERATION;
2226 }
2227 sp<DeviceDescriptor> devDesc =
2228 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2229 if (devDesc == 0) {
2230 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2231 return BAD_VALUE;
2232 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002233
Eric Laurent874c42872014-08-08 15:13:39 -07002234 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2235 patch->sources[0].sample_rate,
2236 NULL, // updatedSamplingRate
2237 patch->sources[0].format,
2238 patch->sources[0].channel_mask,
2239 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2240 ALOGV("createAudioPatch() profile not supported for device %08x",
2241 devDesc->mDeviceType);
2242 return INVALID_OPERATION;
2243 }
2244 devices.add(devDesc);
2245 }
2246 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002247 return INVALID_OPERATION;
2248 }
Eric Laurent874c42872014-08-08 15:13:39 -07002249
Eric Laurent6a94d692014-05-20 11:18:06 -07002250 // TODO: reconfigure output format and channels here
2251 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002252 devices.types(), outputDesc->mIoHandle);
2253 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002254 index = mAudioPatches.indexOfKey(*handle);
2255 if (index >= 0) {
2256 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2257 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2258 }
2259 patchDesc = mAudioPatches.valueAt(index);
2260 patchDesc->mUid = uid;
2261 ALOGV("createAudioPatch() success");
2262 } else {
2263 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2264 return INVALID_OPERATION;
2265 }
2266 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2267 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2268 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002269 // only one sink supported when connecting an input device to a mix
2270 if (patch->num_sinks > 1) {
2271 return INVALID_OPERATION;
2272 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002273 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002274 if (inputDesc == NULL) {
2275 return BAD_VALUE;
2276 }
2277 if (patchDesc != 0) {
2278 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2279 return BAD_VALUE;
2280 }
2281 }
2282 sp<DeviceDescriptor> devDesc =
2283 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2284 if (devDesc == 0) {
2285 return BAD_VALUE;
2286 }
2287
Eric Laurent84c70242014-06-23 08:46:27 -07002288 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002289 patch->sinks[0].sample_rate,
2290 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002291 patch->sinks[0].format,
2292 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002293 // FIXME for the parameter type,
2294 // and the NONE
2295 (audio_output_flags_t)
2296 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002297 return INVALID_OPERATION;
2298 }
2299 // TODO: reconfigure output format and channels here
2300 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002301 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002302 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002303 index = mAudioPatches.indexOfKey(*handle);
2304 if (index >= 0) {
2305 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2306 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2307 }
2308 patchDesc = mAudioPatches.valueAt(index);
2309 patchDesc->mUid = uid;
2310 ALOGV("createAudioPatch() success");
2311 } else {
2312 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2313 return INVALID_OPERATION;
2314 }
2315 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2316 // device to device connection
2317 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002318 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002319 return BAD_VALUE;
2320 }
2321 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002322 sp<DeviceDescriptor> srcDeviceDesc =
2323 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002324 if (srcDeviceDesc == 0) {
2325 return BAD_VALUE;
2326 }
Eric Laurent874c42872014-08-08 15:13:39 -07002327
Eric Laurent6a94d692014-05-20 11:18:06 -07002328 //update source and sink with our own data as the data passed in the patch may
2329 // be incomplete.
2330 struct audio_patch newPatch = *patch;
2331 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002332
Eric Laurent874c42872014-08-08 15:13:39 -07002333 for (size_t i = 0; i < patch->num_sinks; i++) {
2334 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2335 ALOGV("createAudioPatch() source device but one sink is not a device");
2336 return INVALID_OPERATION;
2337 }
2338
2339 sp<DeviceDescriptor> sinkDeviceDesc =
2340 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2341 if (sinkDeviceDesc == 0) {
2342 return BAD_VALUE;
2343 }
2344 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2345
2346 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2347 // only one sink supported when connected devices across HW modules
2348 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002349 return INVALID_OPERATION;
2350 }
Eric Laurent874c42872014-08-08 15:13:39 -07002351 SortedVector<audio_io_handle_t> outputs =
2352 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2353 mOutputs);
2354 // if the sink device is reachable via an opened output stream, request to go via
2355 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002356 audio_io_handle_t output = selectOutput(outputs,
2357 AUDIO_OUTPUT_FLAG_NONE,
2358 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002359 if (output != AUDIO_IO_HANDLE_NONE) {
2360 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2361 if (outputDesc->isDuplicated()) {
2362 return INVALID_OPERATION;
2363 }
2364 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2365 newPatch.num_sources = 2;
2366 }
Eric Laurent83b88082014-06-20 18:31:16 -07002367 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002368 }
2369 // TODO: check from routing capabilities in config file and other conflicting patches
2370
2371 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2372 if (index >= 0) {
2373 afPatchHandle = patchDesc->mAfPatchHandle;
2374 }
2375
2376 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2377 &afPatchHandle,
2378 0);
2379 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2380 status, afPatchHandle);
2381 if (status == NO_ERROR) {
2382 if (index < 0) {
2383 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2384 &newPatch, uid);
2385 addAudioPatch(patchDesc->mHandle, patchDesc);
2386 } else {
2387 patchDesc->mPatch = newPatch;
2388 }
2389 patchDesc->mAfPatchHandle = afPatchHandle;
2390 *handle = patchDesc->mHandle;
2391 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002392 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002393 } else {
2394 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2395 status);
2396 return INVALID_OPERATION;
2397 }
2398 } else {
2399 return BAD_VALUE;
2400 }
2401 } else {
2402 return BAD_VALUE;
2403 }
2404 return NO_ERROR;
2405}
2406
2407status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2408 uid_t uid)
2409{
2410 ALOGV("releaseAudioPatch() patch %d", handle);
2411
2412 ssize_t index = mAudioPatches.indexOfKey(handle);
2413
2414 if (index < 0) {
2415 return BAD_VALUE;
2416 }
2417 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2418 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2419 mUidCached, patchDesc->mUid, uid);
2420 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2421 return INVALID_OPERATION;
2422 }
2423
2424 struct audio_patch *patch = &patchDesc->mPatch;
2425 patchDesc->mUid = mUidCached;
2426 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002427 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002428 if (outputDesc == NULL) {
2429 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2430 return BAD_VALUE;
2431 }
2432
2433 setOutputDevice(outputDesc->mIoHandle,
2434 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2435 true,
2436 0,
2437 NULL);
2438 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2439 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002440 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002441 if (inputDesc == NULL) {
2442 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2443 return BAD_VALUE;
2444 }
2445 setInputDevice(inputDesc->mIoHandle,
2446 getNewInputDevice(inputDesc->mIoHandle),
2447 true,
2448 NULL);
2449 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2450 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2451 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2452 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2453 status, patchDesc->mAfPatchHandle);
2454 removeAudioPatch(patchDesc->mHandle);
2455 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002456 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002457 } else {
2458 return BAD_VALUE;
2459 }
2460 } else {
2461 return BAD_VALUE;
2462 }
2463 return NO_ERROR;
2464}
2465
2466status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2467 struct audio_patch *patches,
2468 unsigned int *generation)
2469{
2470 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2471 generation == NULL) {
2472 return BAD_VALUE;
2473 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002474 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002475 *num_patches, patches, mAudioPatches.size());
2476 if (patches == NULL) {
2477 *num_patches = 0;
2478 }
2479
2480 size_t patchesWritten = 0;
2481 size_t patchesMax = *num_patches;
2482 for (size_t i = 0;
2483 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2484 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2485 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002486 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002487 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2488 }
2489 *num_patches = mAudioPatches.size();
2490
2491 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002492 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002493 return NO_ERROR;
2494}
2495
Eric Laurente1715a42014-05-20 11:30:42 -07002496status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002497{
Eric Laurente1715a42014-05-20 11:30:42 -07002498 ALOGV("setAudioPortConfig()");
2499
2500 if (config == NULL) {
2501 return BAD_VALUE;
2502 }
2503 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2504 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002505 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2506 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002507 }
2508
Eric Laurenta121f902014-06-03 13:32:54 -07002509 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002510 if (config->type == AUDIO_PORT_TYPE_MIX) {
2511 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002512 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002513 if (outputDesc == NULL) {
2514 return BAD_VALUE;
2515 }
Eric Laurent84c70242014-06-23 08:46:27 -07002516 ALOG_ASSERT(!outputDesc->isDuplicated(),
2517 "setAudioPortConfig() called on duplicated output %d",
2518 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002519 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002520 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002521 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002522 if (inputDesc == NULL) {
2523 return BAD_VALUE;
2524 }
Eric Laurenta121f902014-06-03 13:32:54 -07002525 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002526 } else {
2527 return BAD_VALUE;
2528 }
2529 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2530 sp<DeviceDescriptor> deviceDesc;
2531 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2532 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2533 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2534 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2535 } else {
2536 return BAD_VALUE;
2537 }
2538 if (deviceDesc == NULL) {
2539 return BAD_VALUE;
2540 }
Eric Laurenta121f902014-06-03 13:32:54 -07002541 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002542 } else {
2543 return BAD_VALUE;
2544 }
2545
Eric Laurenta121f902014-06-03 13:32:54 -07002546 struct audio_port_config backupConfig;
2547 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2548 if (status == NO_ERROR) {
2549 struct audio_port_config newConfig;
2550 audioPortConfig->toAudioPortConfig(&newConfig, config);
2551 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002552 }
Eric Laurenta121f902014-06-03 13:32:54 -07002553 if (status != NO_ERROR) {
2554 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002555 }
Eric Laurente1715a42014-05-20 11:30:42 -07002556
2557 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002558}
2559
2560void AudioPolicyManager::clearAudioPatches(uid_t uid)
2561{
2562 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2563 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2564 if (patchDesc->mUid == uid) {
2565 // releaseAudioPatch() removes the patch from mAudioPatches
2566 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2567 i--;
2568 }
2569 }
2570 }
2571}
2572
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002573status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2574 audio_io_handle_t *ioHandle,
2575 audio_devices_t *device)
2576{
2577 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2578 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2579 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2580
2581 mSoundTriggerSessions.add(*session, *ioHandle);
2582
2583 return NO_ERROR;
2584}
2585
2586status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2587{
2588 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2589 if (index < 0) {
2590 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2591 return BAD_VALUE;
2592 }
2593
2594 mSoundTriggerSessions.removeItem(session);
2595 return NO_ERROR;
2596}
2597
Eric Laurent6a94d692014-05-20 11:18:06 -07002598status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2599 const sp<AudioPatch>& patch)
2600{
2601 ssize_t index = mAudioPatches.indexOfKey(handle);
2602
2603 if (index >= 0) {
2604 ALOGW("addAudioPatch() patch %d already in", handle);
2605 return ALREADY_EXISTS;
2606 }
2607 mAudioPatches.add(handle, patch);
2608 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2609 "sink handle %d",
2610 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2611 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2612 return NO_ERROR;
2613}
2614
2615status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2616{
2617 ssize_t index = mAudioPatches.indexOfKey(handle);
2618
2619 if (index < 0) {
2620 ALOGW("removeAudioPatch() patch %d not in", handle);
2621 return ALREADY_EXISTS;
2622 }
2623 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2624 mAudioPatches.valueAt(index)->mAfPatchHandle);
2625 mAudioPatches.removeItemsAt(index);
2626 return NO_ERROR;
2627}
2628
Eric Laurente552edb2014-03-10 17:42:56 -07002629// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002630// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002631// ----------------------------------------------------------------------------
2632
Eric Laurent3a4311c2014-03-17 12:00:47 -07002633uint32_t AudioPolicyManager::nextUniqueId()
2634{
2635 return android_atomic_inc(&mNextUniqueId);
2636}
2637
Eric Laurent6a94d692014-05-20 11:18:06 -07002638uint32_t AudioPolicyManager::nextAudioPortGeneration()
2639{
2640 return android_atomic_inc(&mAudioPortGeneration);
2641}
2642
Eric Laurente0720872014-03-11 09:30:41 -07002643AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002644 :
2645#ifdef AUDIO_POLICY_TEST
2646 Thread(false),
2647#endif //AUDIO_POLICY_TEST
2648 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002649 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002650 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2651 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002652 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002653 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2654 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002655{
Eric Laurent6a94d692014-05-20 11:18:06 -07002656 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002657 mpClientInterface = clientInterface;
2658
Eric Laurent3b73df72014-03-11 09:06:29 -07002659 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2660 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002661 }
2662
Eric Laurent1afeecb2014-05-14 08:52:28 -07002663 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002664 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2665 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2666 ALOGE("could not load audio policy configuration file, setting defaults");
2667 defaultAudioPolicyConfig();
2668 }
2669 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002670 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002671
2672 // must be done after reading the policy
2673 initializeVolumeCurves();
2674
2675 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002676 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2677 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002678 for (size_t i = 0; i < mHwModules.size(); i++) {
2679 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2680 if (mHwModules[i]->mHandle == 0) {
2681 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2682 continue;
2683 }
2684 // open all output streams needed to access attached devices
2685 // except for direct output streams that are only opened when they are actually
2686 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002687 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002688 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2689 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002690 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002691
Eric Laurent3a4311c2014-03-17 12:00:47 -07002692 if (outProfile->mSupportedDevices.isEmpty()) {
2693 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2694 continue;
2695 }
2696
Eric Laurentd78f1532014-09-16 16:38:20 -07002697 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2698 continue;
2699 }
Eric Laurent83b88082014-06-20 18:31:16 -07002700 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2701 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2702 profileType = mDefaultOutputDevice->mDeviceType;
2703 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002704 // chose first device present in mSupportedDevices also part of
2705 // outputDeviceTypes
2706 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2707 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2708 if ((profileType & outputDeviceTypes) != 0) {
2709 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002710 }
Eric Laurente552edb2014-03-10 17:42:56 -07002711 }
2712 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002713 if ((profileType & outputDeviceTypes) == 0) {
2714 continue;
2715 }
2716 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2717
2718 outputDesc->mDevice = profileType;
2719 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2720 config.sample_rate = outputDesc->mSamplingRate;
2721 config.channel_mask = outputDesc->mChannelMask;
2722 config.format = outputDesc->mFormat;
2723 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2724 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2725 &output,
2726 &config,
2727 &outputDesc->mDevice,
2728 String8(""),
2729 &outputDesc->mLatency,
2730 outputDesc->mFlags);
2731
2732 if (status != NO_ERROR) {
2733 ALOGW("Cannot open output stream for device %08x on hw module %s",
2734 outputDesc->mDevice,
2735 mHwModules[i]->mName);
2736 } else {
2737 outputDesc->mSamplingRate = config.sample_rate;
2738 outputDesc->mChannelMask = config.channel_mask;
2739 outputDesc->mFormat = config.format;
2740
2741 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2742 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2743 ssize_t index =
2744 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2745 // give a valid ID to an attached device once confirmed it is reachable
2746 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2747 mAvailableOutputDevices[index]->mId = nextUniqueId();
2748 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2749 }
2750 }
2751 if (mPrimaryOutput == 0 &&
2752 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2753 mPrimaryOutput = output;
2754 }
2755 addOutput(output, outputDesc);
2756 setOutputDevice(output,
2757 outputDesc->mDevice,
2758 true);
2759 }
Eric Laurente552edb2014-03-10 17:42:56 -07002760 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002761 // open input streams needed to access attached devices to validate
2762 // mAvailableInputDevices list
2763 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2764 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002765 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002766
Eric Laurent3a4311c2014-03-17 12:00:47 -07002767 if (inProfile->mSupportedDevices.isEmpty()) {
2768 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2769 continue;
2770 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002771 // chose first device present in mSupportedDevices also part of
2772 // inputDeviceTypes
2773 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2774 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2775 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2776 if (profileType & inputDeviceTypes) {
2777 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002778 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002779 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002780 if ((profileType & inputDeviceTypes) == 0) {
2781 continue;
2782 }
2783 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2784
2785 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2786 inputDesc->mDevice = profileType;
2787
2788 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2789 config.sample_rate = inputDesc->mSamplingRate;
2790 config.channel_mask = inputDesc->mChannelMask;
2791 config.format = inputDesc->mFormat;
2792 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2793 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2794 &input,
2795 &config,
2796 &inputDesc->mDevice,
2797 String8(""),
2798 AUDIO_SOURCE_MIC,
2799 AUDIO_INPUT_FLAG_NONE);
2800
2801 if (status == NO_ERROR) {
2802 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2803 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2804 ssize_t index =
2805 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2806 // give a valid ID to an attached device once confirmed it is reachable
2807 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2808 mAvailableInputDevices[index]->mId = nextUniqueId();
2809 mAvailableInputDevices[index]->mModule = mHwModules[i];
2810 }
2811 }
2812 mpClientInterface->closeInput(input);
2813 } else {
2814 ALOGW("Cannot open input stream for device %08x on hw module %s",
2815 inputDesc->mDevice,
2816 mHwModules[i]->mName);
2817 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002818 }
2819 }
2820 // make sure all attached devices have been allocated a unique ID
2821 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2822 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002823 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002824 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2825 continue;
2826 }
2827 i++;
2828 }
2829 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2830 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002831 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002832 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2833 continue;
2834 }
2835 i++;
2836 }
2837 // make sure default device is reachable
2838 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002839 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002840 }
Eric Laurente552edb2014-03-10 17:42:56 -07002841
2842 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2843
2844 updateDevicesAndOutputs();
2845
2846#ifdef AUDIO_POLICY_TEST
2847 if (mPrimaryOutput != 0) {
2848 AudioParameter outputCmd = AudioParameter();
2849 outputCmd.addInt(String8("set_id"), 0);
2850 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2851
2852 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2853 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002854 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2855 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002856 mTestLatencyMs = 0;
2857 mCurOutput = 0;
2858 mDirectOutput = false;
2859 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2860 mTestOutputs[i] = 0;
2861 }
2862
2863 const size_t SIZE = 256;
2864 char buffer[SIZE];
2865 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2866 run(buffer, ANDROID_PRIORITY_AUDIO);
2867 }
2868#endif //AUDIO_POLICY_TEST
2869}
2870
Eric Laurente0720872014-03-11 09:30:41 -07002871AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002872{
2873#ifdef AUDIO_POLICY_TEST
2874 exit();
2875#endif //AUDIO_POLICY_TEST
2876 for (size_t i = 0; i < mOutputs.size(); i++) {
2877 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002878 }
2879 for (size_t i = 0; i < mInputs.size(); i++) {
2880 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002881 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002882 mAvailableOutputDevices.clear();
2883 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002884 mOutputs.clear();
2885 mInputs.clear();
2886 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002887}
2888
Eric Laurente0720872014-03-11 09:30:41 -07002889status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002890{
2891 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2892}
2893
2894#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002895bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002896{
2897 ALOGV("entering threadLoop()");
2898 while (!exitPending())
2899 {
2900 String8 command;
2901 int valueInt;
2902 String8 value;
2903
2904 Mutex::Autolock _l(mLock);
2905 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2906
2907 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2908 AudioParameter param = AudioParameter(command);
2909
2910 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2911 valueInt != 0) {
2912 ALOGV("Test command %s received", command.string());
2913 String8 target;
2914 if (param.get(String8("target"), target) != NO_ERROR) {
2915 target = "Manager";
2916 }
2917 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2918 param.remove(String8("test_cmd_policy_output"));
2919 mCurOutput = valueInt;
2920 }
2921 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2922 param.remove(String8("test_cmd_policy_direct"));
2923 if (value == "false") {
2924 mDirectOutput = false;
2925 } else if (value == "true") {
2926 mDirectOutput = true;
2927 }
2928 }
2929 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2930 param.remove(String8("test_cmd_policy_input"));
2931 mTestInput = valueInt;
2932 }
2933
2934 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2935 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002936 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002937 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002938 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002939 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002940 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002941 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002942 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002943 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002944 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002945 if (target == "Manager") {
2946 mTestFormat = format;
2947 } else if (mTestOutputs[mCurOutput] != 0) {
2948 AudioParameter outputParam = AudioParameter();
2949 outputParam.addInt(String8("format"), format);
2950 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2951 }
2952 }
2953 }
2954 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2955 param.remove(String8("test_cmd_policy_channels"));
2956 int channels = 0;
2957
2958 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002959 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002960 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002961 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002962 }
2963 if (channels != 0) {
2964 if (target == "Manager") {
2965 mTestChannels = channels;
2966 } else if (mTestOutputs[mCurOutput] != 0) {
2967 AudioParameter outputParam = AudioParameter();
2968 outputParam.addInt(String8("channels"), channels);
2969 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2970 }
2971 }
2972 }
2973 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2974 param.remove(String8("test_cmd_policy_sampleRate"));
2975 if (valueInt >= 0 && valueInt <= 96000) {
2976 int samplingRate = valueInt;
2977 if (target == "Manager") {
2978 mTestSamplingRate = samplingRate;
2979 } else if (mTestOutputs[mCurOutput] != 0) {
2980 AudioParameter outputParam = AudioParameter();
2981 outputParam.addInt(String8("sampling_rate"), samplingRate);
2982 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2983 }
2984 }
2985 }
2986
2987 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2988 param.remove(String8("test_cmd_policy_reopen"));
2989
Eric Laurent1f2f2232014-06-02 12:01:23 -07002990 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002991 mpClientInterface->closeOutput(mPrimaryOutput);
2992
2993 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2994
Eric Laurente552edb2014-03-10 17:42:56 -07002995 mOutputs.removeItem(mPrimaryOutput);
2996
Eric Laurent1f2f2232014-06-02 12:01:23 -07002997 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002998 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002999 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3000 config.sample_rate = outputDesc->mSamplingRate;
3001 config.channel_mask = outputDesc->mChannelMask;
3002 config.format = outputDesc->mFormat;
3003 status_t status = mpClientInterface->openOutput(moduleHandle,
3004 &mPrimaryOutput,
3005 &config,
3006 &outputDesc->mDevice,
3007 String8(""),
3008 &outputDesc->mLatency,
3009 outputDesc->mFlags);
3010 if (status != NO_ERROR) {
3011 ALOGE("Failed to reopen hardware output stream, "
3012 "samplingRate: %d, format %d, channels %d",
3013 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003014 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003015 outputDesc->mSamplingRate = config.sample_rate;
3016 outputDesc->mChannelMask = config.channel_mask;
3017 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003018 AudioParameter outputCmd = AudioParameter();
3019 outputCmd.addInt(String8("set_id"), 0);
3020 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3021 addOutput(mPrimaryOutput, outputDesc);
3022 }
3023 }
3024
3025
3026 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3027 }
3028 }
3029 return false;
3030}
3031
Eric Laurente0720872014-03-11 09:30:41 -07003032void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003033{
3034 {
3035 AutoMutex _l(mLock);
3036 requestExit();
3037 mWaitWorkCV.signal();
3038 }
3039 requestExitAndWait();
3040}
3041
Eric Laurente0720872014-03-11 09:30:41 -07003042int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003043{
3044 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3045 if (output == mTestOutputs[i]) return i;
3046 }
3047 return 0;
3048}
3049#endif //AUDIO_POLICY_TEST
3050
3051// ---
3052
Eric Laurent1f2f2232014-06-02 12:01:23 -07003053void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003054{
Eric Laurent1c333e22014-05-20 10:48:17 -07003055 outputDesc->mIoHandle = output;
3056 outputDesc->mId = nextUniqueId();
3057 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003058 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003059}
3060
Eric Laurent1f2f2232014-06-02 12:01:23 -07003061void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003062{
Eric Laurent1c333e22014-05-20 10:48:17 -07003063 inputDesc->mIoHandle = input;
3064 inputDesc->mId = nextUniqueId();
3065 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003066 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003067}
Eric Laurente552edb2014-03-10 17:42:56 -07003068
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003069void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3070 const String8 address /*in*/,
3071 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3072 // look for a match on the given address on the addresses of the outputs:
3073 // find the address by finding the patch that maps to this output
3074 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3075 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3076 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3077 if (patchIdx >= 0) {
3078 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3079 const int numSinks = patchDesc->mPatch.num_sinks;
3080 for (ssize_t j=0; j < numSinks; j++) {
3081 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3082 const char* patchAddr =
3083 patchDesc->mPatch.sinks[j].ext.device.address;
3084 if (strncmp(patchAddr,
3085 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003086 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003087 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3088 outputs.add(desc->mIoHandle);
3089 break;
3090 }
3091 }
3092 }
3093 }
3094}
3095
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003096status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003097 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003098 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003099 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003100{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003101 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003102 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003103 // erase all current sample rates, formats and channel masks
3104 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003105
Eric Laurent3b73df72014-03-11 09:06:29 -07003106 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003107 // first list already open outputs that can be routed to this device
3108 for (size_t i = 0; i < mOutputs.size(); i++) {
3109 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003110 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003111 if (!deviceDistinguishesOnAddress(device)) {
3112 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3113 outputs.add(mOutputs.keyAt(i));
3114 } else {
3115 ALOGV(" checking address match due to device 0x%x", device);
3116 findIoHandlesByAddress(desc, address, outputs);
3117 }
Eric Laurente552edb2014-03-10 17:42:56 -07003118 }
3119 }
3120 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003121 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003122 for (size_t i = 0; i < mHwModules.size(); i++)
3123 {
3124 if (mHwModules[i]->mHandle == 0) {
3125 continue;
3126 }
3127 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3128 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003129 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003130 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003131 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3132 }
3133 }
3134 }
3135
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003136 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3137
Eric Laurente552edb2014-03-10 17:42:56 -07003138 if (profiles.isEmpty() && outputs.isEmpty()) {
3139 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3140 return BAD_VALUE;
3141 }
3142
3143 // open outputs for matching profiles if needed. Direct outputs are also opened to
3144 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3145 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003146 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003147
3148 // nothing to do if one output is already opened for this profile
3149 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003150 for (j = 0; j < outputs.size(); j++) {
3151 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003152 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003153 // matching profile: save the sample rates, format and channel masks supported
3154 // by the profile in our device descriptor
3155 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003156 break;
3157 }
3158 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003159 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003160 continue;
3161 }
3162
Eric Laurent83b88082014-06-20 18:31:16 -07003163 ALOGV("opening output for device %08x with params %s profile %p",
3164 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003165 desc = new AudioOutputDescriptor(profile);
3166 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003167 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3168 config.sample_rate = desc->mSamplingRate;
3169 config.channel_mask = desc->mChannelMask;
3170 config.format = desc->mFormat;
3171 config.offload_info.sample_rate = desc->mSamplingRate;
3172 config.offload_info.channel_mask = desc->mChannelMask;
3173 config.offload_info.format = desc->mFormat;
3174 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3175 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3176 &output,
3177 &config,
3178 &desc->mDevice,
3179 address,
3180 &desc->mLatency,
3181 desc->mFlags);
3182 if (status == NO_ERROR) {
3183 desc->mSamplingRate = config.sample_rate;
3184 desc->mChannelMask = config.channel_mask;
3185 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003186
Eric Laurentd4692962014-05-05 18:13:44 -07003187 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003188 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003189 char *param = audio_device_address_to_parameter(device, address);
3190 mpClientInterface->setParameters(output, String8(param));
3191 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003192 }
3193
Eric Laurentd4692962014-05-05 18:13:44 -07003194 // Here is where we step through and resolve any "dynamic" fields
3195 String8 reply;
3196 char *value;
3197 if (profile->mSamplingRates[0] == 0) {
3198 reply = mpClientInterface->getParameters(output,
3199 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003200 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003201 reply.string());
3202 value = strpbrk((char *)reply.string(), "=");
3203 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003204 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003205 }
Eric Laurentd4692962014-05-05 18:13:44 -07003206 }
3207 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3208 reply = mpClientInterface->getParameters(output,
3209 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003210 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003211 reply.string());
3212 value = strpbrk((char *)reply.string(), "=");
3213 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003214 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003215 }
Eric Laurentd4692962014-05-05 18:13:44 -07003216 }
3217 if (profile->mChannelMasks[0] == 0) {
3218 reply = mpClientInterface->getParameters(output,
3219 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003220 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003221 reply.string());
3222 value = strpbrk((char *)reply.string(), "=");
3223 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003224 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003225 }
Eric Laurentd4692962014-05-05 18:13:44 -07003226 }
3227 if (((profile->mSamplingRates[0] == 0) &&
3228 (profile->mSamplingRates.size() < 2)) ||
3229 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3230 (profile->mFormats.size() < 2)) ||
3231 ((profile->mChannelMasks[0] == 0) &&
3232 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003233 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003234 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003235 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003236 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3237 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003238 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003239 config.sample_rate = profile->pickSamplingRate();
3240 config.channel_mask = profile->pickChannelMask();
3241 config.format = profile->pickFormat();
3242 config.offload_info.sample_rate = config.sample_rate;
3243 config.offload_info.channel_mask = config.channel_mask;
3244 config.offload_info.format = config.format;
3245 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3246 &output,
3247 &config,
3248 &desc->mDevice,
3249 address,
3250 &desc->mLatency,
3251 desc->mFlags);
3252 if (status == NO_ERROR) {
3253 desc->mSamplingRate = config.sample_rate;
3254 desc->mChannelMask = config.channel_mask;
3255 desc->mFormat = config.format;
3256 } else {
3257 output = AUDIO_IO_HANDLE_NONE;
3258 }
Eric Laurentd4692962014-05-05 18:13:44 -07003259 }
3260
Eric Laurentcf2c0212014-07-25 16:20:43 -07003261 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003262 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003263 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003264 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003265
Eric Laurentd4692962014-05-05 18:13:44 -07003266 // set initial stream volume for device
3267 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003268
Eric Laurentd4692962014-05-05 18:13:44 -07003269 //TODO: configure audio effect output stage here
3270
3271 // open a duplicating output thread for the new output and the primary output
3272 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3273 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003274 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003275 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003276 sp<AudioOutputDescriptor> dupOutputDesc =
3277 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003278 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3279 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3280 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3281 dupOutputDesc->mFormat = desc->mFormat;
3282 dupOutputDesc->mChannelMask = desc->mChannelMask;
3283 dupOutputDesc->mLatency = desc->mLatency;
3284 addOutput(duplicatedOutput, dupOutputDesc);
3285 applyStreamVolumes(duplicatedOutput, device, 0, true);
3286 } else {
3287 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3288 mPrimaryOutput, output);
3289 mpClientInterface->closeOutput(output);
3290 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003291 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003292 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003293 }
Eric Laurente552edb2014-03-10 17:42:56 -07003294 }
3295 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003296 } else {
3297 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003298 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003299 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003300 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003301 profiles.removeAt(profile_index);
3302 profile_index--;
3303 } else {
3304 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003305 devDesc->importAudioPort(profile);
3306
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003307 if (deviceDistinguishesOnAddress(device)) {
3308 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3309 device, address.string());
3310 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3311 NULL/*patch handle*/, address.string());
3312 }
Eric Laurente552edb2014-03-10 17:42:56 -07003313 ALOGV("checkOutputsForDevice(): adding output %d", output);
3314 }
3315 }
3316
3317 if (profiles.isEmpty()) {
3318 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3319 return BAD_VALUE;
3320 }
Eric Laurentd4692962014-05-05 18:13:44 -07003321 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003322 // check if one opened output is not needed any more after disconnecting one device
3323 for (size_t i = 0; i < mOutputs.size(); i++) {
3324 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003325 if (!desc->isDuplicated()) {
3326 if (!(desc->mProfile->mSupportedDevices.types()
3327 & mAvailableOutputDevices.types())) {
3328 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3329 mOutputs.keyAt(i));
3330 outputs.add(mOutputs.keyAt(i));
3331 } else if (deviceDistinguishesOnAddress(device) &&
3332 // exact match on device
3333 (desc->mProfile->mSupportedDevices.types() == device)) {
3334 findIoHandlesByAddress(desc, address, outputs);
3335 }
Eric Laurente552edb2014-03-10 17:42:56 -07003336 }
3337 }
Eric Laurentd4692962014-05-05 18:13:44 -07003338 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003339 for (size_t i = 0; i < mHwModules.size(); i++)
3340 {
3341 if (mHwModules[i]->mHandle == 0) {
3342 continue;
3343 }
3344 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3345 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003346 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003347 if (profile->mSupportedDevices.types() & device) {
3348 ALOGV("checkOutputsForDevice(): "
3349 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003350 if (profile->mSamplingRates[0] == 0) {
3351 profile->mSamplingRates.clear();
3352 profile->mSamplingRates.add(0);
3353 }
3354 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3355 profile->mFormats.clear();
3356 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3357 }
3358 if (profile->mChannelMasks[0] == 0) {
3359 profile->mChannelMasks.clear();
3360 profile->mChannelMasks.add(0);
3361 }
3362 }
3363 }
3364 }
3365 }
3366 return NO_ERROR;
3367}
3368
Eric Laurentd4692962014-05-05 18:13:44 -07003369status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3370 audio_policy_dev_state_t state,
3371 SortedVector<audio_io_handle_t>& inputs,
3372 const String8 address)
3373{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003374 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003375 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3376 // first list already open inputs that can be routed to this device
3377 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3378 desc = mInputs.valueAt(input_index);
3379 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3380 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3381 inputs.add(mInputs.keyAt(input_index));
3382 }
3383 }
3384
3385 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003386 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003387 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3388 {
3389 if (mHwModules[module_idx]->mHandle == 0) {
3390 continue;
3391 }
3392 for (size_t profile_index = 0;
3393 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3394 profile_index++)
3395 {
3396 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3397 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003398 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003399 profile_index, module_idx);
3400 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3401 }
3402 }
3403 }
3404
3405 if (profiles.isEmpty() && inputs.isEmpty()) {
3406 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3407 return BAD_VALUE;
3408 }
3409
3410 // open inputs for matching profiles if needed. Direct inputs are also opened to
3411 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3412 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3413
Eric Laurent1c333e22014-05-20 10:48:17 -07003414 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003415 // nothing to do if one input is already opened for this profile
3416 size_t input_index;
3417 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3418 desc = mInputs.valueAt(input_index);
3419 if (desc->mProfile == profile) {
3420 break;
3421 }
3422 }
3423 if (input_index != mInputs.size()) {
3424 continue;
3425 }
3426
3427 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3428 desc = new AudioInputDescriptor(profile);
3429 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003430 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3431 config.sample_rate = desc->mSamplingRate;
3432 config.channel_mask = desc->mChannelMask;
3433 config.format = desc->mFormat;
3434 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3435 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3436 &input,
3437 &config,
3438 &desc->mDevice,
3439 address,
3440 AUDIO_SOURCE_MIC,
3441 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003442
Eric Laurentcf2c0212014-07-25 16:20:43 -07003443 if (status == NO_ERROR) {
3444 desc->mSamplingRate = config.sample_rate;
3445 desc->mChannelMask = config.channel_mask;
3446 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003447
Eric Laurentd4692962014-05-05 18:13:44 -07003448 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003449 char *param = audio_device_address_to_parameter(device, address);
3450 mpClientInterface->setParameters(input, String8(param));
3451 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003452 }
3453
3454 // Here is where we step through and resolve any "dynamic" fields
3455 String8 reply;
3456 char *value;
3457 if (profile->mSamplingRates[0] == 0) {
3458 reply = mpClientInterface->getParameters(input,
3459 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3460 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3461 reply.string());
3462 value = strpbrk((char *)reply.string(), "=");
3463 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003464 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003465 }
3466 }
3467 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3468 reply = mpClientInterface->getParameters(input,
3469 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3470 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3471 value = strpbrk((char *)reply.string(), "=");
3472 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003473 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003474 }
3475 }
3476 if (profile->mChannelMasks[0] == 0) {
3477 reply = mpClientInterface->getParameters(input,
3478 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3479 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3480 reply.string());
3481 value = strpbrk((char *)reply.string(), "=");
3482 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003483 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003484 }
3485 }
3486 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3487 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3488 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3489 ALOGW("checkInputsForDevice() direct input missing param");
3490 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003491 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003492 }
3493
3494 if (input != 0) {
3495 addInput(input, desc);
3496 }
3497 } // endif input != 0
3498
Eric Laurentcf2c0212014-07-25 16:20:43 -07003499 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003500 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003501 profiles.removeAt(profile_index);
3502 profile_index--;
3503 } else {
3504 inputs.add(input);
3505 ALOGV("checkInputsForDevice(): adding input %d", input);
3506 }
3507 } // end scan profiles
3508
3509 if (profiles.isEmpty()) {
3510 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3511 return BAD_VALUE;
3512 }
3513 } else {
3514 // Disconnect
3515 // check if one opened input is not needed any more after disconnecting one device
3516 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3517 desc = mInputs.valueAt(input_index);
3518 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3519 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3520 mInputs.keyAt(input_index));
3521 inputs.add(mInputs.keyAt(input_index));
3522 }
3523 }
3524 // Clear any profiles associated with the disconnected device.
3525 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3526 if (mHwModules[module_index]->mHandle == 0) {
3527 continue;
3528 }
3529 for (size_t profile_index = 0;
3530 profile_index < mHwModules[module_index]->mInputProfiles.size();
3531 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003532 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003533 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003534 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003535 profile_index, module_index);
3536 if (profile->mSamplingRates[0] == 0) {
3537 profile->mSamplingRates.clear();
3538 profile->mSamplingRates.add(0);
3539 }
3540 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3541 profile->mFormats.clear();
3542 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3543 }
3544 if (profile->mChannelMasks[0] == 0) {
3545 profile->mChannelMasks.clear();
3546 profile->mChannelMasks.add(0);
3547 }
3548 }
3549 }
3550 }
3551 } // end disconnect
3552
3553 return NO_ERROR;
3554}
3555
3556
Eric Laurente0720872014-03-11 09:30:41 -07003557void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003558{
3559 ALOGV("closeOutput(%d)", output);
3560
Eric Laurent1f2f2232014-06-02 12:01:23 -07003561 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003562 if (outputDesc == NULL) {
3563 ALOGW("closeOutput() unknown output %d", output);
3564 return;
3565 }
3566
3567 // look for duplicated outputs connected to the output being removed.
3568 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003569 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003570 if (dupOutputDesc->isDuplicated() &&
3571 (dupOutputDesc->mOutput1 == outputDesc ||
3572 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003573 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003574 if (dupOutputDesc->mOutput1 == outputDesc) {
3575 outputDesc2 = dupOutputDesc->mOutput2;
3576 } else {
3577 outputDesc2 = dupOutputDesc->mOutput1;
3578 }
3579 // As all active tracks on duplicated output will be deleted,
3580 // and as they were also referenced on the other output, the reference
3581 // count for their stream type must be adjusted accordingly on
3582 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003583 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003584 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003585 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003586 }
3587 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3588 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3589
3590 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003591 mOutputs.removeItem(duplicatedOutput);
3592 }
3593 }
3594
Eric Laurent05b90f82014-08-27 15:32:29 -07003595 nextAudioPortGeneration();
3596
3597 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3598 if (index >= 0) {
3599 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3600 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3601 mAudioPatches.removeItemsAt(index);
3602 mpClientInterface->onAudioPatchListUpdate();
3603 }
3604
Eric Laurente552edb2014-03-10 17:42:56 -07003605 AudioParameter param;
3606 param.add(String8("closing"), String8("true"));
3607 mpClientInterface->setParameters(output, param.toString());
3608
3609 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003610 mOutputs.removeItem(output);
3611 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003612}
3613
3614void AudioPolicyManager::closeInput(audio_io_handle_t input)
3615{
3616 ALOGV("closeInput(%d)", input);
3617
3618 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3619 if (inputDesc == NULL) {
3620 ALOGW("closeInput() unknown input %d", input);
3621 return;
3622 }
3623
Eric Laurent6a94d692014-05-20 11:18:06 -07003624 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003625
3626 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3627 if (index >= 0) {
3628 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3629 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3630 mAudioPatches.removeItemsAt(index);
3631 mpClientInterface->onAudioPatchListUpdate();
3632 }
3633
3634 mpClientInterface->closeInput(input);
3635 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003636}
3637
Eric Laurente0720872014-03-11 09:30:41 -07003638SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003639 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003640{
3641 SortedVector<audio_io_handle_t> outputs;
3642
3643 ALOGVV("getOutputsForDevice() device %04x", device);
3644 for (size_t i = 0; i < openOutputs.size(); i++) {
3645 ALOGVV("output %d isDuplicated=%d device=%04x",
3646 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3647 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3648 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3649 outputs.add(openOutputs.keyAt(i));
3650 }
3651 }
3652 return outputs;
3653}
3654
Eric Laurente0720872014-03-11 09:30:41 -07003655bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003656 SortedVector<audio_io_handle_t>& outputs2)
3657{
3658 if (outputs1.size() != outputs2.size()) {
3659 return false;
3660 }
3661 for (size_t i = 0; i < outputs1.size(); i++) {
3662 if (outputs1[i] != outputs2[i]) {
3663 return false;
3664 }
3665 }
3666 return true;
3667}
3668
Eric Laurente0720872014-03-11 09:30:41 -07003669void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003670{
3671 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3672 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3673 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3674 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3675
3676 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3677 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3678 strategy, srcOutputs[0], dstOutputs[0]);
3679 // mute strategy while moving tracks from one output to another
3680 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003681 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003682 if (desc->isStrategyActive(strategy)) {
3683 setStrategyMute(strategy, true, srcOutputs[i]);
3684 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3685 }
3686 }
3687
3688 // Move effects associated to this strategy from previous output to new output
3689 if (strategy == STRATEGY_MEDIA) {
3690 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3691 SortedVector<audio_io_handle_t> moved;
3692 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003693 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3694 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3695 effectDesc->mIo != fxOutput) {
3696 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003697 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3698 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003699 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003700 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003701 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003702 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003703 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003704 }
3705 }
3706 }
3707 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003708 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3709 if (getStrategy((audio_stream_type_t)i) == strategy) {
3710 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003711 }
3712 }
3713 }
3714}
3715
Eric Laurente0720872014-03-11 09:30:41 -07003716void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003717{
Jon Eklund966095e2014-09-09 15:39:49 -05003718 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3719 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003720 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003721 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3722 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003723 checkOutputForStrategy(STRATEGY_SONIFICATION);
3724 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3725 checkOutputForStrategy(STRATEGY_MEDIA);
3726 checkOutputForStrategy(STRATEGY_DTMF);
3727}
3728
Eric Laurente0720872014-03-11 09:30:41 -07003729audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003730{
Eric Laurente552edb2014-03-10 17:42:56 -07003731 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003732 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003733 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3734 return mOutputs.keyAt(i);
3735 }
3736 }
3737
3738 return 0;
3739}
3740
Eric Laurente0720872014-03-11 09:30:41 -07003741void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003742{
Eric Laurente552edb2014-03-10 17:42:56 -07003743 audio_io_handle_t a2dpOutput = getA2dpOutput();
3744 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003745 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003746 return;
3747 }
3748
Eric Laurent3a4311c2014-03-17 12:00:47 -07003749 bool isScoConnected =
3750 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003751 // suspend A2DP output if:
3752 // (NOT already suspended) &&
3753 // ((SCO device is connected &&
3754 // (forced usage for communication || for record is SCO))) ||
3755 // (phone state is ringing || in call)
3756 //
3757 // restore A2DP output if:
3758 // (Already suspended) &&
3759 // ((SCO device is NOT connected ||
3760 // (forced usage NOT for communication && NOT for record is SCO))) &&
3761 // (phone state is NOT ringing && NOT in call)
3762 //
3763 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003764 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003765 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3766 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3767 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3768 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003769
3770 mpClientInterface->restoreOutput(a2dpOutput);
3771 mA2dpSuspended = false;
3772 }
3773 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003774 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003775 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3776 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3777 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3778 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003779
3780 mpClientInterface->suspendOutput(a2dpOutput);
3781 mA2dpSuspended = true;
3782 }
3783 }
3784}
3785
Eric Laurent1c333e22014-05-20 10:48:17 -07003786audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003787{
3788 audio_devices_t device = AUDIO_DEVICE_NONE;
3789
Eric Laurent1f2f2232014-06-02 12:01:23 -07003790 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003791
3792 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3793 if (index >= 0) {
3794 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3795 if (patchDesc->mUid != mUidCached) {
3796 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3797 outputDesc->device(), outputDesc->mPatchHandle);
3798 return outputDesc->device();
3799 }
3800 }
3801
Eric Laurente552edb2014-03-10 17:42:56 -07003802 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003803 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003804 // use device for strategy enforced audible
3805 // 2: we are in call or the strategy phone is active on the output:
3806 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003807 // 3: the strategy for enforced audible is active but not enforced on the output:
3808 // use the device for strategy enforced audible
3809 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003810 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003811 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003812 // use device for strategy "respectful" sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003813 // 6: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003814 // use device for strategy media
Jon Eklund966095e2014-09-09 15:39:49 -05003815 // 7: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003816 // use device for strategy DTMF
Jon Eklund966095e2014-09-09 15:39:49 -05003817 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3818 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003819 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3820 } else if (isInCall() ||
3821 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3822 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003823 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3824 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003825 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3826 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3827 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3828 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3829 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3830 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3831 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3832 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3833 }
3834
Eric Laurent1c333e22014-05-20 10:48:17 -07003835 ALOGV("getNewOutputDevice() selected device %x", device);
3836 return device;
3837}
3838
3839audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3840{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003841 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003842
3843 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3844 if (index >= 0) {
3845 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3846 if (patchDesc->mUid != mUidCached) {
3847 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3848 inputDesc->mDevice, inputDesc->mPatchHandle);
3849 return inputDesc->mDevice;
3850 }
3851 }
3852
Eric Laurent1c333e22014-05-20 10:48:17 -07003853 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3854
3855 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003856 return device;
3857}
3858
Eric Laurente0720872014-03-11 09:30:41 -07003859uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003860 return (uint32_t)getStrategy(stream);
3861}
3862
Eric Laurente0720872014-03-11 09:30:41 -07003863audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003864 // By checking the range of stream before calling getStrategy, we avoid
3865 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3866 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003867 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003868 return AUDIO_DEVICE_NONE;
3869 }
3870 audio_devices_t devices;
3871 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3872 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3873 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3874 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003875 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003876 if (outputDesc->isStrategyActive(strategy)) {
3877 devices = outputDesc->device();
3878 break;
3879 }
Eric Laurente552edb2014-03-10 17:42:56 -07003880 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003881
3882 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
3883 and doesn't really need to.*/
3884 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
3885 devices |= AUDIO_DEVICE_OUT_SPEAKER;
3886 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3887 }
3888
Eric Laurente552edb2014-03-10 17:42:56 -07003889 return devices;
3890}
3891
Eric Laurente0720872014-03-11 09:30:41 -07003892AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003893 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003894 // stream to strategy mapping
3895 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003896 case AUDIO_STREAM_VOICE_CALL:
3897 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003898 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003899 case AUDIO_STREAM_RING:
3900 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003901 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003902 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003903 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003904 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003905 return STRATEGY_DTMF;
3906 default:
3907 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003908 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003909 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3910 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003911 case AUDIO_STREAM_TTS:
3912 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003913 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003914 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003915 return STRATEGY_ENFORCED_AUDIBLE;
3916 }
3917}
3918
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003919uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3920 // flags to strategy mapping
3921 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3922 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3923 }
3924
3925 // usage to strategy mapping
3926 switch (attr->usage) {
3927 case AUDIO_USAGE_MEDIA:
3928 case AUDIO_USAGE_GAME:
3929 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3930 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3931 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3932 return (uint32_t) STRATEGY_MEDIA;
3933
3934 case AUDIO_USAGE_VOICE_COMMUNICATION:
3935 return (uint32_t) STRATEGY_PHONE;
3936
3937 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3938 return (uint32_t) STRATEGY_DTMF;
3939
3940 case AUDIO_USAGE_ALARM:
3941 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3942 return (uint32_t) STRATEGY_SONIFICATION;
3943
3944 case AUDIO_USAGE_NOTIFICATION:
3945 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3946 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3947 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3948 case AUDIO_USAGE_NOTIFICATION_EVENT:
3949 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3950
3951 case AUDIO_USAGE_UNKNOWN:
3952 default:
3953 return (uint32_t) STRATEGY_MEDIA;
3954 }
3955}
3956
Eric Laurente0720872014-03-11 09:30:41 -07003957void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003958 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003959 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003960 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3961 updateDevicesAndOutputs();
3962 break;
3963 default:
3964 break;
3965 }
3966}
3967
Eric Laurente0720872014-03-11 09:30:41 -07003968audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003969 bool fromCache)
3970{
3971 uint32_t device = AUDIO_DEVICE_NONE;
3972
3973 if (fromCache) {
3974 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3975 strategy, mDeviceForStrategy[strategy]);
3976 return mDeviceForStrategy[strategy];
3977 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003978 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003979 switch (strategy) {
3980
3981 case STRATEGY_SONIFICATION_RESPECTFUL:
3982 if (isInCall()) {
3983 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003984 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003985 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3986 // while media is playing on a remote device, use the the sonification behavior.
3987 // Note that we test this usecase before testing if media is playing because
3988 // the isStreamActive() method only informs about the activity of a stream, not
3989 // if it's for local playback. Note also that we use the same delay between both tests
3990 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05003991 //user "safe" speaker if available instead of normal speaker to avoid triggering
3992 //other acoustic safety mechanisms for notification
3993 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
3994 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003995 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003996 // while media is playing (or has recently played), use the same device
3997 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3998 } else {
3999 // when media is not playing anymore, fall back on the sonification behavior
4000 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004001 //user "safe" speaker if available instead of normal speaker to avoid triggering
4002 //other acoustic safety mechanisms for notification
4003 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4004 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004005 }
4006
4007 break;
4008
4009 case STRATEGY_DTMF:
4010 if (!isInCall()) {
4011 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4012 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4013 break;
4014 }
4015 // when in call, DTMF and PHONE strategies follow the same rules
4016 // FALL THROUGH
4017
4018 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004019 // Force use of only devices on primary output if:
4020 // - in call AND
4021 // - cannot route from voice call RX OR
4022 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4023 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4024 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4025 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4026 if (((mAvailableInputDevices.types() &
4027 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4028 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004029 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004030 AUDIO_DEVICE_API_VERSION_3_0))) {
4031 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4032 }
4033 }
Eric Laurente552edb2014-03-10 17:42:56 -07004034 // for phone strategy, we first consider the forced use and then the available devices by order
4035 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004036 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4037 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004038 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004039 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004040 if (device) break;
4041 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004042 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004043 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004044 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004045 if (device) break;
4046 // if SCO device is requested but no SCO device is available, fall back to default case
4047 // FALL THROUGH
4048
4049 default: // FORCE_NONE
4050 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004051 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004052 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004053 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004054 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004055 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004056 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004057 if (device) break;
4058 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004059 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004060 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004061 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004062 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004063 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4064 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004065 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004066 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004067 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004069 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004070 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004071 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004072 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004073 if (device) break;
4074 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004075 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004076 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004077 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004078 if (device == AUDIO_DEVICE_NONE) {
4079 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4080 }
4081 break;
4082
Eric Laurent3b73df72014-03-11 09:06:29 -07004083 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004084 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4085 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004086 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004087 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004088 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004089 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004090 if (device) break;
4091 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004092 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004093 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004094 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004095 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004096 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004097 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004098 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004099 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004100 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004101 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004102 if (device) break;
4103 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004104 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4105 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004106 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004107 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004108 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004109 if (device == AUDIO_DEVICE_NONE) {
4110 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4111 }
4112 break;
4113 }
4114 break;
4115
4116 case STRATEGY_SONIFICATION:
4117
4118 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4119 // handleIncallSonification().
4120 if (isInCall()) {
4121 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4122 break;
4123 }
4124 // FALL THROUGH
4125
4126 case STRATEGY_ENFORCED_AUDIBLE:
4127 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4128 // except:
4129 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4130 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4131
4132 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004133 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004134 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004135 if (device == AUDIO_DEVICE_NONE) {
4136 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4137 }
4138 }
4139 // The second device used for sonification is the same as the device used by media strategy
4140 // FALL THROUGH
4141
4142 case STRATEGY_MEDIA: {
4143 uint32_t device2 = AUDIO_DEVICE_NONE;
4144 if (strategy != STRATEGY_SONIFICATION) {
4145 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004146 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004147 }
4148 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004149 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004150 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004151 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004152 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004153 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004154 }
4155 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004156 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004157 }
4158 }
4159 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004160 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004161 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004162 if ((device2 == AUDIO_DEVICE_NONE)) {
4163 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4164 }
Eric Laurente552edb2014-03-10 17:42:56 -07004165 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004166 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004167 }
4168 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004169 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004170 }
4171 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004172 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004173 }
4174 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004175 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004176 }
4177 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4178 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004179 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004180 }
4181 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004182 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004183 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004184 }
4185 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004186 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004187 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004188 int device3 = AUDIO_DEVICE_NONE;
4189 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004190 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004191 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4192 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004193 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004194 }
Eric Laurente552edb2014-03-10 17:42:56 -07004195
Jungshik Jang839e4f32014-06-26 17:23:40 +09004196 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004197 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4198 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4199 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004200
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004201 // If hdmi system audio mode is on, remove speaker out of output list.
4202 if ((strategy == STRATEGY_MEDIA) &&
4203 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4204 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4205 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4206 }
4207
Eric Laurente552edb2014-03-10 17:42:56 -07004208 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004209 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004210 if (device == AUDIO_DEVICE_NONE) {
4211 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4212 }
4213 } break;
4214
4215 default:
4216 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4217 break;
4218 }
4219
4220 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4221 return device;
4222}
4223
Eric Laurente0720872014-03-11 09:30:41 -07004224void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004225{
4226 for (int i = 0; i < NUM_STRATEGIES; i++) {
4227 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4228 }
4229 mPreviousOutputs = mOutputs;
4230}
4231
Eric Laurent1f2f2232014-06-02 12:01:23 -07004232uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004233 audio_devices_t prevDevice,
4234 uint32_t delayMs)
4235{
4236 // mute/unmute strategies using an incompatible device combination
4237 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4238 // if unmuting, unmute only after the specified delay
4239 if (outputDesc->isDuplicated()) {
4240 return 0;
4241 }
4242
4243 uint32_t muteWaitMs = 0;
4244 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004245 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004246
4247 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4248 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4249 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4250 bool doMute = false;
4251
4252 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4253 doMute = true;
4254 outputDesc->mStrategyMutedByDevice[i] = true;
4255 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4256 doMute = true;
4257 outputDesc->mStrategyMutedByDevice[i] = false;
4258 }
Eric Laurent99401132014-05-07 19:48:15 -07004259 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004260 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004261 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004262 // skip output if it does not share any device with current output
4263 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4264 == AUDIO_DEVICE_NONE) {
4265 continue;
4266 }
4267 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4268 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4269 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4270 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4271 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004272 if (mute) {
4273 // FIXME: should not need to double latency if volume could be applied
4274 // immediately by the audioflinger mixer. We must account for the delay
4275 // between now and the next time the audioflinger thread for this output
4276 // will process a buffer (which corresponds to one buffer size,
4277 // usually 1/2 or 1/4 of the latency).
4278 if (muteWaitMs < desc->latency() * 2) {
4279 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004280 }
4281 }
4282 }
4283 }
4284 }
4285 }
4286
Eric Laurent99401132014-05-07 19:48:15 -07004287 // temporary mute output if device selection changes to avoid volume bursts due to
4288 // different per device volumes
4289 if (outputDesc->isActive() && (device != prevDevice)) {
4290 if (muteWaitMs < outputDesc->latency() * 2) {
4291 muteWaitMs = outputDesc->latency() * 2;
4292 }
4293 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4294 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004295 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004296 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004297 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004298 muteWaitMs *2, device);
4299 }
4300 }
4301 }
4302
Eric Laurente552edb2014-03-10 17:42:56 -07004303 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4304 if (muteWaitMs > delayMs) {
4305 muteWaitMs -= delayMs;
4306 usleep(muteWaitMs * 1000);
4307 return muteWaitMs;
4308 }
4309 return 0;
4310}
4311
Eric Laurente0720872014-03-11 09:30:41 -07004312uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004313 audio_devices_t device,
4314 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004315 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004316 audio_patch_handle_t *patchHandle,
4317 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004318{
4319 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004320 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004321 AudioParameter param;
4322 uint32_t muteWaitMs;
4323
4324 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004325 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4326 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004327 return muteWaitMs;
4328 }
4329 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4330 // output profile
4331 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004332 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004333 return 0;
4334 }
4335
4336 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004337 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004338
4339 audio_devices_t prevDevice = outputDesc->mDevice;
4340
4341 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4342
4343 if (device != AUDIO_DEVICE_NONE) {
4344 outputDesc->mDevice = device;
4345 }
4346 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4347
4348 // Do not change the routing if:
4349 // - the requested device is AUDIO_DEVICE_NONE
4350 // - the requested device is the same as current device and force is not specified.
4351 // Doing this check here allows the caller to call setOutputDevice() without conditions
4352 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4353 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4354 return muteWaitMs;
4355 }
4356
4357 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004358
Eric Laurente552edb2014-03-10 17:42:56 -07004359 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004360 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004361 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004362 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004363 DeviceVector deviceList = (address == NULL) ?
4364 mAvailableOutputDevices.getDevicesFromType(device)
4365 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004366 if (!deviceList.isEmpty()) {
4367 struct audio_patch patch;
4368 outputDesc->toAudioPortConfig(&patch.sources[0]);
4369 patch.num_sources = 1;
4370 patch.num_sinks = 0;
4371 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4372 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004373 patch.num_sinks++;
4374 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004375 ssize_t index;
4376 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4377 index = mAudioPatches.indexOfKey(*patchHandle);
4378 } else {
4379 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4380 }
4381 sp< AudioPatch> patchDesc;
4382 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4383 if (index >= 0) {
4384 patchDesc = mAudioPatches.valueAt(index);
4385 afPatchHandle = patchDesc->mAfPatchHandle;
4386 }
4387
Eric Laurent1c333e22014-05-20 10:48:17 -07004388 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004389 &afPatchHandle,
4390 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004391 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4392 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004393 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004394 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004395 if (index < 0) {
4396 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4397 &patch, mUidCached);
4398 addAudioPatch(patchDesc->mHandle, patchDesc);
4399 } else {
4400 patchDesc->mPatch = patch;
4401 }
4402 patchDesc->mAfPatchHandle = afPatchHandle;
4403 patchDesc->mUid = mUidCached;
4404 if (patchHandle) {
4405 *patchHandle = patchDesc->mHandle;
4406 }
4407 outputDesc->mPatchHandle = patchDesc->mHandle;
4408 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004409 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004410 }
4411 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004412
4413 // inform all input as well
4414 for (size_t i = 0; i < mInputs.size(); i++) {
4415 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4416 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4417 AudioParameter inputCmd = AudioParameter();
4418 ALOGV("%s: inform input %d of device:%d", __func__,
4419 inputDescriptor->mIoHandle, device);
4420 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4421 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4422 inputCmd.toString(),
4423 delayMs);
4424 }
4425 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004426 }
Eric Laurente552edb2014-03-10 17:42:56 -07004427
4428 // update stream volumes according to new device
4429 applyStreamVolumes(output, device, delayMs);
4430
4431 return muteWaitMs;
4432}
4433
Eric Laurent1c333e22014-05-20 10:48:17 -07004434status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004435 int delayMs,
4436 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004437{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004438 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004439 ssize_t index;
4440 if (patchHandle) {
4441 index = mAudioPatches.indexOfKey(*patchHandle);
4442 } else {
4443 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4444 }
4445 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004446 return INVALID_OPERATION;
4447 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004448 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4449 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004450 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4451 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004452 removeAudioPatch(patchDesc->mHandle);
4453 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004454 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004455 return status;
4456}
4457
4458status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4459 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004460 bool force,
4461 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004462{
4463 status_t status = NO_ERROR;
4464
Eric Laurent1f2f2232014-06-02 12:01:23 -07004465 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004466 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4467 inputDesc->mDevice = device;
4468
4469 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4470 if (!deviceList.isEmpty()) {
4471 struct audio_patch patch;
4472 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004473 // AUDIO_SOURCE_HOTWORD is for internal use only:
4474 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004475 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4476 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004477 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4478 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004479 patch.num_sinks = 1;
4480 //only one input device for now
4481 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004482 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004483 ssize_t index;
4484 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4485 index = mAudioPatches.indexOfKey(*patchHandle);
4486 } else {
4487 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4488 }
4489 sp< AudioPatch> patchDesc;
4490 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4491 if (index >= 0) {
4492 patchDesc = mAudioPatches.valueAt(index);
4493 afPatchHandle = patchDesc->mAfPatchHandle;
4494 }
4495
Eric Laurent1c333e22014-05-20 10:48:17 -07004496 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004497 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004498 0);
4499 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004500 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004501 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004502 if (index < 0) {
4503 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4504 &patch, mUidCached);
4505 addAudioPatch(patchDesc->mHandle, patchDesc);
4506 } else {
4507 patchDesc->mPatch = patch;
4508 }
4509 patchDesc->mAfPatchHandle = afPatchHandle;
4510 patchDesc->mUid = mUidCached;
4511 if (patchHandle) {
4512 *patchHandle = patchDesc->mHandle;
4513 }
4514 inputDesc->mPatchHandle = patchDesc->mHandle;
4515 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004516 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004517 }
4518 }
4519 }
4520 return status;
4521}
4522
Eric Laurent6a94d692014-05-20 11:18:06 -07004523status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4524 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004525{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004526 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004527 ssize_t index;
4528 if (patchHandle) {
4529 index = mAudioPatches.indexOfKey(*patchHandle);
4530 } else {
4531 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4532 }
4533 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004534 return INVALID_OPERATION;
4535 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004536 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4537 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004538 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4539 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004540 removeAudioPatch(patchDesc->mHandle);
4541 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004542 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004543 return status;
4544}
4545
4546sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004547 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004548 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004549 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004550 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004551{
4552 // Choose an input profile based on the requested capture parameters: select the first available
4553 // profile supporting all requested parameters.
4554
4555 for (size_t i = 0; i < mHwModules.size(); i++)
4556 {
4557 if (mHwModules[i]->mHandle == 0) {
4558 continue;
4559 }
4560 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4561 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004562 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004563 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004564 if (profile->isCompatibleProfile(device, samplingRate,
4565 &samplingRate /*updatedSamplingRate*/,
4566 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004567 return profile;
4568 }
4569 }
4570 }
4571 return NULL;
4572}
4573
Eric Laurente0720872014-03-11 09:30:41 -07004574audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004575{
4576 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004577 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4578 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004579 switch (inputSource) {
4580 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004581 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004582 device = AUDIO_DEVICE_IN_VOICE_CALL;
4583 break;
4584 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004585 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004586
4587 case AUDIO_SOURCE_DEFAULT:
4588 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004589 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4590 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004591 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4592 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4593 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4594 device = AUDIO_DEVICE_IN_USB_DEVICE;
4595 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4596 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004597 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004598 break;
4599
4600 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4601 // Allow only use of devices on primary input if in call and HAL does not support routing
4602 // to voice call path.
4603 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4604 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4605 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4606 }
4607
4608 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4609 case AUDIO_POLICY_FORCE_BT_SCO:
4610 // if SCO device is requested but no SCO device is available, fall back to default case
4611 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4612 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4613 break;
4614 }
4615 // FALL THROUGH
4616
4617 default: // FORCE_NONE
4618 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4619 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4620 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4621 device = AUDIO_DEVICE_IN_USB_DEVICE;
4622 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4623 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4624 }
4625 break;
4626
4627 case AUDIO_POLICY_FORCE_SPEAKER:
4628 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4629 device = AUDIO_DEVICE_IN_BACK_MIC;
4630 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4631 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4632 }
4633 break;
4634 }
4635 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004636
Eric Laurente552edb2014-03-10 17:42:56 -07004637 case AUDIO_SOURCE_VOICE_RECOGNITION:
4638 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004639 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004640 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004641 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004642 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004643 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004644 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4645 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004646 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004647 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4648 }
4649 break;
4650 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004651 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004652 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004653 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004654 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4655 }
4656 break;
4657 case AUDIO_SOURCE_VOICE_DOWNLINK:
4658 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004659 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004660 device = AUDIO_DEVICE_IN_VOICE_CALL;
4661 }
4662 break;
4663 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004664 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004665 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4666 }
4667 break;
4668 default:
4669 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4670 break;
4671 }
4672 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4673 return device;
4674}
4675
Eric Laurente0720872014-03-11 09:30:41 -07004676bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004677{
4678 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4679 device &= ~AUDIO_DEVICE_BIT_IN;
4680 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4681 return true;
4682 }
4683 return false;
4684}
4685
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004686bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4687 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4688}
4689
Eric Laurente0720872014-03-11 09:30:41 -07004690audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004691{
4692 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004693 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004694 if ((input_descriptor->mRefCount > 0)
4695 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4696 return mInputs.keyAt(i);
4697 }
4698 }
4699 return 0;
4700}
4701
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004702uint32_t AudioPolicyManager::activeInputsCount() const
4703{
4704 uint32_t count = 0;
4705 for (size_t i = 0; i < mInputs.size(); i++) {
4706 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4707 if (desc->mRefCount > 0) {
4708 return count++;
4709 }
4710 }
4711 return count;
4712}
4713
Eric Laurente552edb2014-03-10 17:42:56 -07004714
Eric Laurente0720872014-03-11 09:30:41 -07004715audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004716{
4717 if (device == AUDIO_DEVICE_NONE) {
4718 // this happens when forcing a route update and no track is active on an output.
4719 // In this case the returned category is not important.
4720 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004721 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004722 // Multiple device selection is either:
4723 // - speaker + one other device: give priority to speaker in this case.
4724 // - one A2DP device + another device: happens with duplicated output. In this case
4725 // retain the device on the A2DP output as the other must not correspond to an active
4726 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004727 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004728 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4729 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004730 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4731 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4732 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4733 device = AUDIO_DEVICE_OUT_AUX_LINE;
4734 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4735 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004736 } else {
4737 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4738 }
4739 }
4740
Jon Eklund11c9fb12014-06-23 14:47:03 -05004741 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4742 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4743 device = AUDIO_DEVICE_OUT_SPEAKER;
4744
Eric Laurent3b73df72014-03-11 09:06:29 -07004745 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004746 "getDeviceForVolume() invalid device combination: %08x",
4747 device);
4748
4749 return device;
4750}
4751
Eric Laurente0720872014-03-11 09:30:41 -07004752AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004753{
4754 switch(getDeviceForVolume(device)) {
4755 case AUDIO_DEVICE_OUT_EARPIECE:
4756 return DEVICE_CATEGORY_EARPIECE;
4757 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4758 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4759 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4760 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4761 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4762 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4763 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004764 case AUDIO_DEVICE_OUT_LINE:
4765 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4766 /*USB? Remote submix?*/
4767 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004768 case AUDIO_DEVICE_OUT_SPEAKER:
4769 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4770 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004771 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4772 case AUDIO_DEVICE_OUT_USB_DEVICE:
4773 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4774 default:
4775 return DEVICE_CATEGORY_SPEAKER;
4776 }
4777}
4778
Eric Laurente0720872014-03-11 09:30:41 -07004779float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004780 int indexInUi)
4781{
4782 device_category deviceCategory = getDeviceCategory(device);
4783 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4784
4785 // the volume index in the UI is relative to the min and max volume indices for this stream type
4786 int nbSteps = 1 + curve[VOLMAX].mIndex -
4787 curve[VOLMIN].mIndex;
4788 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4789 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4790
4791 // find what part of the curve this index volume belongs to, or if it's out of bounds
4792 int segment = 0;
4793 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4794 return 0.0f;
4795 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4796 segment = 0;
4797 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4798 segment = 1;
4799 } else if (volIdx <= curve[VOLMAX].mIndex) {
4800 segment = 2;
4801 } else { // out of bounds
4802 return 1.0f;
4803 }
4804
4805 // linear interpolation in the attenuation table in dB
4806 float decibels = curve[segment].mDBAttenuation +
4807 ((float)(volIdx - curve[segment].mIndex)) *
4808 ( (curve[segment+1].mDBAttenuation -
4809 curve[segment].mDBAttenuation) /
4810 ((float)(curve[segment+1].mIndex -
4811 curve[segment].mIndex)) );
4812
4813 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4814
4815 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4816 curve[segment].mIndex, volIdx,
4817 curve[segment+1].mIndex,
4818 curve[segment].mDBAttenuation,
4819 decibels,
4820 curve[segment+1].mDBAttenuation,
4821 amplification);
4822
4823 return amplification;
4824}
4825
Eric Laurente0720872014-03-11 09:30:41 -07004826const AudioPolicyManager::VolumeCurvePoint
4827 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004828 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4829};
4830
Eric Laurente0720872014-03-11 09:30:41 -07004831const AudioPolicyManager::VolumeCurvePoint
4832 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004833 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4834};
4835
Eric Laurente0720872014-03-11 09:30:41 -07004836const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004837 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4838 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4839};
4840
4841const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004842 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004843 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4844};
4845
Eric Laurente0720872014-03-11 09:30:41 -07004846const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004847 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004848 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004849};
4850
4851const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004852 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004853 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4854};
4855
Eric Laurente0720872014-03-11 09:30:41 -07004856const AudioPolicyManager::VolumeCurvePoint
4857 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004858 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4859};
4860
4861// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4862// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4863// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4864// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4865
Eric Laurente0720872014-03-11 09:30:41 -07004866const AudioPolicyManager::VolumeCurvePoint
4867 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004868 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4869};
4870
Eric Laurente0720872014-03-11 09:30:41 -07004871const AudioPolicyManager::VolumeCurvePoint
4872 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004873 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4874};
4875
Eric Laurente0720872014-03-11 09:30:41 -07004876const AudioPolicyManager::VolumeCurvePoint
4877 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004878 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4879};
4880
Eric Laurente0720872014-03-11 09:30:41 -07004881const AudioPolicyManager::VolumeCurvePoint
4882 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004883 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4884};
4885
Eric Laurente0720872014-03-11 09:30:41 -07004886const AudioPolicyManager::VolumeCurvePoint
4887 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004888 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4889};
4890
Eric Laurente0720872014-03-11 09:30:41 -07004891const AudioPolicyManager::VolumeCurvePoint
4892 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4893 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004894 { // AUDIO_STREAM_VOICE_CALL
4895 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4896 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004897 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4898 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004899 },
4900 { // AUDIO_STREAM_SYSTEM
4901 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4902 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004903 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4904 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004905 },
4906 { // AUDIO_STREAM_RING
4907 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4908 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004909 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4910 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004911 },
4912 { // AUDIO_STREAM_MUSIC
4913 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4914 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004915 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4916 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004917 },
4918 { // AUDIO_STREAM_ALARM
4919 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4920 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004921 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4922 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004923 },
4924 { // AUDIO_STREAM_NOTIFICATION
4925 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4926 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004927 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4928 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004929 },
4930 { // AUDIO_STREAM_BLUETOOTH_SCO
4931 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4932 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004933 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4934 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004935 },
4936 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4937 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4938 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004939 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4940 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004941 },
4942 { // AUDIO_STREAM_DTMF
4943 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4944 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004945 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4946 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004947 },
4948 { // AUDIO_STREAM_TTS
4949 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4950 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004951 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4952 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004953 },
4954};
4955
Eric Laurente0720872014-03-11 09:30:41 -07004956void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004957{
4958 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4959 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4960 mStreams[i].mVolumeCurve[j] =
4961 sVolumeProfiles[i][j];
4962 }
4963 }
4964
4965 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4966 if (mSpeakerDrcEnabled) {
4967 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4968 sDefaultSystemVolumeCurveDrc;
4969 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4970 sSpeakerSonificationVolumeCurveDrc;
4971 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4972 sSpeakerSonificationVolumeCurveDrc;
4973 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4974 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004975 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4976 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004977 }
4978}
4979
Eric Laurente0720872014-03-11 09:30:41 -07004980float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004981 int index,
4982 audio_io_handle_t output,
4983 audio_devices_t device)
4984{
4985 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004986 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004987 StreamDescriptor &streamDesc = mStreams[stream];
4988
4989 if (device == AUDIO_DEVICE_NONE) {
4990 device = outputDesc->device();
4991 }
4992
Eric Laurente552edb2014-03-10 17:42:56 -07004993 volume = volIndexToAmpl(device, streamDesc, index);
4994
4995 // if a headset is connected, apply the following rules to ring tones and notifications
4996 // to avoid sound level bursts in user's ears:
4997 // - always attenuate ring tones and notifications volume by 6dB
4998 // - if music is playing, always limit the volume to current music volume,
4999 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005000 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005001 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5002 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5003 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5004 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5005 ((stream_strategy == STRATEGY_SONIFICATION)
5006 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005007 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005008 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005009 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005010 streamDesc.mCanBeMuted) {
5011 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5012 // when the phone is ringing we must consider that music could have been paused just before
5013 // by the music application and behave as if music was active if the last music track was
5014 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005015 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005016 mLimitRingtoneVolume) {
5017 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005018 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5019 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005020 output,
5021 musicDevice);
5022 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5023 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5024 if (volume > minVol) {
5025 volume = minVol;
5026 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5027 }
5028 }
5029 }
5030
5031 return volume;
5032}
5033
Eric Laurente0720872014-03-11 09:30:41 -07005034status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005035 int index,
5036 audio_io_handle_t output,
5037 audio_devices_t device,
5038 int delayMs,
5039 bool force)
5040{
5041
5042 // do not change actual stream volume if the stream is muted
5043 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5044 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5045 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5046 return NO_ERROR;
5047 }
5048
5049 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005050 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5051 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5052 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5053 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005054 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005055 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005056 return INVALID_OPERATION;
5057 }
5058
5059 float volume = computeVolume(stream, index, output, device);
5060 // We actually change the volume if:
5061 // - the float value returned by computeVolume() changed
5062 // - the force flag is set
5063 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5064 force) {
5065 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5066 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5067 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5068 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005069 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5070 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005071 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005072 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005073 }
5074
Eric Laurent3b73df72014-03-11 09:06:29 -07005075 if (stream == AUDIO_STREAM_VOICE_CALL ||
5076 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005077 float voiceVolume;
5078 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005079 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005080 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5081 } else {
5082 voiceVolume = 1.0;
5083 }
5084
5085 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5086 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5087 mLastVoiceVolume = voiceVolume;
5088 }
5089 }
5090
5091 return NO_ERROR;
5092}
5093
Eric Laurente0720872014-03-11 09:30:41 -07005094void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005095 audio_devices_t device,
5096 int delayMs,
5097 bool force)
5098{
5099 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5100
Eric Laurent3b73df72014-03-11 09:06:29 -07005101 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5102 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005103 mStreams[stream].getVolumeIndex(device),
5104 output,
5105 device,
5106 delayMs,
5107 force);
5108 }
5109}
5110
Eric Laurente0720872014-03-11 09:30:41 -07005111void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005112 bool on,
5113 audio_io_handle_t output,
5114 int delayMs,
5115 audio_devices_t device)
5116{
5117 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005118 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5119 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5120 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005121 }
5122 }
5123}
5124
Eric Laurente0720872014-03-11 09:30:41 -07005125void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005126 bool on,
5127 audio_io_handle_t output,
5128 int delayMs,
5129 audio_devices_t device)
5130{
5131 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005132 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005133 if (device == AUDIO_DEVICE_NONE) {
5134 device = outputDesc->device();
5135 }
5136
5137 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5138 stream, on, output, outputDesc->mMuteCount[stream], device);
5139
5140 if (on) {
5141 if (outputDesc->mMuteCount[stream] == 0) {
5142 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005143 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5144 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005145 checkAndSetVolume(stream, 0, output, device, delayMs);
5146 }
5147 }
5148 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5149 outputDesc->mMuteCount[stream]++;
5150 } else {
5151 if (outputDesc->mMuteCount[stream] == 0) {
5152 ALOGV("setStreamMute() unmuting non muted stream!");
5153 return;
5154 }
5155 if (--outputDesc->mMuteCount[stream] == 0) {
5156 checkAndSetVolume(stream,
5157 streamDesc.getVolumeIndex(device),
5158 output,
5159 device,
5160 delayMs);
5161 }
5162 }
5163}
5164
Eric Laurente0720872014-03-11 09:30:41 -07005165void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005166 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005167{
5168 // if the stream pertains to sonification strategy and we are in call we must
5169 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5170 // in the device used for phone strategy and play the tone if the selected device does not
5171 // interfere with the device used for phone strategy
5172 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5173 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005174 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005175 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5176 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005177 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005178 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5179 stream, starting, outputDesc->mDevice, stateChange);
5180 if (outputDesc->mRefCount[stream]) {
5181 int muteCount = 1;
5182 if (stateChange) {
5183 muteCount = outputDesc->mRefCount[stream];
5184 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005185 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005186 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5187 for (int i = 0; i < muteCount; i++) {
5188 setStreamMute(stream, starting, mPrimaryOutput);
5189 }
5190 } else {
5191 ALOGV("handleIncallSonification() high visibility");
5192 if (outputDesc->device() &
5193 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5194 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5195 for (int i = 0; i < muteCount; i++) {
5196 setStreamMute(stream, starting, mPrimaryOutput);
5197 }
5198 }
5199 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005200 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5201 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005202 } else {
5203 mpClientInterface->stopTone();
5204 }
5205 }
5206 }
5207 }
5208}
5209
Eric Laurente0720872014-03-11 09:30:41 -07005210bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005211{
5212 return isStateInCall(mPhoneState);
5213}
5214
Eric Laurente0720872014-03-11 09:30:41 -07005215bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005216 return ((state == AUDIO_MODE_IN_CALL) ||
5217 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005218}
5219
Eric Laurente0720872014-03-11 09:30:41 -07005220uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005221{
5222 return MAX_EFFECTS_CPU_LOAD;
5223}
5224
Eric Laurente0720872014-03-11 09:30:41 -07005225uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005226{
5227 return MAX_EFFECTS_MEMORY;
5228}
5229
Eric Laurent6a94d692014-05-20 11:18:06 -07005230
Eric Laurente552edb2014-03-10 17:42:56 -07005231// --- AudioOutputDescriptor class implementation
5232
Eric Laurente0720872014-03-11 09:30:41 -07005233AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005234 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005235 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005236 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005237 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5238{
5239 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005240 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005241 mRefCount[i] = 0;
5242 mCurVolume[i] = -1.0;
5243 mMuteCount[i] = 0;
5244 mStopTime[i] = 0;
5245 }
5246 for (int i = 0; i < NUM_STRATEGIES; i++) {
5247 mStrategyMutedByDevice[i] = false;
5248 }
5249 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005250 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005251 mSamplingRate = profile->pickSamplingRate();
5252 mFormat = profile->pickFormat();
5253 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005254 if (profile->mGains.size() > 0) {
5255 profile->mGains[0]->getDefaultConfig(&mGain);
5256 }
Eric Laurente552edb2014-03-10 17:42:56 -07005257 }
5258}
5259
Eric Laurente0720872014-03-11 09:30:41 -07005260audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005261{
5262 if (isDuplicated()) {
5263 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5264 } else {
5265 return mDevice;
5266 }
5267}
5268
Eric Laurente0720872014-03-11 09:30:41 -07005269uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005270{
5271 if (isDuplicated()) {
5272 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5273 } else {
5274 return mLatency;
5275 }
5276}
5277
Eric Laurente0720872014-03-11 09:30:41 -07005278bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005279 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005280{
5281 if (isDuplicated()) {
5282 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5283 } else if (outputDesc->isDuplicated()){
5284 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5285 } else {
5286 return (mProfile->mModule == outputDesc->mProfile->mModule);
5287 }
5288}
5289
Eric Laurente0720872014-03-11 09:30:41 -07005290void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005291 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005292{
5293 // forward usage count change to attached outputs
5294 if (isDuplicated()) {
5295 mOutput1->changeRefCount(stream, delta);
5296 mOutput2->changeRefCount(stream, delta);
5297 }
5298 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005299 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5300 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005301 mRefCount[stream] = 0;
5302 return;
5303 }
5304 mRefCount[stream] += delta;
5305 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5306}
5307
Eric Laurente0720872014-03-11 09:30:41 -07005308audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005309{
5310 if (isDuplicated()) {
5311 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5312 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005313 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005314 }
5315}
5316
Eric Laurente0720872014-03-11 09:30:41 -07005317bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005318{
5319 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5320}
5321
Eric Laurente0720872014-03-11 09:30:41 -07005322bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005323 uint32_t inPastMs,
5324 nsecs_t sysTime) const
5325{
5326 if ((sysTime == 0) && (inPastMs != 0)) {
5327 sysTime = systemTime();
5328 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005329 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5330 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005331 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005332 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005333 return true;
5334 }
5335 }
5336 return false;
5337}
5338
Eric Laurente0720872014-03-11 09:30:41 -07005339bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005340 uint32_t inPastMs,
5341 nsecs_t sysTime) const
5342{
5343 if (mRefCount[stream] != 0) {
5344 return true;
5345 }
5346 if (inPastMs == 0) {
5347 return false;
5348 }
5349 if (sysTime == 0) {
5350 sysTime = systemTime();
5351 }
5352 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5353 return true;
5354 }
5355 return false;
5356}
5357
Eric Laurent1c333e22014-05-20 10:48:17 -07005358void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005359 struct audio_port_config *dstConfig,
5360 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005361{
Eric Laurent84c70242014-06-23 08:46:27 -07005362 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5363
Eric Laurent1f2f2232014-06-02 12:01:23 -07005364 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5365 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5366 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005367 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005368 }
5369 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5370
Eric Laurent6a94d692014-05-20 11:18:06 -07005371 dstConfig->id = mId;
5372 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5373 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005374 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5375 dstConfig->ext.mix.handle = mIoHandle;
5376 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005377}
5378
5379void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5380 struct audio_port *port) const
5381{
Eric Laurent84c70242014-06-23 08:46:27 -07005382 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005383 mProfile->toAudioPort(port);
5384 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005385 toAudioPortConfig(&port->active_config);
5386 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005387 port->ext.mix.handle = mIoHandle;
5388 port->ext.mix.latency_class =
5389 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5390}
Eric Laurente552edb2014-03-10 17:42:56 -07005391
Eric Laurente0720872014-03-11 09:30:41 -07005392status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005393{
5394 const size_t SIZE = 256;
5395 char buffer[SIZE];
5396 String8 result;
5397
Eric Laurent4d416952014-08-10 14:07:09 -07005398 snprintf(buffer, SIZE, " ID: %d\n", mId);
5399 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005400 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5401 result.append(buffer);
5402 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5403 result.append(buffer);
5404 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5405 result.append(buffer);
5406 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5407 result.append(buffer);
5408 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5409 result.append(buffer);
5410 snprintf(buffer, SIZE, " Devices %08x\n", device());
5411 result.append(buffer);
5412 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5413 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005414 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5415 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5416 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005417 result.append(buffer);
5418 }
5419 write(fd, result.string(), result.size());
5420
5421 return NO_ERROR;
5422}
5423
5424// --- AudioInputDescriptor class implementation
5425
Eric Laurent1c333e22014-05-20 10:48:17 -07005426AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005427 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005428 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005429 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005430{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005431 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005432 mSamplingRate = profile->pickSamplingRate();
5433 mFormat = profile->pickFormat();
5434 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005435 if (profile->mGains.size() > 0) {
5436 profile->mGains[0]->getDefaultConfig(&mGain);
5437 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005438 }
Eric Laurente552edb2014-03-10 17:42:56 -07005439}
5440
Eric Laurent1c333e22014-05-20 10:48:17 -07005441void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005442 struct audio_port_config *dstConfig,
5443 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005444{
Eric Laurent84c70242014-06-23 08:46:27 -07005445 ALOG_ASSERT(mProfile != 0,
5446 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005447 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5448 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5449 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005450 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005451 }
5452
5453 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5454
Eric Laurent6a94d692014-05-20 11:18:06 -07005455 dstConfig->id = mId;
5456 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5457 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005458 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5459 dstConfig->ext.mix.handle = mIoHandle;
5460 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005461}
5462
5463void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5464 struct audio_port *port) const
5465{
Eric Laurent84c70242014-06-23 08:46:27 -07005466 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5467
Eric Laurent1c333e22014-05-20 10:48:17 -07005468 mProfile->toAudioPort(port);
5469 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005470 toAudioPortConfig(&port->active_config);
5471 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005472 port->ext.mix.handle = mIoHandle;
5473 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5474}
5475
Eric Laurente0720872014-03-11 09:30:41 -07005476status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005477{
5478 const size_t SIZE = 256;
5479 char buffer[SIZE];
5480 String8 result;
5481
Eric Laurent4d416952014-08-10 14:07:09 -07005482 snprintf(buffer, SIZE, " ID: %d\n", mId);
5483 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005484 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5485 result.append(buffer);
5486 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5487 result.append(buffer);
5488 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5489 result.append(buffer);
5490 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5491 result.append(buffer);
5492 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5493 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005494 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5495 result.append(buffer);
5496
Eric Laurente552edb2014-03-10 17:42:56 -07005497 write(fd, result.string(), result.size());
5498
5499 return NO_ERROR;
5500}
5501
5502// --- StreamDescriptor class implementation
5503
Eric Laurente0720872014-03-11 09:30:41 -07005504AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005505 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5506{
5507 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5508}
5509
Eric Laurente0720872014-03-11 09:30:41 -07005510int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005511{
Eric Laurente0720872014-03-11 09:30:41 -07005512 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005513 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5514 if (mIndexCur.indexOfKey(device) < 0) {
5515 device = AUDIO_DEVICE_OUT_DEFAULT;
5516 }
5517 return mIndexCur.valueFor(device);
5518}
5519
Eric Laurente0720872014-03-11 09:30:41 -07005520void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005521{
5522 const size_t SIZE = 256;
5523 char buffer[SIZE];
5524 String8 result;
5525
5526 snprintf(buffer, SIZE, "%s %02d %02d ",
5527 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5528 result.append(buffer);
5529 for (size_t i = 0; i < mIndexCur.size(); i++) {
5530 snprintf(buffer, SIZE, "%04x : %02d, ",
5531 mIndexCur.keyAt(i),
5532 mIndexCur.valueAt(i));
5533 result.append(buffer);
5534 }
5535 result.append("\n");
5536
5537 write(fd, result.string(), result.size());
5538}
5539
5540// --- EffectDescriptor class implementation
5541
Eric Laurente0720872014-03-11 09:30:41 -07005542status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005543{
5544 const size_t SIZE = 256;
5545 char buffer[SIZE];
5546 String8 result;
5547
5548 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5549 result.append(buffer);
5550 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5551 result.append(buffer);
5552 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5553 result.append(buffer);
5554 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5555 result.append(buffer);
5556 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5557 result.append(buffer);
5558 write(fd, result.string(), result.size());
5559
5560 return NO_ERROR;
5561}
5562
Eric Laurent1c333e22014-05-20 10:48:17 -07005563// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005564
Eric Laurente0720872014-03-11 09:30:41 -07005565AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005566 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5567 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005568{
5569}
5570
Eric Laurente0720872014-03-11 09:30:41 -07005571AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005572{
5573 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005574 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005575 }
5576 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005577 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005578 }
5579 free((void *)mName);
5580}
5581
Eric Laurent1afeecb2014-05-14 08:52:28 -07005582status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5583{
5584 cnode *node = root->first_child;
5585
5586 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5587
5588 while (node) {
5589 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5590 profile->loadSamplingRates((char *)node->value);
5591 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5592 profile->loadFormats((char *)node->value);
5593 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5594 profile->loadInChannels((char *)node->value);
5595 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5596 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5597 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005598 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5599 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005600 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5601 profile->loadGains(node);
5602 }
5603 node = node->next;
5604 }
5605 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5606 "loadInput() invalid supported devices");
5607 ALOGW_IF(profile->mChannelMasks.size() == 0,
5608 "loadInput() invalid supported channel masks");
5609 ALOGW_IF(profile->mSamplingRates.size() == 0,
5610 "loadInput() invalid supported sampling rates");
5611 ALOGW_IF(profile->mFormats.size() == 0,
5612 "loadInput() invalid supported formats");
5613 if (!profile->mSupportedDevices.isEmpty() &&
5614 (profile->mChannelMasks.size() != 0) &&
5615 (profile->mSamplingRates.size() != 0) &&
5616 (profile->mFormats.size() != 0)) {
5617
5618 ALOGV("loadInput() adding input Supported Devices %04x",
5619 profile->mSupportedDevices.types());
5620
5621 mInputProfiles.add(profile);
5622 return NO_ERROR;
5623 } else {
5624 return BAD_VALUE;
5625 }
5626}
5627
5628status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5629{
5630 cnode *node = root->first_child;
5631
5632 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5633
5634 while (node) {
5635 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5636 profile->loadSamplingRates((char *)node->value);
5637 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5638 profile->loadFormats((char *)node->value);
5639 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5640 profile->loadOutChannels((char *)node->value);
5641 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5642 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5643 mDeclaredDevices);
5644 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005645 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005646 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5647 profile->loadGains(node);
5648 }
5649 node = node->next;
5650 }
5651 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5652 "loadOutput() invalid supported devices");
5653 ALOGW_IF(profile->mChannelMasks.size() == 0,
5654 "loadOutput() invalid supported channel masks");
5655 ALOGW_IF(profile->mSamplingRates.size() == 0,
5656 "loadOutput() invalid supported sampling rates");
5657 ALOGW_IF(profile->mFormats.size() == 0,
5658 "loadOutput() invalid supported formats");
5659 if (!profile->mSupportedDevices.isEmpty() &&
5660 (profile->mChannelMasks.size() != 0) &&
5661 (profile->mSamplingRates.size() != 0) &&
5662 (profile->mFormats.size() != 0)) {
5663
5664 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5665 profile->mSupportedDevices.types(), profile->mFlags);
5666
5667 mOutputProfiles.add(profile);
5668 return NO_ERROR;
5669 } else {
5670 return BAD_VALUE;
5671 }
5672}
5673
5674status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5675{
5676 cnode *node = root->first_child;
5677
5678 audio_devices_t type = AUDIO_DEVICE_NONE;
5679 while (node) {
5680 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5681 type = parseDeviceNames((char *)node->value);
5682 break;
5683 }
5684 node = node->next;
5685 }
5686 if (type == AUDIO_DEVICE_NONE ||
5687 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5688 ALOGW("loadDevice() bad type %08x", type);
5689 return BAD_VALUE;
5690 }
5691 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5692 deviceDesc->mModule = this;
5693
5694 node = root->first_child;
5695 while (node) {
5696 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5697 deviceDesc->mAddress = String8((char *)node->value);
5698 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5699 if (audio_is_input_device(type)) {
5700 deviceDesc->loadInChannels((char *)node->value);
5701 } else {
5702 deviceDesc->loadOutChannels((char *)node->value);
5703 }
5704 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5705 deviceDesc->loadGains(node);
5706 }
5707 node = node->next;
5708 }
5709
5710 ALOGV("loadDevice() adding device name %s type %08x address %s",
5711 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5712
5713 mDeclaredDevices.add(deviceDesc);
5714
5715 return NO_ERROR;
5716}
5717
Eric Laurente0720872014-03-11 09:30:41 -07005718void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005719{
5720 const size_t SIZE = 256;
5721 char buffer[SIZE];
5722 String8 result;
5723
5724 snprintf(buffer, SIZE, " - name: %s\n", mName);
5725 result.append(buffer);
5726 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5727 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005728 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5729 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005730 write(fd, result.string(), result.size());
5731 if (mOutputProfiles.size()) {
5732 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5733 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005734 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005735 write(fd, buffer, strlen(buffer));
5736 mOutputProfiles[i]->dump(fd);
5737 }
5738 }
5739 if (mInputProfiles.size()) {
5740 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5741 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005742 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005743 write(fd, buffer, strlen(buffer));
5744 mInputProfiles[i]->dump(fd);
5745 }
5746 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005747 if (mDeclaredDevices.size()) {
5748 write(fd, " - devices:\n", strlen(" - devices:\n"));
5749 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5750 mDeclaredDevices[i]->dump(fd, 4, i);
5751 }
5752 }
Eric Laurente552edb2014-03-10 17:42:56 -07005753}
5754
Eric Laurent1c333e22014-05-20 10:48:17 -07005755// --- AudioPort class implementation
5756
Eric Laurenta121f902014-06-03 13:32:54 -07005757
5758AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5759 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07005760 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07005761{
5762 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5763 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5764}
5765
Eric Laurent1c333e22014-05-20 10:48:17 -07005766void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5767{
5768 port->role = mRole;
5769 port->type = mType;
5770 unsigned int i;
5771 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005772 if (mSamplingRates[i] != 0) {
5773 port->sample_rates[i] = mSamplingRates[i];
5774 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005775 }
5776 port->num_sample_rates = i;
5777 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005778 if (mChannelMasks[i] != 0) {
5779 port->channel_masks[i] = mChannelMasks[i];
5780 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005781 }
5782 port->num_channel_masks = i;
5783 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005784 if (mFormats[i] != 0) {
5785 port->formats[i] = mFormats[i];
5786 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005787 }
5788 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005789
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005790 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005791
5792 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5793 port->gains[i] = mGains[i]->mGain;
5794 }
5795 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005796}
5797
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005798void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5799 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5800 const uint32_t rate = port->mSamplingRates.itemAt(k);
5801 if (rate != 0) { // skip "dynamic" rates
5802 bool hasRate = false;
5803 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5804 if (rate == mSamplingRates.itemAt(l)) {
5805 hasRate = true;
5806 break;
5807 }
5808 }
5809 if (!hasRate) { // never import a sampling rate twice
5810 mSamplingRates.add(rate);
5811 }
5812 }
5813 }
5814 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5815 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5816 if (mask != 0) { // skip "dynamic" masks
5817 bool hasMask = false;
5818 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5819 if (mask == mChannelMasks.itemAt(l)) {
5820 hasMask = true;
5821 break;
5822 }
5823 }
5824 if (!hasMask) { // never import a channel mask twice
5825 mChannelMasks.add(mask);
5826 }
5827 }
5828 }
5829 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5830 const audio_format_t format = port->mFormats.itemAt(k);
5831 if (format != 0) { // skip "dynamic" formats
5832 bool hasFormat = false;
5833 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5834 if (format == mFormats.itemAt(l)) {
5835 hasFormat = true;
5836 break;
5837 }
5838 }
5839 if (!hasFormat) { // never import a channel mask twice
5840 mFormats.add(format);
5841 }
5842 }
5843 }
5844}
5845
5846void AudioPolicyManager::AudioPort::clearCapabilities() {
5847 mChannelMasks.clear();
5848 mFormats.clear();
5849 mSamplingRates.clear();
5850}
Eric Laurent1c333e22014-05-20 10:48:17 -07005851
5852void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5853{
5854 char *str = strtok(name, "|");
5855
5856 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5857 // rates should be read from the output stream after it is opened for the first time
5858 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5859 mSamplingRates.add(0);
5860 return;
5861 }
5862
5863 while (str != NULL) {
5864 uint32_t rate = atoi(str);
5865 if (rate != 0) {
5866 ALOGV("loadSamplingRates() adding rate %d", rate);
5867 mSamplingRates.add(rate);
5868 }
5869 str = strtok(NULL, "|");
5870 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005871}
5872
5873void AudioPolicyManager::AudioPort::loadFormats(char *name)
5874{
5875 char *str = strtok(name, "|");
5876
5877 // by convention, "0' in the first entry in mFormats indicates the supported formats
5878 // should be read from the output stream after it is opened for the first time
5879 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5880 mFormats.add(AUDIO_FORMAT_DEFAULT);
5881 return;
5882 }
5883
5884 while (str != NULL) {
5885 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5886 ARRAY_SIZE(sFormatNameToEnumTable),
5887 str);
5888 if (format != AUDIO_FORMAT_DEFAULT) {
5889 mFormats.add(format);
5890 }
5891 str = strtok(NULL, "|");
5892 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005893}
5894
5895void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5896{
5897 const char *str = strtok(name, "|");
5898
5899 ALOGV("loadInChannels() %s", name);
5900
5901 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5902 mChannelMasks.add(0);
5903 return;
5904 }
5905
5906 while (str != NULL) {
5907 audio_channel_mask_t channelMask =
5908 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5909 ARRAY_SIZE(sInChannelsNameToEnumTable),
5910 str);
5911 if (channelMask != 0) {
5912 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5913 mChannelMasks.add(channelMask);
5914 }
5915 str = strtok(NULL, "|");
5916 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005917}
5918
5919void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5920{
5921 const char *str = strtok(name, "|");
5922
5923 ALOGV("loadOutChannels() %s", name);
5924
5925 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5926 // masks should be read from the output stream after it is opened for the first time
5927 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5928 mChannelMasks.add(0);
5929 return;
5930 }
5931
5932 while (str != NULL) {
5933 audio_channel_mask_t channelMask =
5934 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5935 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5936 str);
5937 if (channelMask != 0) {
5938 mChannelMasks.add(channelMask);
5939 }
5940 str = strtok(NULL, "|");
5941 }
5942 return;
5943}
5944
Eric Laurent1afeecb2014-05-14 08:52:28 -07005945audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5946{
5947 const char *str = strtok(name, "|");
5948
5949 ALOGV("loadGainMode() %s", name);
5950 audio_gain_mode_t mode = 0;
5951 while (str != NULL) {
5952 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5953 ARRAY_SIZE(sGainModeNameToEnumTable),
5954 str);
5955 str = strtok(NULL, "|");
5956 }
5957 return mode;
5958}
5959
Eric Laurenta121f902014-06-03 13:32:54 -07005960void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005961{
5962 cnode *node = root->first_child;
5963
Eric Laurenta121f902014-06-03 13:32:54 -07005964 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005965
5966 while (node) {
5967 if (strcmp(node->name, GAIN_MODE) == 0) {
5968 gain->mGain.mode = loadGainMode((char *)node->value);
5969 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005970 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005971 gain->mGain.channel_mask =
5972 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5973 ARRAY_SIZE(sInChannelsNameToEnumTable),
5974 (char *)node->value);
5975 } else {
5976 gain->mGain.channel_mask =
5977 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5978 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5979 (char *)node->value);
5980 }
5981 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5982 gain->mGain.min_value = atoi((char *)node->value);
5983 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5984 gain->mGain.max_value = atoi((char *)node->value);
5985 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5986 gain->mGain.default_value = atoi((char *)node->value);
5987 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5988 gain->mGain.step_value = atoi((char *)node->value);
5989 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5990 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5991 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5992 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5993 }
5994 node = node->next;
5995 }
5996
5997 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5998 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5999
6000 if (gain->mGain.mode == 0) {
6001 return;
6002 }
6003 mGains.add(gain);
6004}
6005
6006void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6007{
6008 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006009 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006010 while (node) {
6011 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006012 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006013 node = node->next;
6014 }
6015}
6016
Glenn Kastencbd48022014-07-24 13:46:44 -07006017status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006018{
6019 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6020 if (mSamplingRates[i] == samplingRate) {
6021 return NO_ERROR;
6022 }
6023 }
6024 return BAD_VALUE;
6025}
6026
Glenn Kastencbd48022014-07-24 13:46:44 -07006027status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6028 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006029{
Glenn Kastencbd48022014-07-24 13:46:44 -07006030 // Search for the closest supported sampling rate that is above (preferred)
6031 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6032 // The sampling rates do not need to be sorted in ascending order.
6033 ssize_t maxBelow = -1;
6034 ssize_t minAbove = -1;
6035 uint32_t candidate;
6036 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6037 candidate = mSamplingRates[i];
6038 if (candidate == samplingRate) {
6039 if (updatedSamplingRate != NULL) {
6040 *updatedSamplingRate = candidate;
6041 }
6042 return NO_ERROR;
6043 }
6044 // candidate < desired
6045 if (candidate < samplingRate) {
6046 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6047 maxBelow = i;
6048 }
6049 // candidate > desired
6050 } else {
6051 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6052 minAbove = i;
6053 }
6054 }
6055 }
6056 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6057 // TODO Move these assumptions out.
6058 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6059 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6060 // due to approximation by an int32_t of the
6061 // phase increments
6062 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6063 if (minAbove >= 0) {
6064 candidate = mSamplingRates[minAbove];
6065 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6066 if (updatedSamplingRate != NULL) {
6067 *updatedSamplingRate = candidate;
6068 }
6069 return NO_ERROR;
6070 }
6071 }
6072 // But if we have to up-sample from a lower sampling rate, that's OK.
6073 if (maxBelow >= 0) {
6074 candidate = mSamplingRates[maxBelow];
6075 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6076 if (updatedSamplingRate != NULL) {
6077 *updatedSamplingRate = candidate;
6078 }
6079 return NO_ERROR;
6080 }
6081 }
6082 // leave updatedSamplingRate unmodified
6083 return BAD_VALUE;
6084}
6085
6086status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6087{
6088 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006089 if (mChannelMasks[i] == channelMask) {
6090 return NO_ERROR;
6091 }
6092 }
6093 return BAD_VALUE;
6094}
6095
Glenn Kastencbd48022014-07-24 13:46:44 -07006096status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6097 const
6098{
6099 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6100 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6101 // FIXME Does not handle multi-channel automatic conversions yet
6102 audio_channel_mask_t supported = mChannelMasks[i];
6103 if (supported == channelMask) {
6104 return NO_ERROR;
6105 }
6106 if (isRecordThread) {
6107 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6108 // FIXME Abstract this out to a table.
6109 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6110 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6111 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6112 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6113 return NO_ERROR;
6114 }
6115 }
6116 }
6117 return BAD_VALUE;
6118}
6119
Eric Laurenta121f902014-06-03 13:32:54 -07006120status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6121{
6122 for (size_t i = 0; i < mFormats.size(); i ++) {
6123 if (mFormats[i] == format) {
6124 return NO_ERROR;
6125 }
6126 }
6127 return BAD_VALUE;
6128}
6129
Eric Laurent1e693b52014-07-09 15:03:28 -07006130
6131uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6132{
6133 // special case for uninitialized dynamic profile
6134 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6135 return 0;
6136 }
6137
Eric Laurent828bcff2014-09-07 12:26:06 -07006138 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6139 // channel count / sampling rate combination chosen will be supported by the connected
6140 // sink
6141 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6142 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6143 uint32_t samplingRate = UINT_MAX;
6144 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6145 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6146 samplingRate = mSamplingRates[i];
6147 }
6148 }
6149 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6150 }
6151
Eric Laurent1e693b52014-07-09 15:03:28 -07006152 uint32_t samplingRate = 0;
6153 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6154
6155 // For mixed output and inputs, use max mixer sampling rates. Do not
6156 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006157 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006158 maxRate = UINT_MAX;
6159 }
6160 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6161 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6162 samplingRate = mSamplingRates[i];
6163 }
6164 }
6165 return samplingRate;
6166}
6167
6168audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6169{
6170 // special case for uninitialized dynamic profile
6171 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6172 return AUDIO_CHANNEL_NONE;
6173 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006174 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006175
6176 // For direct outputs, pick minimum channel count: this helps ensuring that the
6177 // channel count / sampling rate combination chosen will be supported by the connected
6178 // sink
6179 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6180 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6181 uint32_t channelCount = UINT_MAX;
6182 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6183 uint32_t cnlCount;
6184 if (mUseInChannelMask) {
6185 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6186 } else {
6187 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6188 }
6189 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6190 channelMask = mChannelMasks[i];
6191 channelCount = cnlCount;
6192 }
6193 }
6194 return channelMask;
6195 }
6196
Eric Laurent1e693b52014-07-09 15:03:28 -07006197 uint32_t channelCount = 0;
6198 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6199
6200 // For mixed output and inputs, use max mixer channel count. Do not
6201 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006202 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006203 maxCount = UINT_MAX;
6204 }
6205 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6206 uint32_t cnlCount;
6207 if (mUseInChannelMask) {
6208 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6209 } else {
6210 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6211 }
6212 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6213 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006214 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006215 }
6216 }
6217 return channelMask;
6218}
6219
Andy Hung9a605382014-07-28 16:16:31 -07006220/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006221const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6222 AUDIO_FORMAT_DEFAULT,
6223 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006224 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006225 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006226 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006227 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006228};
6229
6230int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6231 audio_format_t format2)
6232{
6233 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6234 // compressed format and better than any PCM format. This is by design of pickFormat()
6235 if (!audio_is_linear_pcm(format1)) {
6236 if (!audio_is_linear_pcm(format2)) {
6237 return 0;
6238 }
6239 return 1;
6240 }
6241 if (!audio_is_linear_pcm(format2)) {
6242 return -1;
6243 }
6244
6245 int index1 = -1, index2 = -1;
6246 for (size_t i = 0;
6247 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6248 i ++) {
6249 if (sPcmFormatCompareTable[i] == format1) {
6250 index1 = i;
6251 }
6252 if (sPcmFormatCompareTable[i] == format2) {
6253 index2 = i;
6254 }
6255 }
6256 // format1 not found => index1 < 0 => format2 > format1
6257 // format2 not found => index2 < 0 => format2 < format1
6258 return index1 - index2;
6259}
6260
6261audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6262{
6263 // special case for uninitialized dynamic profile
6264 if (mFormats.size() == 1 && mFormats[0] == 0) {
6265 return AUDIO_FORMAT_DEFAULT;
6266 }
6267
6268 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006269 audio_format_t bestFormat =
6270 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6271 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006272 // For mixed output and inputs, use best mixer output format. Do not
6273 // limit format otherwise
6274 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6275 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006276 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006277 bestFormat = AUDIO_FORMAT_INVALID;
6278 }
6279
6280 for (size_t i = 0; i < mFormats.size(); i ++) {
6281 if ((compareFormats(mFormats[i], format) > 0) &&
6282 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6283 format = mFormats[i];
6284 }
6285 }
6286 return format;
6287}
6288
Eric Laurenta121f902014-06-03 13:32:54 -07006289status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6290 int index) const
6291{
6292 if (index < 0 || (size_t)index >= mGains.size()) {
6293 return BAD_VALUE;
6294 }
6295 return mGains[index]->checkConfig(gainConfig);
6296}
6297
Eric Laurent1afeecb2014-05-14 08:52:28 -07006298void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6299{
6300 const size_t SIZE = 256;
6301 char buffer[SIZE];
6302 String8 result;
6303
6304 if (mName.size() != 0) {
6305 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6306 result.append(buffer);
6307 }
6308
6309 if (mSamplingRates.size() != 0) {
6310 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6311 result.append(buffer);
6312 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006313 if (i == 0 && mSamplingRates[i] == 0) {
6314 snprintf(buffer, SIZE, "Dynamic");
6315 } else {
6316 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6317 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006318 result.append(buffer);
6319 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6320 }
6321 result.append("\n");
6322 }
6323
6324 if (mChannelMasks.size() != 0) {
6325 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6326 result.append(buffer);
6327 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006328 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6329
6330 if (i == 0 && mChannelMasks[i] == 0) {
6331 snprintf(buffer, SIZE, "Dynamic");
6332 } else {
6333 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6334 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006335 result.append(buffer);
6336 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6337 }
6338 result.append("\n");
6339 }
6340
6341 if (mFormats.size() != 0) {
6342 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6343 result.append(buffer);
6344 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006345 const char *formatStr = enumToString(sFormatNameToEnumTable,
6346 ARRAY_SIZE(sFormatNameToEnumTable),
6347 mFormats[i]);
6348 if (i == 0 && strcmp(formatStr, "") == 0) {
6349 snprintf(buffer, SIZE, "Dynamic");
6350 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006351 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006352 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006353 result.append(buffer);
6354 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6355 }
6356 result.append("\n");
6357 }
6358 write(fd, result.string(), result.size());
6359 if (mGains.size() != 0) {
6360 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6361 write(fd, buffer, strlen(buffer) + 1);
6362 result.append(buffer);
6363 for (size_t i = 0; i < mGains.size(); i++) {
6364 mGains[i]->dump(fd, spaces + 2, i);
6365 }
6366 }
6367}
6368
6369// --- AudioGain class implementation
6370
Eric Laurenta121f902014-06-03 13:32:54 -07006371AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006372{
Eric Laurenta121f902014-06-03 13:32:54 -07006373 mIndex = index;
6374 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006375 memset(&mGain, 0, sizeof(struct audio_gain));
6376}
6377
Eric Laurenta121f902014-06-03 13:32:54 -07006378void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6379{
6380 config->index = mIndex;
6381 config->mode = mGain.mode;
6382 config->channel_mask = mGain.channel_mask;
6383 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6384 config->values[0] = mGain.default_value;
6385 } else {
6386 uint32_t numValues;
6387 if (mUseInChannelMask) {
6388 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6389 } else {
6390 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6391 }
6392 for (size_t i = 0; i < numValues; i++) {
6393 config->values[i] = mGain.default_value;
6394 }
6395 }
6396 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6397 config->ramp_duration_ms = mGain.min_ramp_ms;
6398 }
6399}
6400
6401status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6402{
6403 if ((config->mode & ~mGain.mode) != 0) {
6404 return BAD_VALUE;
6405 }
6406 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6407 if ((config->values[0] < mGain.min_value) ||
6408 (config->values[0] > mGain.max_value)) {
6409 return BAD_VALUE;
6410 }
6411 } else {
6412 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6413 return BAD_VALUE;
6414 }
6415 uint32_t numValues;
6416 if (mUseInChannelMask) {
6417 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6418 } else {
6419 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6420 }
6421 for (size_t i = 0; i < numValues; i++) {
6422 if ((config->values[i] < mGain.min_value) ||
6423 (config->values[i] > mGain.max_value)) {
6424 return BAD_VALUE;
6425 }
6426 }
6427 }
6428 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6429 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6430 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6431 return BAD_VALUE;
6432 }
6433 }
6434 return NO_ERROR;
6435}
6436
Eric Laurent1afeecb2014-05-14 08:52:28 -07006437void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6438{
6439 const size_t SIZE = 256;
6440 char buffer[SIZE];
6441 String8 result;
6442
6443 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6444 result.append(buffer);
6445 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6446 result.append(buffer);
6447 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6448 result.append(buffer);
6449 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6450 result.append(buffer);
6451 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6452 result.append(buffer);
6453 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6454 result.append(buffer);
6455 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6456 result.append(buffer);
6457 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6458 result.append(buffer);
6459 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6460 result.append(buffer);
6461
6462 write(fd, result.string(), result.size());
6463}
6464
Eric Laurent1f2f2232014-06-02 12:01:23 -07006465// --- AudioPortConfig class implementation
6466
6467AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6468{
6469 mSamplingRate = 0;
6470 mChannelMask = AUDIO_CHANNEL_NONE;
6471 mFormat = AUDIO_FORMAT_INVALID;
6472 mGain.index = -1;
6473}
6474
Eric Laurenta121f902014-06-03 13:32:54 -07006475status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6476 const struct audio_port_config *config,
6477 struct audio_port_config *backupConfig)
6478{
6479 struct audio_port_config localBackupConfig;
6480 status_t status = NO_ERROR;
6481
6482 localBackupConfig.config_mask = config->config_mask;
6483 toAudioPortConfig(&localBackupConfig);
6484
Marco Nelissen961ec212014-08-25 15:58:39 -07006485 sp<AudioPort> audioport = getAudioPort();
6486 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006487 status = NO_INIT;
6488 goto exit;
6489 }
6490 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006491 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006492 if (status != NO_ERROR) {
6493 goto exit;
6494 }
6495 mSamplingRate = config->sample_rate;
6496 }
6497 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006498 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006499 if (status != NO_ERROR) {
6500 goto exit;
6501 }
6502 mChannelMask = config->channel_mask;
6503 }
6504 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006505 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006506 if (status != NO_ERROR) {
6507 goto exit;
6508 }
6509 mFormat = config->format;
6510 }
6511 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006512 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006513 if (status != NO_ERROR) {
6514 goto exit;
6515 }
6516 mGain = config->gain;
6517 }
6518
6519exit:
6520 if (status != NO_ERROR) {
6521 applyAudioPortConfig(&localBackupConfig);
6522 }
6523 if (backupConfig != NULL) {
6524 *backupConfig = localBackupConfig;
6525 }
6526 return status;
6527}
6528
Eric Laurent1f2f2232014-06-02 12:01:23 -07006529void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6530 struct audio_port_config *dstConfig,
6531 const struct audio_port_config *srcConfig) const
6532{
6533 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6534 dstConfig->sample_rate = mSamplingRate;
6535 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6536 dstConfig->sample_rate = srcConfig->sample_rate;
6537 }
6538 } else {
6539 dstConfig->sample_rate = 0;
6540 }
6541 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6542 dstConfig->channel_mask = mChannelMask;
6543 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6544 dstConfig->channel_mask = srcConfig->channel_mask;
6545 }
6546 } else {
6547 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6548 }
6549 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6550 dstConfig->format = mFormat;
6551 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6552 dstConfig->format = srcConfig->format;
6553 }
6554 } else {
6555 dstConfig->format = AUDIO_FORMAT_INVALID;
6556 }
6557 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6558 dstConfig->gain = mGain;
6559 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6560 dstConfig->gain = srcConfig->gain;
6561 }
6562 } else {
6563 dstConfig->gain.index = -1;
6564 }
6565 if (dstConfig->gain.index != -1) {
6566 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6567 } else {
6568 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6569 }
6570}
6571
Eric Laurent1c333e22014-05-20 10:48:17 -07006572// --- IOProfile class implementation
6573
Eric Laurent1afeecb2014-05-14 08:52:28 -07006574AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006575 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006576 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006577{
6578}
6579
Eric Laurente0720872014-03-11 09:30:41 -07006580AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006581{
6582}
6583
6584// checks if the IO profile is compatible with specified parameters.
6585// Sampling rate, format and channel mask must be specified in order to
6586// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006587bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006588 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006589 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006590 audio_format_t format,
6591 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006592 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006593{
Glenn Kastencbd48022014-07-24 13:46:44 -07006594 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6595 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6596 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006597
Glenn Kastencbd48022014-07-24 13:46:44 -07006598 if ((mSupportedDevices.types() & device) != device) {
6599 return false;
6600 }
6601
6602 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006603 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006604 }
6605 uint32_t myUpdatedSamplingRate = samplingRate;
6606 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006607 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006608 }
6609 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6610 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006611 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006612 }
6613
6614 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6615 return false;
6616 }
6617
6618 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6619 checkExactChannelMask(channelMask) != NO_ERROR)) {
6620 return false;
6621 }
6622 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6623 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6624 return false;
6625 }
6626
6627 if (isPlaybackThread && (mFlags & flags) != flags) {
6628 return false;
6629 }
6630 // The only input flag that is allowed to be different is the fast flag.
6631 // An existing fast stream is compatible with a normal track request.
6632 // An existing normal stream is compatible with a fast track request,
6633 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006634 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006635 ~AUDIO_INPUT_FLAG_FAST)) {
6636 return false;
6637 }
6638
6639 if (updatedSamplingRate != NULL) {
6640 *updatedSamplingRate = myUpdatedSamplingRate;
6641 }
6642 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006643}
6644
Eric Laurente0720872014-03-11 09:30:41 -07006645void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006646{
6647 const size_t SIZE = 256;
6648 char buffer[SIZE];
6649 String8 result;
6650
Eric Laurent1afeecb2014-05-14 08:52:28 -07006651 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006652
Eric Laurente552edb2014-03-10 17:42:56 -07006653 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6654 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006655 snprintf(buffer, SIZE, " - devices:\n");
6656 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006657 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006658 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6659 mSupportedDevices[i]->dump(fd, 6, i);
6660 }
Eric Laurente552edb2014-03-10 17:42:56 -07006661}
6662
Eric Laurentd4692962014-05-05 18:13:44 -07006663void AudioPolicyManager::IOProfile::log()
6664{
6665 const size_t SIZE = 256;
6666 char buffer[SIZE];
6667 String8 result;
6668
6669 ALOGV(" - sampling rates: ");
6670 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6671 ALOGV(" %d", mSamplingRates[i]);
6672 }
6673
6674 ALOGV(" - channel masks: ");
6675 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6676 ALOGV(" 0x%04x", mChannelMasks[i]);
6677 }
6678
6679 ALOGV(" - formats: ");
6680 for (size_t i = 0; i < mFormats.size(); i++) {
6681 ALOGV(" 0x%08x", mFormats[i]);
6682 }
6683
6684 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6685 ALOGV(" - flags: 0x%04x\n", mFlags);
6686}
6687
6688
Eric Laurent3a4311c2014-03-17 12:00:47 -07006689// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006690
Eric Laurent1f2f2232014-06-02 12:01:23 -07006691
6692AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6693 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6694 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6695 AUDIO_PORT_ROLE_SOURCE,
6696 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006697 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006698{
Eric Laurenta121f902014-06-03 13:32:54 -07006699 if (mGains.size() > 0) {
6700 mGains[0]->getDefaultConfig(&mGain);
6701 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006702}
6703
Eric Laurent3a4311c2014-03-17 12:00:47 -07006704bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006705{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006706 // Devices are considered equal if they:
6707 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6708 // - have the same address or one device does not specify the address
6709 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006710 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006711 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006712 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006713 mChannelMask == other->mChannelMask);
6714}
6715
6716void AudioPolicyManager::DeviceVector::refreshTypes()
6717{
Eric Laurent1c333e22014-05-20 10:48:17 -07006718 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006719 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006720 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006721 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006722 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006723}
6724
6725ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6726{
6727 for(size_t i = 0; i < size(); i++) {
6728 if (item->equals(itemAt(i))) {
6729 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006730 }
6731 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006732 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006733}
6734
Eric Laurent3a4311c2014-03-17 12:00:47 -07006735ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006736{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006737 ssize_t ret = indexOf(item);
6738
6739 if (ret < 0) {
6740 ret = SortedVector::add(item);
6741 if (ret >= 0) {
6742 refreshTypes();
6743 }
6744 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006745 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006746 ret = -1;
6747 }
6748 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006749}
6750
Eric Laurent3a4311c2014-03-17 12:00:47 -07006751ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6752{
6753 size_t i;
6754 ssize_t ret = indexOf(item);
6755
6756 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006757 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006758 } else {
6759 ret = SortedVector::removeAt(ret);
6760 if (ret >= 0) {
6761 refreshTypes();
6762 }
6763 }
6764 return ret;
6765}
6766
6767void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6768{
6769 DeviceVector deviceList;
6770
6771 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6772 types &= ~role_bit;
6773
6774 while (types) {
6775 uint32_t i = 31 - __builtin_clz(types);
6776 uint32_t type = 1 << i;
6777 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006778 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006779 }
6780}
6781
Eric Laurent1afeecb2014-05-14 08:52:28 -07006782void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6783 const DeviceVector& declaredDevices)
6784{
6785 char *devName = strtok(name, "|");
6786 while (devName != NULL) {
6787 if (strlen(devName) != 0) {
6788 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6789 ARRAY_SIZE(sDeviceNameToEnumTable),
6790 devName);
6791 if (type != AUDIO_DEVICE_NONE) {
6792 add(new DeviceDescriptor(String8(""), type));
6793 } else {
6794 sp<DeviceDescriptor> deviceDesc =
6795 declaredDevices.getDeviceFromName(String8(devName));
6796 if (deviceDesc != 0) {
6797 add(deviceDesc);
6798 }
6799 }
6800 }
6801 devName = strtok(NULL, "|");
6802 }
6803}
6804
Eric Laurent1c333e22014-05-20 10:48:17 -07006805sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6806 audio_devices_t type, String8 address) const
6807{
6808 sp<DeviceDescriptor> device;
6809 for (size_t i = 0; i < size(); i++) {
6810 if (itemAt(i)->mDeviceType == type) {
6811 device = itemAt(i);
6812 if (itemAt(i)->mAddress = address) {
6813 break;
6814 }
6815 }
6816 }
6817 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6818 type, address.string(), device.get());
6819 return device;
6820}
6821
Eric Laurent6a94d692014-05-20 11:18:06 -07006822sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6823 audio_port_handle_t id) const
6824{
6825 sp<DeviceDescriptor> device;
6826 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006827 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006828 if (itemAt(i)->mId == id) {
6829 device = itemAt(i);
6830 break;
6831 }
6832 }
6833 return device;
6834}
6835
Eric Laurent1c333e22014-05-20 10:48:17 -07006836AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6837 audio_devices_t type) const
6838{
6839 DeviceVector devices;
6840 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6841 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6842 devices.add(itemAt(i));
6843 type &= ~itemAt(i)->mDeviceType;
6844 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6845 itemAt(i)->mDeviceType, itemAt(i).get());
6846 }
6847 }
6848 return devices;
6849}
6850
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006851AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6852 audio_devices_t type, String8 address) const
6853{
6854 DeviceVector devices;
6855 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6856 for (size_t i = 0; i < size(); i++) {
6857 //ALOGV(" at i=%d: device=%x, addr=%s",
6858 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6859 if (itemAt(i)->mDeviceType == type) {
6860 if (itemAt(i)->mAddress == address) {
6861 //ALOGV(" found matching address %s", address.string());
6862 devices.add(itemAt(i));
6863 }
6864 }
6865 }
6866 return devices;
6867}
6868
Eric Laurent1afeecb2014-05-14 08:52:28 -07006869sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6870 const String8& name) const
6871{
6872 sp<DeviceDescriptor> device;
6873 for (size_t i = 0; i < size(); i++) {
6874 if (itemAt(i)->mName == name) {
6875 device = itemAt(i);
6876 break;
6877 }
6878 }
6879 return device;
6880}
6881
Eric Laurent6a94d692014-05-20 11:18:06 -07006882void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6883 struct audio_port_config *dstConfig,
6884 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006885{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006886 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6887 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006888 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006889 }
6890
6891 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6892
Eric Laurent6a94d692014-05-20 11:18:06 -07006893 dstConfig->id = mId;
6894 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006895 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006896 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006897 dstConfig->ext.device.type = mDeviceType;
6898 dstConfig->ext.device.hw_module = mModule->mHandle;
6899 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006900}
6901
6902void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6903{
Eric Laurent83b88082014-06-20 18:31:16 -07006904 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006905 AudioPort::toAudioPort(port);
6906 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006907 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006908 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006909 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006910 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6911}
6912
Eric Laurent1afeecb2014-05-14 08:52:28 -07006913status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006914{
6915 const size_t SIZE = 256;
6916 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006917 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006918
Eric Laurent1afeecb2014-05-14 08:52:28 -07006919 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6920 result.append(buffer);
6921 if (mId != 0) {
6922 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6923 result.append(buffer);
6924 }
6925 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6926 enumToString(sDeviceNameToEnumTable,
6927 ARRAY_SIZE(sDeviceNameToEnumTable),
6928 mDeviceType));
6929 result.append(buffer);
6930 if (mAddress.size() != 0) {
6931 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6932 result.append(buffer);
6933 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006934 write(fd, result.string(), result.size());
6935 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006936
6937 return NO_ERROR;
6938}
6939
Eric Laurent4d416952014-08-10 14:07:09 -07006940status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6941{
6942 const size_t SIZE = 256;
6943 char buffer[SIZE];
6944 String8 result;
6945
6946
6947 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6948 result.append(buffer);
6949 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6950 result.append(buffer);
6951 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6952 result.append(buffer);
6953 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6954 result.append(buffer);
6955 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6956 result.append(buffer);
6957 for (size_t i = 0; i < mPatch.num_sources; i++) {
6958 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6959 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6960 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6961 ARRAY_SIZE(sDeviceNameToEnumTable),
6962 mPatch.sources[i].ext.device.type));
6963 } else {
6964 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6965 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6966 }
6967 result.append(buffer);
6968 }
6969 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6970 result.append(buffer);
6971 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6972 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
6973 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6974 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
6975 ARRAY_SIZE(sDeviceNameToEnumTable),
6976 mPatch.sinks[i].ext.device.type));
6977 } else {
6978 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6979 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
6980 }
6981 result.append(buffer);
6982 }
6983
6984 write(fd, result.string(), result.size());
6985 return NO_ERROR;
6986}
Eric Laurent3a4311c2014-03-17 12:00:47 -07006987
6988// --- audio_policy.conf file parsing
6989
Eric Laurent5dbe4712014-09-19 19:04:57 -07006990uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006991{
6992 uint32_t flag = 0;
6993
6994 // it is OK to cast name to non const here as we are not going to use it after
6995 // strtok() modifies it
6996 char *flagName = strtok(name, "|");
6997 while (flagName != NULL) {
6998 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006999 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7000 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007001 flagName);
7002 }
7003 flagName = strtok(NULL, "|");
7004 }
7005 //force direct flag if offload flag is set: offloading implies a direct output stream
7006 // and all common behaviors are driven by checking only the direct flag
7007 // this should normally be set appropriately in the policy configuration file
7008 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7009 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7010 }
7011
Eric Laurent5dbe4712014-09-19 19:04:57 -07007012 return flag;
7013}
7014
7015uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7016{
7017 uint32_t flag = 0;
7018
7019 // it is OK to cast name to non const here as we are not going to use it after
7020 // strtok() modifies it
7021 char *flagName = strtok(name, "|");
7022 while (flagName != NULL) {
7023 if (strlen(flagName) != 0) {
7024 flag |= stringToEnum(sInputFlagNameToEnumTable,
7025 ARRAY_SIZE(sInputFlagNameToEnumTable),
7026 flagName);
7027 }
7028 flagName = strtok(NULL, "|");
7029 }
7030 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007031}
7032
Eric Laurente0720872014-03-11 09:30:41 -07007033audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007034{
7035 uint32_t device = 0;
7036
7037 char *devName = strtok(name, "|");
7038 while (devName != NULL) {
7039 if (strlen(devName) != 0) {
7040 device |= stringToEnum(sDeviceNameToEnumTable,
7041 ARRAY_SIZE(sDeviceNameToEnumTable),
7042 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007043 }
Eric Laurente552edb2014-03-10 17:42:56 -07007044 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007045 }
Eric Laurente552edb2014-03-10 17:42:56 -07007046 return device;
7047}
7048
Eric Laurente0720872014-03-11 09:30:41 -07007049void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007050{
Eric Laurente552edb2014-03-10 17:42:56 -07007051 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007052 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007053 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007054
Eric Laurent1afeecb2014-05-14 08:52:28 -07007055 node = config_find(root, DEVICES_TAG);
7056 if (node != NULL) {
7057 node = node->first_child;
7058 while (node) {
7059 ALOGV("loadHwModule() loading device %s", node->name);
7060 status_t tmpStatus = module->loadDevice(node);
7061 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7062 status = tmpStatus;
7063 }
7064 node = node->next;
7065 }
7066 }
7067 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007068 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007069 node = node->first_child;
7070 while (node) {
7071 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007072 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007073 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7074 status = tmpStatus;
7075 }
7076 node = node->next;
7077 }
7078 }
7079 node = config_find(root, INPUTS_TAG);
7080 if (node != NULL) {
7081 node = node->first_child;
7082 while (node) {
7083 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007084 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007085 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7086 status = tmpStatus;
7087 }
7088 node = node->next;
7089 }
7090 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007091 loadGlobalConfig(root, module);
7092
Eric Laurente552edb2014-03-10 17:42:56 -07007093 if (status == NO_ERROR) {
7094 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007095 }
7096}
7097
Eric Laurente0720872014-03-11 09:30:41 -07007098void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007099{
7100 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7101 if (node == NULL) {
7102 return;
7103 }
7104
7105 node = node->first_child;
7106 while (node) {
7107 ALOGV("loadHwModules() loading module %s", node->name);
7108 loadHwModule(node);
7109 node = node->next;
7110 }
7111}
7112
Eric Laurent1f2f2232014-06-02 12:01:23 -07007113void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007114{
7115 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007116
Eric Laurente552edb2014-03-10 17:42:56 -07007117 if (node == NULL) {
7118 return;
7119 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007120 DeviceVector declaredDevices;
7121 if (module != NULL) {
7122 declaredDevices = module->mDeclaredDevices;
7123 }
7124
Eric Laurente552edb2014-03-10 17:42:56 -07007125 node = node->first_child;
7126 while (node) {
7127 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007128 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7129 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007130 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7131 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007132 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007133 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007134 ARRAY_SIZE(sDeviceNameToEnumTable),
7135 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007136 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007137 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007138 } else {
7139 ALOGW("loadGlobalConfig() default device not specified");
7140 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007141 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007142 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007143 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7144 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007145 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007146 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7147 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7148 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007149 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7150 uint32_t major, minor;
7151 sscanf((char *)node->value, "%u.%u", &major, &minor);
7152 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7153 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7154 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007155 }
7156 node = node->next;
7157 }
7158}
7159
Eric Laurente0720872014-03-11 09:30:41 -07007160status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007161{
7162 cnode *root;
7163 char *data;
7164
7165 data = (char *)load_file(path, NULL);
7166 if (data == NULL) {
7167 return -ENODEV;
7168 }
7169 root = config_node("", "");
7170 config_load(root, data);
7171
Eric Laurente552edb2014-03-10 17:42:56 -07007172 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007173 // legacy audio_policy.conf files have one global_configuration section
7174 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007175 config_free(root);
7176 free(root);
7177 free(data);
7178
7179 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7180
7181 return NO_ERROR;
7182}
7183
Eric Laurente0720872014-03-11 09:30:41 -07007184void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007185{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007186 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007187 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007188 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7189 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007190 mAvailableOutputDevices.add(mDefaultOutputDevice);
7191 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007192
7193 module = new HwModule("primary");
7194
Eric Laurent1afeecb2014-05-14 08:52:28 -07007195 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007196 profile->mSamplingRates.add(44100);
7197 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7198 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007199 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007200 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7201 module->mOutputProfiles.add(profile);
7202
Eric Laurent1afeecb2014-05-14 08:52:28 -07007203 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007204 profile->mSamplingRates.add(8000);
7205 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7206 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007207 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007208 module->mInputProfiles.add(profile);
7209
7210 mHwModules.add(module);
7211}
7212
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007213audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7214{
7215 // flags to stream type mapping
7216 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7217 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7218 }
7219 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7220 return AUDIO_STREAM_BLUETOOTH_SCO;
7221 }
7222
7223 // usage to stream type mapping
7224 switch (attr->usage) {
7225 case AUDIO_USAGE_MEDIA:
7226 case AUDIO_USAGE_GAME:
7227 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7228 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7229 return AUDIO_STREAM_MUSIC;
7230 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7231 return AUDIO_STREAM_SYSTEM;
7232 case AUDIO_USAGE_VOICE_COMMUNICATION:
7233 return AUDIO_STREAM_VOICE_CALL;
7234
7235 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7236 return AUDIO_STREAM_DTMF;
7237
7238 case AUDIO_USAGE_ALARM:
7239 return AUDIO_STREAM_ALARM;
7240 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7241 return AUDIO_STREAM_RING;
7242
7243 case AUDIO_USAGE_NOTIFICATION:
7244 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7245 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7246 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7247 case AUDIO_USAGE_NOTIFICATION_EVENT:
7248 return AUDIO_STREAM_NOTIFICATION;
7249
7250 case AUDIO_USAGE_UNKNOWN:
7251 default:
7252 return AUDIO_STREAM_MUSIC;
7253 }
7254}
Eric Laurente552edb2014-03-10 17:42:56 -07007255}; // namespace android