blob: d51ee8e2eb41373f3ec4716098d586f241e721b9 [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
930 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
931 // creating an offloaded track and tearing it down immediately after start when audioflinger
932 // detects there is an active non offloadable effect.
933 // FIXME: We should check the audio session here but we do not have it in this context.
934 // This may prevent offloading in rare situations where effects are left active by apps
935 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700936 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700937 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
938 !isNonOffloadableEffectEnabled()) {
939 profile = getProfileForDirectOutput(device,
940 samplingRate,
941 format,
942 channelMask,
943 (audio_output_flags_t)flags);
944 }
945
Eric Laurent1c333e22014-05-20 10:48:17 -0700946 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700947 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700948
949 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700950 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700951 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
952 outputDesc = desc;
953 // reuse direct output if currently open and configured with same parameters
954 if ((samplingRate == outputDesc->mSamplingRate) &&
955 (format == outputDesc->mFormat) &&
956 (channelMask == outputDesc->mChannelMask)) {
957 outputDesc->mDirectOpenCount++;
958 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
959 return mOutputs.keyAt(i);
960 }
961 }
962 }
963 // close direct output if currently open and configured with different parameters
964 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700965 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700966 }
967 outputDesc = new AudioOutputDescriptor(profile);
968 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700969 outputDesc->mLatency = 0;
970 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700971 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
972 config.sample_rate = samplingRate;
973 config.channel_mask = channelMask;
974 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700975 if (offloadInfo != NULL) {
976 config.offload_info = *offloadInfo;
977 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700978 status = mpClientInterface->openOutput(profile->mModule->mHandle,
979 &output,
980 &config,
981 &outputDesc->mDevice,
982 String8(""),
983 &outputDesc->mLatency,
984 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700985
986 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700987 if (status != NO_ERROR ||
988 (samplingRate != 0 && samplingRate != config.sample_rate) ||
989 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
990 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700991 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
992 "format %d %d, channelMask %04x %04x", output, samplingRate,
993 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
994 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700995 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700996 mpClientInterface->closeOutput(output);
997 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700998 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700999 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001000 outputDesc->mSamplingRate = config.sample_rate;
1001 outputDesc->mChannelMask = config.channel_mask;
1002 outputDesc->mFormat = config.format;
1003 outputDesc->mRefCount[stream] = 0;
1004 outputDesc->mStopTime[stream] = 0;
1005 outputDesc->mDirectOpenCount = 1;
1006
Eric Laurente552edb2014-03-10 17:42:56 -07001007 audio_io_handle_t srcOutput = getOutputForEffect();
1008 addOutput(output, outputDesc);
1009 audio_io_handle_t dstOutput = getOutputForEffect();
1010 if (dstOutput == output) {
1011 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1012 }
1013 mPreviousOutputs = mOutputs;
1014 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001015 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001016 return output;
1017 }
1018
1019 // ignoring channel mask due to downmix capability in mixer
1020
1021 // open a non direct output
1022
1023 // for non direct outputs, only PCM is supported
1024 if (audio_is_linear_pcm(format)) {
1025 // get which output is suitable for the specified stream. The actual
1026 // routing change will happen when startOutput() will be called
1027 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1028
Eric Laurent8838a382014-09-08 16:44:28 -07001029 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1030 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1031 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001032 }
1033 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1034 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1035
1036 ALOGV("getOutput() returns output %d", output);
1037
1038 return output;
1039}
1040
Eric Laurente0720872014-03-11 09:30:41 -07001041audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001042 audio_output_flags_t flags,
1043 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001044{
1045 // select one output among several that provide a path to a particular device or set of
1046 // devices (the list was previously build by getOutputsForDevice()).
1047 // The priority is as follows:
1048 // 1: the output with the highest number of requested policy flags
1049 // 2: the primary output
1050 // 3: the first output in the list
1051
1052 if (outputs.size() == 0) {
1053 return 0;
1054 }
1055 if (outputs.size() == 1) {
1056 return outputs[0];
1057 }
1058
1059 int maxCommonFlags = 0;
1060 audio_io_handle_t outputFlags = 0;
1061 audio_io_handle_t outputPrimary = 0;
1062
1063 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001064 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001065 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001066 // if a valid format is specified, skip output if not compatible
1067 if (format != AUDIO_FORMAT_INVALID) {
1068 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1069 if (format != outputDesc->mFormat) {
1070 continue;
1071 }
1072 } else if (!audio_is_linear_pcm(format)) {
1073 continue;
1074 }
1075 }
1076
Eric Laurent3b73df72014-03-11 09:06:29 -07001077 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001078 if (commonFlags > maxCommonFlags) {
1079 outputFlags = outputs[i];
1080 maxCommonFlags = commonFlags;
1081 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1082 }
1083 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1084 outputPrimary = outputs[i];
1085 }
1086 }
1087 }
1088
1089 if (outputFlags != 0) {
1090 return outputFlags;
1091 }
1092 if (outputPrimary != 0) {
1093 return outputPrimary;
1094 }
1095
1096 return outputs[0];
1097}
1098
Eric Laurente0720872014-03-11 09:30:41 -07001099status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001100 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001101 int session)
1102{
1103 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1104 ssize_t index = mOutputs.indexOfKey(output);
1105 if (index < 0) {
1106 ALOGW("startOutput() unknown output %d", output);
1107 return BAD_VALUE;
1108 }
1109
Eric Laurent1f2f2232014-06-02 12:01:23 -07001110 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001111
1112 // increment usage count for this stream on the requested output:
1113 // NOTE that the usage count is the same for duplicated output and hardware output which is
1114 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1115 outputDesc->changeRefCount(stream, 1);
1116
1117 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001118 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001119 routing_strategy strategy = getStrategy(stream);
1120 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1121 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1122 uint32_t waitMs = 0;
1123 bool force = false;
1124 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001125 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001126 if (desc != outputDesc) {
1127 // force a device change if any other output is managed by the same hw
1128 // module and has a current device selection that differs from selected device.
1129 // In this case, the audio HAL must receive the new device selection so that it can
1130 // change the device currently selected by the other active output.
1131 if (outputDesc->sharesHwModuleWith(desc) &&
1132 desc->device() != newDevice) {
1133 force = true;
1134 }
1135 // wait for audio on other active outputs to be presented when starting
1136 // a notification so that audio focus effect can propagate.
1137 uint32_t latency = desc->latency();
1138 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1139 waitMs = latency;
1140 }
1141 }
1142 }
1143 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1144
1145 // handle special case for sonification while in call
1146 if (isInCall()) {
1147 handleIncallSonification(stream, true, false);
1148 }
1149
1150 // apply volume rules for current stream and device if necessary
1151 checkAndSetVolume(stream,
1152 mStreams[stream].getVolumeIndex(newDevice),
1153 output,
1154 newDevice);
1155
1156 // update the outputs if starting an output with a stream that can affect notification
1157 // routing
1158 handleNotificationRoutingForStream(stream);
1159 if (waitMs > muteWaitMs) {
1160 usleep((waitMs - muteWaitMs) * 2 * 1000);
1161 }
1162 }
1163 return NO_ERROR;
1164}
1165
1166
Eric Laurente0720872014-03-11 09:30:41 -07001167status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001168 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001169 int session)
1170{
1171 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1172 ssize_t index = mOutputs.indexOfKey(output);
1173 if (index < 0) {
1174 ALOGW("stopOutput() unknown output %d", output);
1175 return BAD_VALUE;
1176 }
1177
Eric Laurent1f2f2232014-06-02 12:01:23 -07001178 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001179
1180 // handle special case for sonification while in call
1181 if (isInCall()) {
1182 handleIncallSonification(stream, false, false);
1183 }
1184
1185 if (outputDesc->mRefCount[stream] > 0) {
1186 // decrement usage count of this stream on the output
1187 outputDesc->changeRefCount(stream, -1);
1188 // store time at which the stream was stopped - see isStreamActive()
1189 if (outputDesc->mRefCount[stream] == 0) {
1190 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001191 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001192 // delay the device switch by twice the latency because stopOutput() is executed when
1193 // the track stop() command is received and at that time the audio track buffer can
1194 // still contain data that needs to be drained. The latency only covers the audio HAL
1195 // and kernel buffers. Also the latency does not always include additional delay in the
1196 // audio path (audio DSP, CODEC ...)
1197 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1198
1199 // force restoring the device selection on other active outputs if it differs from the
1200 // one being selected for this output
1201 for (size_t i = 0; i < mOutputs.size(); i++) {
1202 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001203 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001204 if (curOutput != output &&
1205 desc->isActive() &&
1206 outputDesc->sharesHwModuleWith(desc) &&
1207 (newDevice != desc->device())) {
1208 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001209 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001210 true,
1211 outputDesc->mLatency*2);
1212 }
1213 }
1214 // update the outputs if stopping one with a stream that can affect notification routing
1215 handleNotificationRoutingForStream(stream);
1216 }
1217 return NO_ERROR;
1218 } else {
1219 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1220 return INVALID_OPERATION;
1221 }
1222}
1223
Eric Laurente0720872014-03-11 09:30:41 -07001224void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001225{
1226 ALOGV("releaseOutput() %d", output);
1227 ssize_t index = mOutputs.indexOfKey(output);
1228 if (index < 0) {
1229 ALOGW("releaseOutput() releasing unknown output %d", output);
1230 return;
1231 }
1232
1233#ifdef AUDIO_POLICY_TEST
1234 int testIndex = testOutputIndex(output);
1235 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001236 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001237 if (outputDesc->isActive()) {
1238 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001239 mOutputs.removeItem(output);
1240 mTestOutputs[testIndex] = 0;
1241 }
1242 return;
1243 }
1244#endif //AUDIO_POLICY_TEST
1245
Eric Laurent1f2f2232014-06-02 12:01:23 -07001246 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001247 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001248 if (desc->mDirectOpenCount <= 0) {
1249 ALOGW("releaseOutput() invalid open count %d for output %d",
1250 desc->mDirectOpenCount, output);
1251 return;
1252 }
1253 if (--desc->mDirectOpenCount == 0) {
1254 closeOutput(output);
1255 // If effects where present on the output, audioflinger moved them to the primary
1256 // output by default: move them back to the appropriate output.
1257 audio_io_handle_t dstOutput = getOutputForEffect();
1258 if (dstOutput != mPrimaryOutput) {
1259 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1260 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001261 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001262 }
1263 }
1264}
1265
1266
Eric Laurente0720872014-03-11 09:30:41 -07001267audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001268 uint32_t samplingRate,
1269 audio_format_t format,
1270 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001271 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001272 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001273{
Eric Laurent4dc68062014-07-28 17:26:49 -07001274 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001275 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001276 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001277
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001278 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001279
1280 if (device == AUDIO_DEVICE_NONE) {
1281 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001282 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001283 }
1284
1285 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001286 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001287 case AUDIO_SOURCE_VOICE_UPLINK:
1288 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1289 break;
1290 case AUDIO_SOURCE_VOICE_DOWNLINK:
1291 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1292 break;
1293 case AUDIO_SOURCE_VOICE_CALL:
1294 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1295 break;
1296 default:
1297 break;
1298 }
1299
Eric Laurent5dbe4712014-09-19 19:04:57 -07001300 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1301 bool isSoundTrigger = false;
1302 audio_source_t halInputSource = inputSource;
1303 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1304 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1305 if (index >= 0) {
1306 input = mSoundTriggerSessions.valueFor(session);
1307 isSoundTrigger = true;
1308 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1309 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1310 } else {
1311 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1312 }
1313 }
1314
Eric Laurent1c333e22014-05-20 10:48:17 -07001315 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001316 samplingRate,
1317 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001318 channelMask,
1319 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001320 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001321 //retry without flags
1322 audio_input_flags_t log_flags = flags;
1323 flags = AUDIO_INPUT_FLAG_NONE;
1324 profile = getInputProfile(device,
1325 samplingRate,
1326 format,
1327 channelMask,
1328 flags);
1329 if (profile == 0) {
1330 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1331 "channelMask 0x%X, flags %#x",
1332 device, samplingRate, format, channelMask, log_flags);
1333 return AUDIO_IO_HANDLE_NONE;
1334 }
Eric Laurente552edb2014-03-10 17:42:56 -07001335 }
1336
1337 if (profile->mModule->mHandle == 0) {
1338 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001339 return AUDIO_IO_HANDLE_NONE;
1340 }
1341
1342 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1343 config.sample_rate = samplingRate;
1344 config.channel_mask = channelMask;
1345 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001346
Eric Laurentcf2c0212014-07-25 16:20:43 -07001347 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1348 &input,
1349 &config,
1350 &device,
1351 String8(""),
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001352 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001353 flags);
1354
1355 // only accept input with the exact requested set of parameters
1356 if (status != NO_ERROR ||
1357 (samplingRate != config.sample_rate) ||
1358 (format != config.format) ||
1359 (channelMask != config.channel_mask)) {
1360 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1361 samplingRate, format, channelMask);
1362 if (input != AUDIO_IO_HANDLE_NONE) {
1363 mpClientInterface->closeInput(input);
1364 }
1365 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001366 }
1367
Eric Laurent1f2f2232014-06-02 12:01:23 -07001368 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001369 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001370 inputDesc->mRefCount = 0;
1371 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001372 inputDesc->mSamplingRate = samplingRate;
1373 inputDesc->mFormat = format;
1374 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001375 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001376 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001377 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001378
Eric Laurentd4692962014-05-05 18:13:44 -07001379 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001380 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001381 return input;
1382}
1383
Eric Laurent4dc68062014-07-28 17:26:49 -07001384status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1385 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001386{
1387 ALOGV("startInput() input %d", input);
1388 ssize_t index = mInputs.indexOfKey(input);
1389 if (index < 0) {
1390 ALOGW("startInput() unknown input %d", input);
1391 return BAD_VALUE;
1392 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001393 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001394
Eric Laurent4dc68062014-07-28 17:26:49 -07001395 index = inputDesc->mSessions.indexOf(session);
1396 if (index < 0) {
1397 ALOGW("startInput() unknown session %d on input %d", session, input);
1398 return BAD_VALUE;
1399 }
1400
Glenn Kasten74a8e252014-07-24 14:09:55 -07001401 // virtual input devices are compatible with other input devices
1402 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1403
1404 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001405 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001406 if (activeInput != 0 && activeInput != input) {
1407
1408 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1409 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001410 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001411 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001412 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001413 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1414 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001415 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001416 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001417 return INVALID_OPERATION;
1418 }
1419 }
1420 }
1421
Glenn Kasten74a8e252014-07-24 14:09:55 -07001422 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001423 if (activeInputsCount() == 0) {
1424 SoundTrigger::setCaptureState(true);
1425 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001426 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001427
Glenn Kasten74a8e252014-07-24 14:09:55 -07001428 // Automatically enable the remote submix output when input is started.
1429 // For remote submix (a virtual device), we open only one input per capture request.
1430 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1431 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1432 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1433 }
Eric Laurente552edb2014-03-10 17:42:56 -07001434 }
1435
Eric Laurente552edb2014-03-10 17:42:56 -07001436 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1437
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001438 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001439 return NO_ERROR;
1440}
1441
Eric Laurent4dc68062014-07-28 17:26:49 -07001442status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1443 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001444{
1445 ALOGV("stopInput() input %d", input);
1446 ssize_t index = mInputs.indexOfKey(input);
1447 if (index < 0) {
1448 ALOGW("stopInput() unknown input %d", input);
1449 return BAD_VALUE;
1450 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001451 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001452
Eric Laurent4dc68062014-07-28 17:26:49 -07001453 index = inputDesc->mSessions.indexOf(session);
1454 if (index < 0) {
1455 ALOGW("stopInput() unknown session %d on input %d", session, input);
1456 return BAD_VALUE;
1457 }
1458
Eric Laurente552edb2014-03-10 17:42:56 -07001459 if (inputDesc->mRefCount == 0) {
1460 ALOGW("stopInput() input %d already stopped", input);
1461 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001462 }
1463
1464 inputDesc->mRefCount--;
1465 if (inputDesc->mRefCount == 0) {
1466
Eric Laurente552edb2014-03-10 17:42:56 -07001467 // automatically disable the remote submix output when input is stopped
1468 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1469 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001470 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001471 }
1472
Eric Laurent1c333e22014-05-20 10:48:17 -07001473 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001474
1475 if (activeInputsCount() == 0) {
1476 SoundTrigger::setCaptureState(false);
1477 }
Eric Laurente552edb2014-03-10 17:42:56 -07001478 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001479 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001480}
1481
Eric Laurent4dc68062014-07-28 17:26:49 -07001482void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1483 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001484{
1485 ALOGV("releaseInput() %d", input);
1486 ssize_t index = mInputs.indexOfKey(input);
1487 if (index < 0) {
1488 ALOGW("releaseInput() releasing unknown input %d", input);
1489 return;
1490 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001491 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1492 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001493
1494 index = inputDesc->mSessions.indexOf(session);
1495 if (index < 0) {
1496 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1497 return;
1498 }
1499 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001500 if (inputDesc->mOpenRefCount == 0) {
1501 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1502 return;
1503 }
1504 inputDesc->mOpenRefCount--;
1505 if (inputDesc->mOpenRefCount > 0) {
1506 ALOGV("releaseInput() exit > 0");
1507 return;
1508 }
1509
Eric Laurent05b90f82014-08-27 15:32:29 -07001510 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001511 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001512 ALOGV("releaseInput() exit");
1513}
1514
Eric Laurentd4692962014-05-05 18:13:44 -07001515void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001516 bool patchRemoved = false;
1517
Eric Laurentd4692962014-05-05 18:13:44 -07001518 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001519 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1520 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1521 if (patch_index >= 0) {
1522 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1523 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1524 mAudioPatches.removeItemsAt(patch_index);
1525 patchRemoved = true;
1526 }
Eric Laurentd4692962014-05-05 18:13:44 -07001527 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1528 }
1529 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001530 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001531
1532 if (patchRemoved) {
1533 mpClientInterface->onAudioPatchListUpdate();
1534 }
Eric Laurentd4692962014-05-05 18:13:44 -07001535}
1536
Eric Laurente0720872014-03-11 09:30:41 -07001537void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001538 int indexMin,
1539 int indexMax)
1540{
1541 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1542 if (indexMin < 0 || indexMin >= indexMax) {
1543 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1544 return;
1545 }
1546 mStreams[stream].mIndexMin = indexMin;
1547 mStreams[stream].mIndexMax = indexMax;
1548}
1549
Eric Laurente0720872014-03-11 09:30:41 -07001550status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001551 int index,
1552 audio_devices_t device)
1553{
1554
1555 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1556 return BAD_VALUE;
1557 }
1558 if (!audio_is_output_device(device)) {
1559 return BAD_VALUE;
1560 }
1561
1562 // Force max volume if stream cannot be muted
1563 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1564
1565 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1566 stream, device, index);
1567
1568 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1569 // clear all device specific values
1570 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1571 mStreams[stream].mIndexCur.clear();
1572 }
1573 mStreams[stream].mIndexCur.add(device, index);
1574
1575 // compute and apply stream volume on all outputs according to connected device
1576 status_t status = NO_ERROR;
1577 for (size_t i = 0; i < mOutputs.size(); i++) {
1578 audio_devices_t curDevice =
1579 getDeviceForVolume(mOutputs.valueAt(i)->device());
1580 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1581 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1582 if (volStatus != NO_ERROR) {
1583 status = volStatus;
1584 }
1585 }
1586 }
1587 return status;
1588}
1589
Eric Laurente0720872014-03-11 09:30:41 -07001590status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001591 int *index,
1592 audio_devices_t device)
1593{
1594 if (index == NULL) {
1595 return BAD_VALUE;
1596 }
1597 if (!audio_is_output_device(device)) {
1598 return BAD_VALUE;
1599 }
1600 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1601 // the strategy the stream belongs to.
1602 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1603 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1604 }
1605 device = getDeviceForVolume(device);
1606
1607 *index = mStreams[stream].getVolumeIndex(device);
1608 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1609 return NO_ERROR;
1610}
1611
Eric Laurente0720872014-03-11 09:30:41 -07001612audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001613 const SortedVector<audio_io_handle_t>& outputs)
1614{
1615 // select one output among several suitable for global effects.
1616 // The priority is as follows:
1617 // 1: An offloaded output. If the effect ends up not being offloadable,
1618 // AudioFlinger will invalidate the track and the offloaded output
1619 // will be closed causing the effect to be moved to a PCM output.
1620 // 2: A deep buffer output
1621 // 3: the first output in the list
1622
1623 if (outputs.size() == 0) {
1624 return 0;
1625 }
1626
1627 audio_io_handle_t outputOffloaded = 0;
1628 audio_io_handle_t outputDeepBuffer = 0;
1629
1630 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001631 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001632 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001633 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1634 outputOffloaded = outputs[i];
1635 }
1636 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1637 outputDeepBuffer = outputs[i];
1638 }
1639 }
1640
1641 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1642 outputOffloaded, outputDeepBuffer);
1643 if (outputOffloaded != 0) {
1644 return outputOffloaded;
1645 }
1646 if (outputDeepBuffer != 0) {
1647 return outputDeepBuffer;
1648 }
1649
1650 return outputs[0];
1651}
1652
Eric Laurente0720872014-03-11 09:30:41 -07001653audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001654{
1655 // apply simple rule where global effects are attached to the same output as MUSIC streams
1656
Eric Laurent3b73df72014-03-11 09:06:29 -07001657 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001658 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1659 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1660
1661 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1662 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1663 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1664
1665 return output;
1666}
1667
Eric Laurente0720872014-03-11 09:30:41 -07001668status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001669 audio_io_handle_t io,
1670 uint32_t strategy,
1671 int session,
1672 int id)
1673{
1674 ssize_t index = mOutputs.indexOfKey(io);
1675 if (index < 0) {
1676 index = mInputs.indexOfKey(io);
1677 if (index < 0) {
1678 ALOGW("registerEffect() unknown io %d", io);
1679 return INVALID_OPERATION;
1680 }
1681 }
1682
1683 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1684 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1685 desc->name, desc->memoryUsage);
1686 return INVALID_OPERATION;
1687 }
1688 mTotalEffectsMemory += desc->memoryUsage;
1689 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1690 desc->name, io, strategy, session, id);
1691 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1692
Eric Laurent1f2f2232014-06-02 12:01:23 -07001693 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1694 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1695 effectDesc->mIo = io;
1696 effectDesc->mStrategy = (routing_strategy)strategy;
1697 effectDesc->mSession = session;
1698 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001699
Eric Laurent1f2f2232014-06-02 12:01:23 -07001700 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001701
1702 return NO_ERROR;
1703}
1704
Eric Laurente0720872014-03-11 09:30:41 -07001705status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001706{
1707 ssize_t index = mEffects.indexOfKey(id);
1708 if (index < 0) {
1709 ALOGW("unregisterEffect() unknown effect ID %d", id);
1710 return INVALID_OPERATION;
1711 }
1712
Eric Laurent1f2f2232014-06-02 12:01:23 -07001713 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001714
Eric Laurent1f2f2232014-06-02 12:01:23 -07001715 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001716
Eric Laurent1f2f2232014-06-02 12:01:23 -07001717 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001718 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001719 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1720 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001721 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001722 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001723 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001724 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001725
1726 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001727
1728 return NO_ERROR;
1729}
1730
Eric Laurente0720872014-03-11 09:30:41 -07001731status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001732{
1733 ssize_t index = mEffects.indexOfKey(id);
1734 if (index < 0) {
1735 ALOGW("unregisterEffect() unknown effect ID %d", id);
1736 return INVALID_OPERATION;
1737 }
1738
1739 return setEffectEnabled(mEffects.valueAt(index), enabled);
1740}
1741
Eric Laurent1f2f2232014-06-02 12:01:23 -07001742status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001743{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001744 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001745 ALOGV("setEffectEnabled(%s) effect already %s",
1746 enabled?"true":"false", enabled?"enabled":"disabled");
1747 return INVALID_OPERATION;
1748 }
1749
1750 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001751 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001752 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001753 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001754 return INVALID_OPERATION;
1755 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001756 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001757 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1758 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001759 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001760 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001761 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1762 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001763 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001764 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001765 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1766 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001767 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001768 return NO_ERROR;
1769}
1770
Eric Laurente0720872014-03-11 09:30:41 -07001771bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001772{
1773 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001774 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1775 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1776 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001777 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001778 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001779 return true;
1780 }
1781 }
1782 return false;
1783}
1784
Eric Laurente0720872014-03-11 09:30:41 -07001785bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001786{
1787 nsecs_t sysTime = systemTime();
1788 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001789 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001790 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001791 return true;
1792 }
1793 }
1794 return false;
1795}
1796
Eric Laurente0720872014-03-11 09:30:41 -07001797bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001798 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001799{
1800 nsecs_t sysTime = systemTime();
1801 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001802 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001803 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001804 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001805 return true;
1806 }
1807 }
1808 return false;
1809}
1810
Eric Laurente0720872014-03-11 09:30:41 -07001811bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001812{
1813 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001814 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001815 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001816 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001817 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1818 && (inputDescriptor->mRefCount > 0)) {
1819 return true;
1820 }
1821 }
1822 return false;
1823}
1824
1825
Eric Laurente0720872014-03-11 09:30:41 -07001826status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001827{
1828 const size_t SIZE = 256;
1829 char buffer[SIZE];
1830 String8 result;
1831
1832 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1833 result.append(buffer);
1834
1835 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1836 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001837 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1838 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001839 snprintf(buffer, SIZE, " Force use for communications %d\n",
1840 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001841 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001842 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001843 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001844 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001845 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001846 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001847 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001848 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001849 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001850 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1851 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1852 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001853
Eric Laurent3a4311c2014-03-17 12:00:47 -07001854 snprintf(buffer, SIZE, " Available output devices:\n");
1855 result.append(buffer);
1856 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001857 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001858 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001859 }
1860 snprintf(buffer, SIZE, "\n Available input devices:\n");
1861 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001862 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001863 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001864 }
Eric Laurente552edb2014-03-10 17:42:56 -07001865
1866 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1867 write(fd, buffer, strlen(buffer));
1868 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001869 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001870 write(fd, buffer, strlen(buffer));
1871 mHwModules[i]->dump(fd);
1872 }
1873
1874 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1875 write(fd, buffer, strlen(buffer));
1876 for (size_t i = 0; i < mOutputs.size(); i++) {
1877 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1878 write(fd, buffer, strlen(buffer));
1879 mOutputs.valueAt(i)->dump(fd);
1880 }
1881
1882 snprintf(buffer, SIZE, "\nInputs dump:\n");
1883 write(fd, buffer, strlen(buffer));
1884 for (size_t i = 0; i < mInputs.size(); i++) {
1885 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1886 write(fd, buffer, strlen(buffer));
1887 mInputs.valueAt(i)->dump(fd);
1888 }
1889
1890 snprintf(buffer, SIZE, "\nStreams dump:\n");
1891 write(fd, buffer, strlen(buffer));
1892 snprintf(buffer, SIZE,
1893 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1894 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001895 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001896 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001897 write(fd, buffer, strlen(buffer));
1898 mStreams[i].dump(fd);
1899 }
1900
1901 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1902 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1903 write(fd, buffer, strlen(buffer));
1904
1905 snprintf(buffer, SIZE, "Registered effects:\n");
1906 write(fd, buffer, strlen(buffer));
1907 for (size_t i = 0; i < mEffects.size(); i++) {
1908 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1909 write(fd, buffer, strlen(buffer));
1910 mEffects.valueAt(i)->dump(fd);
1911 }
1912
Eric Laurent4d416952014-08-10 14:07:09 -07001913 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1914 write(fd, buffer, strlen(buffer));
1915 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1916 mAudioPatches[i]->dump(fd, 2, i);
1917 }
Eric Laurente552edb2014-03-10 17:42:56 -07001918
1919 return NO_ERROR;
1920}
1921
1922// This function checks for the parameters which can be offloaded.
1923// This can be enhanced depending on the capability of the DSP and policy
1924// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001925bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001926{
1927 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001928 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001929 offloadInfo.sample_rate, offloadInfo.channel_mask,
1930 offloadInfo.format,
1931 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1932 offloadInfo.has_video);
1933
1934 // Check if offload has been disabled
1935 char propValue[PROPERTY_VALUE_MAX];
1936 if (property_get("audio.offload.disable", propValue, "0")) {
1937 if (atoi(propValue) != 0) {
1938 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1939 return false;
1940 }
1941 }
1942
1943 // Check if stream type is music, then only allow offload as of now.
1944 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1945 {
1946 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1947 return false;
1948 }
1949
1950 //TODO: enable audio offloading with video when ready
1951 if (offloadInfo.has_video)
1952 {
1953 ALOGV("isOffloadSupported: has_video == true, returning false");
1954 return false;
1955 }
1956
1957 //If duration is less than minimum value defined in property, return false
1958 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1959 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1960 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1961 return false;
1962 }
1963 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1964 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1965 return false;
1966 }
1967
1968 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1969 // creating an offloaded track and tearing it down immediately after start when audioflinger
1970 // detects there is an active non offloadable effect.
1971 // FIXME: We should check the audio session here but we do not have it in this context.
1972 // This may prevent offloading in rare situations where effects are left active by apps
1973 // in the background.
1974 if (isNonOffloadableEffectEnabled()) {
1975 return false;
1976 }
1977
1978 // See if there is a profile to support this.
1979 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001980 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001981 offloadInfo.sample_rate,
1982 offloadInfo.format,
1983 offloadInfo.channel_mask,
1984 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001985 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1986 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001987}
1988
Eric Laurent6a94d692014-05-20 11:18:06 -07001989status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1990 audio_port_type_t type,
1991 unsigned int *num_ports,
1992 struct audio_port *ports,
1993 unsigned int *generation)
1994{
1995 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1996 generation == NULL) {
1997 return BAD_VALUE;
1998 }
1999 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2000 if (ports == NULL) {
2001 *num_ports = 0;
2002 }
2003
2004 size_t portsWritten = 0;
2005 size_t portsMax = *num_ports;
2006 *num_ports = 0;
2007 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2008 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2009 for (size_t i = 0;
2010 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2011 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2012 }
2013 *num_ports += mAvailableOutputDevices.size();
2014 }
2015 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2016 for (size_t i = 0;
2017 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2018 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2019 }
2020 *num_ports += mAvailableInputDevices.size();
2021 }
2022 }
2023 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2024 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2025 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2026 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2027 }
2028 *num_ports += mInputs.size();
2029 }
2030 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002031 size_t numOutputs = 0;
2032 for (size_t i = 0; i < mOutputs.size(); i++) {
2033 if (!mOutputs[i]->isDuplicated()) {
2034 numOutputs++;
2035 if (portsWritten < portsMax) {
2036 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2037 }
2038 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002039 }
Eric Laurent84c70242014-06-23 08:46:27 -07002040 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002041 }
2042 }
2043 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002044 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002045 return NO_ERROR;
2046}
2047
2048status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2049{
2050 return NO_ERROR;
2051}
2052
Eric Laurent1f2f2232014-06-02 12:01:23 -07002053sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002054 audio_port_handle_t id) const
2055{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002056 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002057 for (size_t i = 0; i < mOutputs.size(); i++) {
2058 outputDesc = mOutputs.valueAt(i);
2059 if (outputDesc->mId == id) {
2060 break;
2061 }
2062 }
2063 return outputDesc;
2064}
2065
Eric Laurent1f2f2232014-06-02 12:01:23 -07002066sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002067 audio_port_handle_t id) const
2068{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002069 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002070 for (size_t i = 0; i < mInputs.size(); i++) {
2071 inputDesc = mInputs.valueAt(i);
2072 if (inputDesc->mId == id) {
2073 break;
2074 }
2075 }
2076 return inputDesc;
2077}
2078
Eric Laurent1f2f2232014-06-02 12:01:23 -07002079sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2080 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002081{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002082 sp <HwModule> module;
2083
Eric Laurent6a94d692014-05-20 11:18:06 -07002084 for (size_t i = 0; i < mHwModules.size(); i++) {
2085 if (mHwModules[i]->mHandle == 0) {
2086 continue;
2087 }
2088 if (audio_is_output_device(device)) {
2089 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2090 {
2091 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2092 return mHwModules[i];
2093 }
2094 }
2095 } else {
2096 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2097 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2098 device & ~AUDIO_DEVICE_BIT_IN) {
2099 return mHwModules[i];
2100 }
2101 }
2102 }
2103 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002104 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002105}
2106
Eric Laurent1f2f2232014-06-02 12:01:23 -07002107sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002108{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002109 sp <HwModule> module;
2110
Eric Laurent1afeecb2014-05-14 08:52:28 -07002111 for (size_t i = 0; i < mHwModules.size(); i++)
2112 {
2113 if (strcmp(mHwModules[i]->mName, name) == 0) {
2114 return mHwModules[i];
2115 }
2116 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002117 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002118}
2119
Eric Laurentc2730ba2014-07-20 15:47:07 -07002120audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2121{
2122 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2123 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2124 return devices & mAvailableOutputDevices.types();
2125}
2126
2127audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2128{
2129 audio_module_handle_t primaryHandle =
2130 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2131 audio_devices_t devices = AUDIO_DEVICE_NONE;
2132 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2133 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2134 devices |= mAvailableInputDevices[i]->mDeviceType;
2135 }
2136 }
2137 return devices;
2138}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002139
Eric Laurent6a94d692014-05-20 11:18:06 -07002140status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2141 audio_patch_handle_t *handle,
2142 uid_t uid)
2143{
2144 ALOGV("createAudioPatch()");
2145
2146 if (handle == NULL || patch == NULL) {
2147 return BAD_VALUE;
2148 }
2149 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2150
Eric Laurent874c42872014-08-08 15:13:39 -07002151 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2152 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2153 return BAD_VALUE;
2154 }
2155 // only one source per audio patch supported for now
2156 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002157 return INVALID_OPERATION;
2158 }
Eric Laurent874c42872014-08-08 15:13:39 -07002159
2160 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002161 return INVALID_OPERATION;
2162 }
Eric Laurent874c42872014-08-08 15:13:39 -07002163 for (size_t i = 0; i < patch->num_sinks; i++) {
2164 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2165 return INVALID_OPERATION;
2166 }
2167 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002168
2169 sp<AudioPatch> patchDesc;
2170 ssize_t index = mAudioPatches.indexOfKey(*handle);
2171
Eric Laurent6a94d692014-05-20 11:18:06 -07002172 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2173 patch->sources[0].role,
2174 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002175#if LOG_NDEBUG == 0
2176 for (size_t i = 0; i < patch->num_sinks; i++) {
2177 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2178 patch->sinks[i].role,
2179 patch->sinks[i].type);
2180 }
2181#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002182
2183 if (index >= 0) {
2184 patchDesc = mAudioPatches.valueAt(index);
2185 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2186 mUidCached, patchDesc->mUid, uid);
2187 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2188 return INVALID_OPERATION;
2189 }
2190 } else {
2191 *handle = 0;
2192 }
2193
2194 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002195 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002196 if (outputDesc == NULL) {
2197 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2198 return BAD_VALUE;
2199 }
Eric Laurent84c70242014-06-23 08:46:27 -07002200 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2201 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002202 if (patchDesc != 0) {
2203 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2204 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2205 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2206 return BAD_VALUE;
2207 }
2208 }
Eric Laurent874c42872014-08-08 15:13:39 -07002209 DeviceVector devices;
2210 for (size_t i = 0; i < patch->num_sinks; i++) {
2211 // Only support mix to devices connection
2212 // TODO add support for mix to mix connection
2213 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2214 ALOGV("createAudioPatch() source mix but sink is not a device");
2215 return INVALID_OPERATION;
2216 }
2217 sp<DeviceDescriptor> devDesc =
2218 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2219 if (devDesc == 0) {
2220 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2221 return BAD_VALUE;
2222 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002223
Eric Laurent874c42872014-08-08 15:13:39 -07002224 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2225 patch->sources[0].sample_rate,
2226 NULL, // updatedSamplingRate
2227 patch->sources[0].format,
2228 patch->sources[0].channel_mask,
2229 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2230 ALOGV("createAudioPatch() profile not supported for device %08x",
2231 devDesc->mDeviceType);
2232 return INVALID_OPERATION;
2233 }
2234 devices.add(devDesc);
2235 }
2236 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002237 return INVALID_OPERATION;
2238 }
Eric Laurent874c42872014-08-08 15:13:39 -07002239
Eric Laurent6a94d692014-05-20 11:18:06 -07002240 // TODO: reconfigure output format and channels here
2241 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002242 devices.types(), outputDesc->mIoHandle);
2243 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002244 index = mAudioPatches.indexOfKey(*handle);
2245 if (index >= 0) {
2246 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2247 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2248 }
2249 patchDesc = mAudioPatches.valueAt(index);
2250 patchDesc->mUid = uid;
2251 ALOGV("createAudioPatch() success");
2252 } else {
2253 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2254 return INVALID_OPERATION;
2255 }
2256 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2257 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2258 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002259 // only one sink supported when connecting an input device to a mix
2260 if (patch->num_sinks > 1) {
2261 return INVALID_OPERATION;
2262 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002263 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002264 if (inputDesc == NULL) {
2265 return BAD_VALUE;
2266 }
2267 if (patchDesc != 0) {
2268 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2269 return BAD_VALUE;
2270 }
2271 }
2272 sp<DeviceDescriptor> devDesc =
2273 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2274 if (devDesc == 0) {
2275 return BAD_VALUE;
2276 }
2277
Eric Laurent84c70242014-06-23 08:46:27 -07002278 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002279 patch->sinks[0].sample_rate,
2280 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002281 patch->sinks[0].format,
2282 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002283 // FIXME for the parameter type,
2284 // and the NONE
2285 (audio_output_flags_t)
2286 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002287 return INVALID_OPERATION;
2288 }
2289 // TODO: reconfigure output format and channels here
2290 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002291 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002292 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002293 index = mAudioPatches.indexOfKey(*handle);
2294 if (index >= 0) {
2295 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2296 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2297 }
2298 patchDesc = mAudioPatches.valueAt(index);
2299 patchDesc->mUid = uid;
2300 ALOGV("createAudioPatch() success");
2301 } else {
2302 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2303 return INVALID_OPERATION;
2304 }
2305 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2306 // device to device connection
2307 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002308 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002309 return BAD_VALUE;
2310 }
2311 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002312 sp<DeviceDescriptor> srcDeviceDesc =
2313 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002314 if (srcDeviceDesc == 0) {
2315 return BAD_VALUE;
2316 }
Eric Laurent874c42872014-08-08 15:13:39 -07002317
Eric Laurent6a94d692014-05-20 11:18:06 -07002318 //update source and sink with our own data as the data passed in the patch may
2319 // be incomplete.
2320 struct audio_patch newPatch = *patch;
2321 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002322
Eric Laurent874c42872014-08-08 15:13:39 -07002323 for (size_t i = 0; i < patch->num_sinks; i++) {
2324 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2325 ALOGV("createAudioPatch() source device but one sink is not a device");
2326 return INVALID_OPERATION;
2327 }
2328
2329 sp<DeviceDescriptor> sinkDeviceDesc =
2330 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2331 if (sinkDeviceDesc == 0) {
2332 return BAD_VALUE;
2333 }
2334 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2335
2336 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2337 // only one sink supported when connected devices across HW modules
2338 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002339 return INVALID_OPERATION;
2340 }
Eric Laurent874c42872014-08-08 15:13:39 -07002341 SortedVector<audio_io_handle_t> outputs =
2342 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2343 mOutputs);
2344 // if the sink device is reachable via an opened output stream, request to go via
2345 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002346 audio_io_handle_t output = selectOutput(outputs,
2347 AUDIO_OUTPUT_FLAG_NONE,
2348 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002349 if (output != AUDIO_IO_HANDLE_NONE) {
2350 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2351 if (outputDesc->isDuplicated()) {
2352 return INVALID_OPERATION;
2353 }
2354 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2355 newPatch.num_sources = 2;
2356 }
Eric Laurent83b88082014-06-20 18:31:16 -07002357 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002358 }
2359 // TODO: check from routing capabilities in config file and other conflicting patches
2360
2361 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2362 if (index >= 0) {
2363 afPatchHandle = patchDesc->mAfPatchHandle;
2364 }
2365
2366 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2367 &afPatchHandle,
2368 0);
2369 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2370 status, afPatchHandle);
2371 if (status == NO_ERROR) {
2372 if (index < 0) {
2373 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2374 &newPatch, uid);
2375 addAudioPatch(patchDesc->mHandle, patchDesc);
2376 } else {
2377 patchDesc->mPatch = newPatch;
2378 }
2379 patchDesc->mAfPatchHandle = afPatchHandle;
2380 *handle = patchDesc->mHandle;
2381 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002382 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002383 } else {
2384 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2385 status);
2386 return INVALID_OPERATION;
2387 }
2388 } else {
2389 return BAD_VALUE;
2390 }
2391 } else {
2392 return BAD_VALUE;
2393 }
2394 return NO_ERROR;
2395}
2396
2397status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2398 uid_t uid)
2399{
2400 ALOGV("releaseAudioPatch() patch %d", handle);
2401
2402 ssize_t index = mAudioPatches.indexOfKey(handle);
2403
2404 if (index < 0) {
2405 return BAD_VALUE;
2406 }
2407 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2408 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2409 mUidCached, patchDesc->mUid, uid);
2410 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2411 return INVALID_OPERATION;
2412 }
2413
2414 struct audio_patch *patch = &patchDesc->mPatch;
2415 patchDesc->mUid = mUidCached;
2416 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002417 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002418 if (outputDesc == NULL) {
2419 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2420 return BAD_VALUE;
2421 }
2422
2423 setOutputDevice(outputDesc->mIoHandle,
2424 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2425 true,
2426 0,
2427 NULL);
2428 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2429 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002430 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002431 if (inputDesc == NULL) {
2432 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2433 return BAD_VALUE;
2434 }
2435 setInputDevice(inputDesc->mIoHandle,
2436 getNewInputDevice(inputDesc->mIoHandle),
2437 true,
2438 NULL);
2439 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2440 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2441 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2442 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2443 status, patchDesc->mAfPatchHandle);
2444 removeAudioPatch(patchDesc->mHandle);
2445 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002446 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002447 } else {
2448 return BAD_VALUE;
2449 }
2450 } else {
2451 return BAD_VALUE;
2452 }
2453 return NO_ERROR;
2454}
2455
2456status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2457 struct audio_patch *patches,
2458 unsigned int *generation)
2459{
2460 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2461 generation == NULL) {
2462 return BAD_VALUE;
2463 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002464 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002465 *num_patches, patches, mAudioPatches.size());
2466 if (patches == NULL) {
2467 *num_patches = 0;
2468 }
2469
2470 size_t patchesWritten = 0;
2471 size_t patchesMax = *num_patches;
2472 for (size_t i = 0;
2473 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2474 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2475 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002476 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002477 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2478 }
2479 *num_patches = mAudioPatches.size();
2480
2481 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002482 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002483 return NO_ERROR;
2484}
2485
Eric Laurente1715a42014-05-20 11:30:42 -07002486status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002487{
Eric Laurente1715a42014-05-20 11:30:42 -07002488 ALOGV("setAudioPortConfig()");
2489
2490 if (config == NULL) {
2491 return BAD_VALUE;
2492 }
2493 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2494 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002495 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2496 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002497 }
2498
Eric Laurenta121f902014-06-03 13:32:54 -07002499 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002500 if (config->type == AUDIO_PORT_TYPE_MIX) {
2501 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002502 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002503 if (outputDesc == NULL) {
2504 return BAD_VALUE;
2505 }
Eric Laurent84c70242014-06-23 08:46:27 -07002506 ALOG_ASSERT(!outputDesc->isDuplicated(),
2507 "setAudioPortConfig() called on duplicated output %d",
2508 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002509 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002510 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002511 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002512 if (inputDesc == NULL) {
2513 return BAD_VALUE;
2514 }
Eric Laurenta121f902014-06-03 13:32:54 -07002515 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002516 } else {
2517 return BAD_VALUE;
2518 }
2519 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2520 sp<DeviceDescriptor> deviceDesc;
2521 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2522 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2523 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2524 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2525 } else {
2526 return BAD_VALUE;
2527 }
2528 if (deviceDesc == NULL) {
2529 return BAD_VALUE;
2530 }
Eric Laurenta121f902014-06-03 13:32:54 -07002531 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002532 } else {
2533 return BAD_VALUE;
2534 }
2535
Eric Laurenta121f902014-06-03 13:32:54 -07002536 struct audio_port_config backupConfig;
2537 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2538 if (status == NO_ERROR) {
2539 struct audio_port_config newConfig;
2540 audioPortConfig->toAudioPortConfig(&newConfig, config);
2541 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002542 }
Eric Laurenta121f902014-06-03 13:32:54 -07002543 if (status != NO_ERROR) {
2544 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002545 }
Eric Laurente1715a42014-05-20 11:30:42 -07002546
2547 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002548}
2549
2550void AudioPolicyManager::clearAudioPatches(uid_t uid)
2551{
2552 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2553 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2554 if (patchDesc->mUid == uid) {
2555 // releaseAudioPatch() removes the patch from mAudioPatches
2556 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2557 i--;
2558 }
2559 }
2560 }
2561}
2562
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002563status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2564 audio_io_handle_t *ioHandle,
2565 audio_devices_t *device)
2566{
2567 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2568 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2569 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2570
2571 mSoundTriggerSessions.add(*session, *ioHandle);
2572
2573 return NO_ERROR;
2574}
2575
2576status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2577{
2578 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2579 if (index < 0) {
2580 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2581 return BAD_VALUE;
2582 }
2583
2584 mSoundTriggerSessions.removeItem(session);
2585 return NO_ERROR;
2586}
2587
Eric Laurent6a94d692014-05-20 11:18:06 -07002588status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2589 const sp<AudioPatch>& patch)
2590{
2591 ssize_t index = mAudioPatches.indexOfKey(handle);
2592
2593 if (index >= 0) {
2594 ALOGW("addAudioPatch() patch %d already in", handle);
2595 return ALREADY_EXISTS;
2596 }
2597 mAudioPatches.add(handle, patch);
2598 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2599 "sink handle %d",
2600 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2601 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2602 return NO_ERROR;
2603}
2604
2605status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2606{
2607 ssize_t index = mAudioPatches.indexOfKey(handle);
2608
2609 if (index < 0) {
2610 ALOGW("removeAudioPatch() patch %d not in", handle);
2611 return ALREADY_EXISTS;
2612 }
2613 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2614 mAudioPatches.valueAt(index)->mAfPatchHandle);
2615 mAudioPatches.removeItemsAt(index);
2616 return NO_ERROR;
2617}
2618
Eric Laurente552edb2014-03-10 17:42:56 -07002619// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002620// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002621// ----------------------------------------------------------------------------
2622
Eric Laurent3a4311c2014-03-17 12:00:47 -07002623uint32_t AudioPolicyManager::nextUniqueId()
2624{
2625 return android_atomic_inc(&mNextUniqueId);
2626}
2627
Eric Laurent6a94d692014-05-20 11:18:06 -07002628uint32_t AudioPolicyManager::nextAudioPortGeneration()
2629{
2630 return android_atomic_inc(&mAudioPortGeneration);
2631}
2632
Eric Laurente0720872014-03-11 09:30:41 -07002633AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002634 :
2635#ifdef AUDIO_POLICY_TEST
2636 Thread(false),
2637#endif //AUDIO_POLICY_TEST
2638 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002639 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002640 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2641 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002642 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002643 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2644 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002645{
Eric Laurent6a94d692014-05-20 11:18:06 -07002646 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002647 mpClientInterface = clientInterface;
2648
Eric Laurent3b73df72014-03-11 09:06:29 -07002649 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2650 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002651 }
2652
Eric Laurent1afeecb2014-05-14 08:52:28 -07002653 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002654 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2655 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2656 ALOGE("could not load audio policy configuration file, setting defaults");
2657 defaultAudioPolicyConfig();
2658 }
2659 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002660 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002661
2662 // must be done after reading the policy
2663 initializeVolumeCurves();
2664
2665 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002666 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2667 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002668 for (size_t i = 0; i < mHwModules.size(); i++) {
2669 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2670 if (mHwModules[i]->mHandle == 0) {
2671 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2672 continue;
2673 }
2674 // open all output streams needed to access attached devices
2675 // except for direct output streams that are only opened when they are actually
2676 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002677 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002678 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2679 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002680 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002681
Eric Laurent3a4311c2014-03-17 12:00:47 -07002682 if (outProfile->mSupportedDevices.isEmpty()) {
2683 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2684 continue;
2685 }
2686
Eric Laurentd78f1532014-09-16 16:38:20 -07002687 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2688 continue;
2689 }
Eric Laurent83b88082014-06-20 18:31:16 -07002690 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2691 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2692 profileType = mDefaultOutputDevice->mDeviceType;
2693 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002694 // chose first device present in mSupportedDevices also part of
2695 // outputDeviceTypes
2696 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2697 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2698 if ((profileType & outputDeviceTypes) != 0) {
2699 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002700 }
Eric Laurente552edb2014-03-10 17:42:56 -07002701 }
2702 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002703 if ((profileType & outputDeviceTypes) == 0) {
2704 continue;
2705 }
2706 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2707
2708 outputDesc->mDevice = profileType;
2709 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2710 config.sample_rate = outputDesc->mSamplingRate;
2711 config.channel_mask = outputDesc->mChannelMask;
2712 config.format = outputDesc->mFormat;
2713 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2714 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2715 &output,
2716 &config,
2717 &outputDesc->mDevice,
2718 String8(""),
2719 &outputDesc->mLatency,
2720 outputDesc->mFlags);
2721
2722 if (status != NO_ERROR) {
2723 ALOGW("Cannot open output stream for device %08x on hw module %s",
2724 outputDesc->mDevice,
2725 mHwModules[i]->mName);
2726 } else {
2727 outputDesc->mSamplingRate = config.sample_rate;
2728 outputDesc->mChannelMask = config.channel_mask;
2729 outputDesc->mFormat = config.format;
2730
2731 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2732 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2733 ssize_t index =
2734 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2735 // give a valid ID to an attached device once confirmed it is reachable
2736 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2737 mAvailableOutputDevices[index]->mId = nextUniqueId();
2738 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2739 }
2740 }
2741 if (mPrimaryOutput == 0 &&
2742 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2743 mPrimaryOutput = output;
2744 }
2745 addOutput(output, outputDesc);
2746 setOutputDevice(output,
2747 outputDesc->mDevice,
2748 true);
2749 }
Eric Laurente552edb2014-03-10 17:42:56 -07002750 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002751 // open input streams needed to access attached devices to validate
2752 // mAvailableInputDevices list
2753 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2754 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002755 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002756
Eric Laurent3a4311c2014-03-17 12:00:47 -07002757 if (inProfile->mSupportedDevices.isEmpty()) {
2758 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2759 continue;
2760 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002761 // chose first device present in mSupportedDevices also part of
2762 // inputDeviceTypes
2763 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2764 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2765 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2766 if (profileType & inputDeviceTypes) {
2767 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002768 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002769 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002770 if ((profileType & inputDeviceTypes) == 0) {
2771 continue;
2772 }
2773 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2774
2775 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2776 inputDesc->mDevice = profileType;
2777
2778 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2779 config.sample_rate = inputDesc->mSamplingRate;
2780 config.channel_mask = inputDesc->mChannelMask;
2781 config.format = inputDesc->mFormat;
2782 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2783 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2784 &input,
2785 &config,
2786 &inputDesc->mDevice,
2787 String8(""),
2788 AUDIO_SOURCE_MIC,
2789 AUDIO_INPUT_FLAG_NONE);
2790
2791 if (status == NO_ERROR) {
2792 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2793 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2794 ssize_t index =
2795 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2796 // give a valid ID to an attached device once confirmed it is reachable
2797 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2798 mAvailableInputDevices[index]->mId = nextUniqueId();
2799 mAvailableInputDevices[index]->mModule = mHwModules[i];
2800 }
2801 }
2802 mpClientInterface->closeInput(input);
2803 } else {
2804 ALOGW("Cannot open input stream for device %08x on hw module %s",
2805 inputDesc->mDevice,
2806 mHwModules[i]->mName);
2807 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002808 }
2809 }
2810 // make sure all attached devices have been allocated a unique ID
2811 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2812 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002813 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002814 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2815 continue;
2816 }
2817 i++;
2818 }
2819 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2820 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002821 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002822 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2823 continue;
2824 }
2825 i++;
2826 }
2827 // make sure default device is reachable
2828 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002829 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002830 }
Eric Laurente552edb2014-03-10 17:42:56 -07002831
2832 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2833
2834 updateDevicesAndOutputs();
2835
2836#ifdef AUDIO_POLICY_TEST
2837 if (mPrimaryOutput != 0) {
2838 AudioParameter outputCmd = AudioParameter();
2839 outputCmd.addInt(String8("set_id"), 0);
2840 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2841
2842 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2843 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002844 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2845 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002846 mTestLatencyMs = 0;
2847 mCurOutput = 0;
2848 mDirectOutput = false;
2849 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2850 mTestOutputs[i] = 0;
2851 }
2852
2853 const size_t SIZE = 256;
2854 char buffer[SIZE];
2855 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2856 run(buffer, ANDROID_PRIORITY_AUDIO);
2857 }
2858#endif //AUDIO_POLICY_TEST
2859}
2860
Eric Laurente0720872014-03-11 09:30:41 -07002861AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002862{
2863#ifdef AUDIO_POLICY_TEST
2864 exit();
2865#endif //AUDIO_POLICY_TEST
2866 for (size_t i = 0; i < mOutputs.size(); i++) {
2867 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002868 }
2869 for (size_t i = 0; i < mInputs.size(); i++) {
2870 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002871 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002872 mAvailableOutputDevices.clear();
2873 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002874 mOutputs.clear();
2875 mInputs.clear();
2876 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002877}
2878
Eric Laurente0720872014-03-11 09:30:41 -07002879status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002880{
2881 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2882}
2883
2884#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002885bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002886{
2887 ALOGV("entering threadLoop()");
2888 while (!exitPending())
2889 {
2890 String8 command;
2891 int valueInt;
2892 String8 value;
2893
2894 Mutex::Autolock _l(mLock);
2895 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2896
2897 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2898 AudioParameter param = AudioParameter(command);
2899
2900 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2901 valueInt != 0) {
2902 ALOGV("Test command %s received", command.string());
2903 String8 target;
2904 if (param.get(String8("target"), target) != NO_ERROR) {
2905 target = "Manager";
2906 }
2907 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2908 param.remove(String8("test_cmd_policy_output"));
2909 mCurOutput = valueInt;
2910 }
2911 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2912 param.remove(String8("test_cmd_policy_direct"));
2913 if (value == "false") {
2914 mDirectOutput = false;
2915 } else if (value == "true") {
2916 mDirectOutput = true;
2917 }
2918 }
2919 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2920 param.remove(String8("test_cmd_policy_input"));
2921 mTestInput = valueInt;
2922 }
2923
2924 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2925 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002926 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002927 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002928 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002929 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002930 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002931 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002932 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002933 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002934 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002935 if (target == "Manager") {
2936 mTestFormat = format;
2937 } else if (mTestOutputs[mCurOutput] != 0) {
2938 AudioParameter outputParam = AudioParameter();
2939 outputParam.addInt(String8("format"), format);
2940 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2941 }
2942 }
2943 }
2944 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2945 param.remove(String8("test_cmd_policy_channels"));
2946 int channels = 0;
2947
2948 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002949 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002950 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002951 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002952 }
2953 if (channels != 0) {
2954 if (target == "Manager") {
2955 mTestChannels = channels;
2956 } else if (mTestOutputs[mCurOutput] != 0) {
2957 AudioParameter outputParam = AudioParameter();
2958 outputParam.addInt(String8("channels"), channels);
2959 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2960 }
2961 }
2962 }
2963 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2964 param.remove(String8("test_cmd_policy_sampleRate"));
2965 if (valueInt >= 0 && valueInt <= 96000) {
2966 int samplingRate = valueInt;
2967 if (target == "Manager") {
2968 mTestSamplingRate = samplingRate;
2969 } else if (mTestOutputs[mCurOutput] != 0) {
2970 AudioParameter outputParam = AudioParameter();
2971 outputParam.addInt(String8("sampling_rate"), samplingRate);
2972 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2973 }
2974 }
2975 }
2976
2977 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2978 param.remove(String8("test_cmd_policy_reopen"));
2979
Eric Laurent1f2f2232014-06-02 12:01:23 -07002980 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002981 mpClientInterface->closeOutput(mPrimaryOutput);
2982
2983 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2984
Eric Laurente552edb2014-03-10 17:42:56 -07002985 mOutputs.removeItem(mPrimaryOutput);
2986
Eric Laurent1f2f2232014-06-02 12:01:23 -07002987 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002988 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002989 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2990 config.sample_rate = outputDesc->mSamplingRate;
2991 config.channel_mask = outputDesc->mChannelMask;
2992 config.format = outputDesc->mFormat;
2993 status_t status = mpClientInterface->openOutput(moduleHandle,
2994 &mPrimaryOutput,
2995 &config,
2996 &outputDesc->mDevice,
2997 String8(""),
2998 &outputDesc->mLatency,
2999 outputDesc->mFlags);
3000 if (status != NO_ERROR) {
3001 ALOGE("Failed to reopen hardware output stream, "
3002 "samplingRate: %d, format %d, channels %d",
3003 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003004 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003005 outputDesc->mSamplingRate = config.sample_rate;
3006 outputDesc->mChannelMask = config.channel_mask;
3007 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003008 AudioParameter outputCmd = AudioParameter();
3009 outputCmd.addInt(String8("set_id"), 0);
3010 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3011 addOutput(mPrimaryOutput, outputDesc);
3012 }
3013 }
3014
3015
3016 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3017 }
3018 }
3019 return false;
3020}
3021
Eric Laurente0720872014-03-11 09:30:41 -07003022void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003023{
3024 {
3025 AutoMutex _l(mLock);
3026 requestExit();
3027 mWaitWorkCV.signal();
3028 }
3029 requestExitAndWait();
3030}
3031
Eric Laurente0720872014-03-11 09:30:41 -07003032int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003033{
3034 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3035 if (output == mTestOutputs[i]) return i;
3036 }
3037 return 0;
3038}
3039#endif //AUDIO_POLICY_TEST
3040
3041// ---
3042
Eric Laurent1f2f2232014-06-02 12:01:23 -07003043void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003044{
Eric Laurent1c333e22014-05-20 10:48:17 -07003045 outputDesc->mIoHandle = output;
3046 outputDesc->mId = nextUniqueId();
3047 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003048 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003049}
3050
Eric Laurent1f2f2232014-06-02 12:01:23 -07003051void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003052{
Eric Laurent1c333e22014-05-20 10:48:17 -07003053 inputDesc->mIoHandle = input;
3054 inputDesc->mId = nextUniqueId();
3055 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003056 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003057}
Eric Laurente552edb2014-03-10 17:42:56 -07003058
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003059void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3060 const String8 address /*in*/,
3061 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3062 // look for a match on the given address on the addresses of the outputs:
3063 // find the address by finding the patch that maps to this output
3064 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3065 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3066 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3067 if (patchIdx >= 0) {
3068 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3069 const int numSinks = patchDesc->mPatch.num_sinks;
3070 for (ssize_t j=0; j < numSinks; j++) {
3071 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3072 const char* patchAddr =
3073 patchDesc->mPatch.sinks[j].ext.device.address;
3074 if (strncmp(patchAddr,
3075 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003076 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003077 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3078 outputs.add(desc->mIoHandle);
3079 break;
3080 }
3081 }
3082 }
3083 }
3084}
3085
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003086status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003087 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003088 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003089 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003090{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003091 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003092 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003093 // erase all current sample rates, formats and channel masks
3094 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003095
Eric Laurent3b73df72014-03-11 09:06:29 -07003096 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003097 // first list already open outputs that can be routed to this device
3098 for (size_t i = 0; i < mOutputs.size(); i++) {
3099 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003100 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003101 if (!deviceDistinguishesOnAddress(device)) {
3102 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3103 outputs.add(mOutputs.keyAt(i));
3104 } else {
3105 ALOGV(" checking address match due to device 0x%x", device);
3106 findIoHandlesByAddress(desc, address, outputs);
3107 }
Eric Laurente552edb2014-03-10 17:42:56 -07003108 }
3109 }
3110 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003111 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003112 for (size_t i = 0; i < mHwModules.size(); i++)
3113 {
3114 if (mHwModules[i]->mHandle == 0) {
3115 continue;
3116 }
3117 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3118 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003119 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003120 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003121 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3122 }
3123 }
3124 }
3125
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003126 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3127
Eric Laurente552edb2014-03-10 17:42:56 -07003128 if (profiles.isEmpty() && outputs.isEmpty()) {
3129 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3130 return BAD_VALUE;
3131 }
3132
3133 // open outputs for matching profiles if needed. Direct outputs are also opened to
3134 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3135 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003136 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003137
3138 // nothing to do if one output is already opened for this profile
3139 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003140 for (j = 0; j < outputs.size(); j++) {
3141 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003142 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003143 // matching profile: save the sample rates, format and channel masks supported
3144 // by the profile in our device descriptor
3145 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003146 break;
3147 }
3148 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003149 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003150 continue;
3151 }
3152
Eric Laurent83b88082014-06-20 18:31:16 -07003153 ALOGV("opening output for device %08x with params %s profile %p",
3154 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003155 desc = new AudioOutputDescriptor(profile);
3156 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003157 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3158 config.sample_rate = desc->mSamplingRate;
3159 config.channel_mask = desc->mChannelMask;
3160 config.format = desc->mFormat;
3161 config.offload_info.sample_rate = desc->mSamplingRate;
3162 config.offload_info.channel_mask = desc->mChannelMask;
3163 config.offload_info.format = desc->mFormat;
3164 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3165 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3166 &output,
3167 &config,
3168 &desc->mDevice,
3169 address,
3170 &desc->mLatency,
3171 desc->mFlags);
3172 if (status == NO_ERROR) {
3173 desc->mSamplingRate = config.sample_rate;
3174 desc->mChannelMask = config.channel_mask;
3175 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003176
Eric Laurentd4692962014-05-05 18:13:44 -07003177 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003178 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003179 char *param = audio_device_address_to_parameter(device, address);
3180 mpClientInterface->setParameters(output, String8(param));
3181 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003182 }
3183
Eric Laurentd4692962014-05-05 18:13:44 -07003184 // Here is where we step through and resolve any "dynamic" fields
3185 String8 reply;
3186 char *value;
3187 if (profile->mSamplingRates[0] == 0) {
3188 reply = mpClientInterface->getParameters(output,
3189 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003190 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003191 reply.string());
3192 value = strpbrk((char *)reply.string(), "=");
3193 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003194 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003195 }
Eric Laurentd4692962014-05-05 18:13:44 -07003196 }
3197 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3198 reply = mpClientInterface->getParameters(output,
3199 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003200 ALOGV("checkOutputsForDevice() supported formats %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->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003205 }
Eric Laurentd4692962014-05-05 18:13:44 -07003206 }
3207 if (profile->mChannelMasks[0] == 0) {
3208 reply = mpClientInterface->getParameters(output,
3209 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003210 ALOGV("checkOutputsForDevice() supported channel masks %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->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003215 }
Eric Laurentd4692962014-05-05 18:13:44 -07003216 }
3217 if (((profile->mSamplingRates[0] == 0) &&
3218 (profile->mSamplingRates.size() < 2)) ||
3219 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3220 (profile->mFormats.size() < 2)) ||
3221 ((profile->mChannelMasks[0] == 0) &&
3222 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003223 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003224 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003225 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003226 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3227 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003228 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003229 config.sample_rate = profile->pickSamplingRate();
3230 config.channel_mask = profile->pickChannelMask();
3231 config.format = profile->pickFormat();
3232 config.offload_info.sample_rate = config.sample_rate;
3233 config.offload_info.channel_mask = config.channel_mask;
3234 config.offload_info.format = config.format;
3235 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3236 &output,
3237 &config,
3238 &desc->mDevice,
3239 address,
3240 &desc->mLatency,
3241 desc->mFlags);
3242 if (status == NO_ERROR) {
3243 desc->mSamplingRate = config.sample_rate;
3244 desc->mChannelMask = config.channel_mask;
3245 desc->mFormat = config.format;
3246 } else {
3247 output = AUDIO_IO_HANDLE_NONE;
3248 }
Eric Laurentd4692962014-05-05 18:13:44 -07003249 }
3250
Eric Laurentcf2c0212014-07-25 16:20:43 -07003251 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003252 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003253 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003254 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003255
Eric Laurentd4692962014-05-05 18:13:44 -07003256 // set initial stream volume for device
3257 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003258
Eric Laurentd4692962014-05-05 18:13:44 -07003259 //TODO: configure audio effect output stage here
3260
3261 // open a duplicating output thread for the new output and the primary output
3262 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3263 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003264 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003265 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003266 sp<AudioOutputDescriptor> dupOutputDesc =
3267 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003268 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3269 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3270 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3271 dupOutputDesc->mFormat = desc->mFormat;
3272 dupOutputDesc->mChannelMask = desc->mChannelMask;
3273 dupOutputDesc->mLatency = desc->mLatency;
3274 addOutput(duplicatedOutput, dupOutputDesc);
3275 applyStreamVolumes(duplicatedOutput, device, 0, true);
3276 } else {
3277 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3278 mPrimaryOutput, output);
3279 mpClientInterface->closeOutput(output);
3280 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003281 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003282 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003283 }
Eric Laurente552edb2014-03-10 17:42:56 -07003284 }
3285 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003286 } else {
3287 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003288 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003289 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003290 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003291 profiles.removeAt(profile_index);
3292 profile_index--;
3293 } else {
3294 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003295 devDesc->importAudioPort(profile);
3296
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003297 if (deviceDistinguishesOnAddress(device)) {
3298 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3299 device, address.string());
3300 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3301 NULL/*patch handle*/, address.string());
3302 }
Eric Laurente552edb2014-03-10 17:42:56 -07003303 ALOGV("checkOutputsForDevice(): adding output %d", output);
3304 }
3305 }
3306
3307 if (profiles.isEmpty()) {
3308 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3309 return BAD_VALUE;
3310 }
Eric Laurentd4692962014-05-05 18:13:44 -07003311 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003312 // check if one opened output is not needed any more after disconnecting one device
3313 for (size_t i = 0; i < mOutputs.size(); i++) {
3314 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003315 if (!desc->isDuplicated()) {
3316 if (!(desc->mProfile->mSupportedDevices.types()
3317 & mAvailableOutputDevices.types())) {
3318 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3319 mOutputs.keyAt(i));
3320 outputs.add(mOutputs.keyAt(i));
3321 } else if (deviceDistinguishesOnAddress(device) &&
3322 // exact match on device
3323 (desc->mProfile->mSupportedDevices.types() == device)) {
3324 findIoHandlesByAddress(desc, address, outputs);
3325 }
Eric Laurente552edb2014-03-10 17:42:56 -07003326 }
3327 }
Eric Laurentd4692962014-05-05 18:13:44 -07003328 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003329 for (size_t i = 0; i < mHwModules.size(); i++)
3330 {
3331 if (mHwModules[i]->mHandle == 0) {
3332 continue;
3333 }
3334 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3335 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003336 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003337 if (profile->mSupportedDevices.types() & device) {
3338 ALOGV("checkOutputsForDevice(): "
3339 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003340 if (profile->mSamplingRates[0] == 0) {
3341 profile->mSamplingRates.clear();
3342 profile->mSamplingRates.add(0);
3343 }
3344 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3345 profile->mFormats.clear();
3346 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3347 }
3348 if (profile->mChannelMasks[0] == 0) {
3349 profile->mChannelMasks.clear();
3350 profile->mChannelMasks.add(0);
3351 }
3352 }
3353 }
3354 }
3355 }
3356 return NO_ERROR;
3357}
3358
Eric Laurentd4692962014-05-05 18:13:44 -07003359status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3360 audio_policy_dev_state_t state,
3361 SortedVector<audio_io_handle_t>& inputs,
3362 const String8 address)
3363{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003364 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003365 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3366 // first list already open inputs that can be routed to this device
3367 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3368 desc = mInputs.valueAt(input_index);
3369 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3370 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3371 inputs.add(mInputs.keyAt(input_index));
3372 }
3373 }
3374
3375 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003376 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003377 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3378 {
3379 if (mHwModules[module_idx]->mHandle == 0) {
3380 continue;
3381 }
3382 for (size_t profile_index = 0;
3383 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3384 profile_index++)
3385 {
3386 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3387 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003388 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003389 profile_index, module_idx);
3390 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3391 }
3392 }
3393 }
3394
3395 if (profiles.isEmpty() && inputs.isEmpty()) {
3396 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3397 return BAD_VALUE;
3398 }
3399
3400 // open inputs for matching profiles if needed. Direct inputs are also opened to
3401 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3402 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3403
Eric Laurent1c333e22014-05-20 10:48:17 -07003404 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003405 // nothing to do if one input is already opened for this profile
3406 size_t input_index;
3407 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3408 desc = mInputs.valueAt(input_index);
3409 if (desc->mProfile == profile) {
3410 break;
3411 }
3412 }
3413 if (input_index != mInputs.size()) {
3414 continue;
3415 }
3416
3417 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3418 desc = new AudioInputDescriptor(profile);
3419 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003420 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3421 config.sample_rate = desc->mSamplingRate;
3422 config.channel_mask = desc->mChannelMask;
3423 config.format = desc->mFormat;
3424 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3425 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3426 &input,
3427 &config,
3428 &desc->mDevice,
3429 address,
3430 AUDIO_SOURCE_MIC,
3431 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003432
Eric Laurentcf2c0212014-07-25 16:20:43 -07003433 if (status == NO_ERROR) {
3434 desc->mSamplingRate = config.sample_rate;
3435 desc->mChannelMask = config.channel_mask;
3436 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003437
Eric Laurentd4692962014-05-05 18:13:44 -07003438 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003439 char *param = audio_device_address_to_parameter(device, address);
3440 mpClientInterface->setParameters(input, String8(param));
3441 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003442 }
3443
3444 // Here is where we step through and resolve any "dynamic" fields
3445 String8 reply;
3446 char *value;
3447 if (profile->mSamplingRates[0] == 0) {
3448 reply = mpClientInterface->getParameters(input,
3449 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3450 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3451 reply.string());
3452 value = strpbrk((char *)reply.string(), "=");
3453 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003454 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003455 }
3456 }
3457 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3458 reply = mpClientInterface->getParameters(input,
3459 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3460 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3461 value = strpbrk((char *)reply.string(), "=");
3462 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003463 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003464 }
3465 }
3466 if (profile->mChannelMasks[0] == 0) {
3467 reply = mpClientInterface->getParameters(input,
3468 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3469 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3470 reply.string());
3471 value = strpbrk((char *)reply.string(), "=");
3472 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003473 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003474 }
3475 }
3476 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3477 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3478 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3479 ALOGW("checkInputsForDevice() direct input missing param");
3480 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003481 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003482 }
3483
3484 if (input != 0) {
3485 addInput(input, desc);
3486 }
3487 } // endif input != 0
3488
Eric Laurentcf2c0212014-07-25 16:20:43 -07003489 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003490 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003491 profiles.removeAt(profile_index);
3492 profile_index--;
3493 } else {
3494 inputs.add(input);
3495 ALOGV("checkInputsForDevice(): adding input %d", input);
3496 }
3497 } // end scan profiles
3498
3499 if (profiles.isEmpty()) {
3500 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3501 return BAD_VALUE;
3502 }
3503 } else {
3504 // Disconnect
3505 // check if one opened input is not needed any more after disconnecting one device
3506 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3507 desc = mInputs.valueAt(input_index);
3508 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3509 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3510 mInputs.keyAt(input_index));
3511 inputs.add(mInputs.keyAt(input_index));
3512 }
3513 }
3514 // Clear any profiles associated with the disconnected device.
3515 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3516 if (mHwModules[module_index]->mHandle == 0) {
3517 continue;
3518 }
3519 for (size_t profile_index = 0;
3520 profile_index < mHwModules[module_index]->mInputProfiles.size();
3521 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003522 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003523 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003524 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003525 profile_index, module_index);
3526 if (profile->mSamplingRates[0] == 0) {
3527 profile->mSamplingRates.clear();
3528 profile->mSamplingRates.add(0);
3529 }
3530 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3531 profile->mFormats.clear();
3532 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3533 }
3534 if (profile->mChannelMasks[0] == 0) {
3535 profile->mChannelMasks.clear();
3536 profile->mChannelMasks.add(0);
3537 }
3538 }
3539 }
3540 }
3541 } // end disconnect
3542
3543 return NO_ERROR;
3544}
3545
3546
Eric Laurente0720872014-03-11 09:30:41 -07003547void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003548{
3549 ALOGV("closeOutput(%d)", output);
3550
Eric Laurent1f2f2232014-06-02 12:01:23 -07003551 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003552 if (outputDesc == NULL) {
3553 ALOGW("closeOutput() unknown output %d", output);
3554 return;
3555 }
3556
3557 // look for duplicated outputs connected to the output being removed.
3558 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003559 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003560 if (dupOutputDesc->isDuplicated() &&
3561 (dupOutputDesc->mOutput1 == outputDesc ||
3562 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003563 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003564 if (dupOutputDesc->mOutput1 == outputDesc) {
3565 outputDesc2 = dupOutputDesc->mOutput2;
3566 } else {
3567 outputDesc2 = dupOutputDesc->mOutput1;
3568 }
3569 // As all active tracks on duplicated output will be deleted,
3570 // and as they were also referenced on the other output, the reference
3571 // count for their stream type must be adjusted accordingly on
3572 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003573 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003574 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003575 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003576 }
3577 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3578 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3579
3580 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003581 mOutputs.removeItem(duplicatedOutput);
3582 }
3583 }
3584
Eric Laurent05b90f82014-08-27 15:32:29 -07003585 nextAudioPortGeneration();
3586
3587 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3588 if (index >= 0) {
3589 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3590 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3591 mAudioPatches.removeItemsAt(index);
3592 mpClientInterface->onAudioPatchListUpdate();
3593 }
3594
Eric Laurente552edb2014-03-10 17:42:56 -07003595 AudioParameter param;
3596 param.add(String8("closing"), String8("true"));
3597 mpClientInterface->setParameters(output, param.toString());
3598
3599 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003600 mOutputs.removeItem(output);
3601 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003602}
3603
3604void AudioPolicyManager::closeInput(audio_io_handle_t input)
3605{
3606 ALOGV("closeInput(%d)", input);
3607
3608 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3609 if (inputDesc == NULL) {
3610 ALOGW("closeInput() unknown input %d", input);
3611 return;
3612 }
3613
Eric Laurent6a94d692014-05-20 11:18:06 -07003614 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003615
3616 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3617 if (index >= 0) {
3618 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3619 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3620 mAudioPatches.removeItemsAt(index);
3621 mpClientInterface->onAudioPatchListUpdate();
3622 }
3623
3624 mpClientInterface->closeInput(input);
3625 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003626}
3627
Eric Laurente0720872014-03-11 09:30:41 -07003628SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003629 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003630{
3631 SortedVector<audio_io_handle_t> outputs;
3632
3633 ALOGVV("getOutputsForDevice() device %04x", device);
3634 for (size_t i = 0; i < openOutputs.size(); i++) {
3635 ALOGVV("output %d isDuplicated=%d device=%04x",
3636 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3637 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3638 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3639 outputs.add(openOutputs.keyAt(i));
3640 }
3641 }
3642 return outputs;
3643}
3644
Eric Laurente0720872014-03-11 09:30:41 -07003645bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003646 SortedVector<audio_io_handle_t>& outputs2)
3647{
3648 if (outputs1.size() != outputs2.size()) {
3649 return false;
3650 }
3651 for (size_t i = 0; i < outputs1.size(); i++) {
3652 if (outputs1[i] != outputs2[i]) {
3653 return false;
3654 }
3655 }
3656 return true;
3657}
3658
Eric Laurente0720872014-03-11 09:30:41 -07003659void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003660{
3661 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3662 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3663 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3664 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3665
3666 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3667 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3668 strategy, srcOutputs[0], dstOutputs[0]);
3669 // mute strategy while moving tracks from one output to another
3670 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003671 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003672 if (desc->isStrategyActive(strategy)) {
3673 setStrategyMute(strategy, true, srcOutputs[i]);
3674 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3675 }
3676 }
3677
3678 // Move effects associated to this strategy from previous output to new output
3679 if (strategy == STRATEGY_MEDIA) {
3680 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3681 SortedVector<audio_io_handle_t> moved;
3682 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003683 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3684 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3685 effectDesc->mIo != fxOutput) {
3686 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003687 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3688 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003689 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003690 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003691 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003692 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003693 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003694 }
3695 }
3696 }
3697 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003698 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3699 if (getStrategy((audio_stream_type_t)i) == strategy) {
3700 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003701 }
3702 }
3703 }
3704}
3705
Eric Laurente0720872014-03-11 09:30:41 -07003706void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003707{
Jon Eklund966095e2014-09-09 15:39:49 -05003708 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3709 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003710 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003711 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3712 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003713 checkOutputForStrategy(STRATEGY_SONIFICATION);
3714 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3715 checkOutputForStrategy(STRATEGY_MEDIA);
3716 checkOutputForStrategy(STRATEGY_DTMF);
3717}
3718
Eric Laurente0720872014-03-11 09:30:41 -07003719audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003720{
Eric Laurente552edb2014-03-10 17:42:56 -07003721 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003722 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003723 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3724 return mOutputs.keyAt(i);
3725 }
3726 }
3727
3728 return 0;
3729}
3730
Eric Laurente0720872014-03-11 09:30:41 -07003731void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003732{
Eric Laurente552edb2014-03-10 17:42:56 -07003733 audio_io_handle_t a2dpOutput = getA2dpOutput();
3734 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003735 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003736 return;
3737 }
3738
Eric Laurent3a4311c2014-03-17 12:00:47 -07003739 bool isScoConnected =
3740 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003741 // suspend A2DP output if:
3742 // (NOT already suspended) &&
3743 // ((SCO device is connected &&
3744 // (forced usage for communication || for record is SCO))) ||
3745 // (phone state is ringing || in call)
3746 //
3747 // restore A2DP output if:
3748 // (Already suspended) &&
3749 // ((SCO device is NOT connected ||
3750 // (forced usage NOT for communication && NOT for record is SCO))) &&
3751 // (phone state is NOT ringing && NOT in call)
3752 //
3753 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003754 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003755 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3756 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3757 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3758 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003759
3760 mpClientInterface->restoreOutput(a2dpOutput);
3761 mA2dpSuspended = false;
3762 }
3763 } else {
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->suspendOutput(a2dpOutput);
3771 mA2dpSuspended = true;
3772 }
3773 }
3774}
3775
Eric Laurent1c333e22014-05-20 10:48:17 -07003776audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003777{
3778 audio_devices_t device = AUDIO_DEVICE_NONE;
3779
Eric Laurent1f2f2232014-06-02 12:01:23 -07003780 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003781
3782 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3783 if (index >= 0) {
3784 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3785 if (patchDesc->mUid != mUidCached) {
3786 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3787 outputDesc->device(), outputDesc->mPatchHandle);
3788 return outputDesc->device();
3789 }
3790 }
3791
Eric Laurente552edb2014-03-10 17:42:56 -07003792 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003793 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003794 // use device for strategy enforced audible
3795 // 2: we are in call or the strategy phone is active on the output:
3796 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003797 // 3: the strategy for enforced audible is active but not enforced on the output:
3798 // use the device for strategy enforced audible
3799 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003800 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003801 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003802 // use device for strategy "respectful" sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003803 // 6: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003804 // use device for strategy media
Jon Eklund966095e2014-09-09 15:39:49 -05003805 // 7: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003806 // use device for strategy DTMF
Jon Eklund966095e2014-09-09 15:39:49 -05003807 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3808 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003809 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3810 } else if (isInCall() ||
3811 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3812 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003813 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3814 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003815 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3816 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3817 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3818 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3819 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3820 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3821 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3822 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3823 }
3824
Eric Laurent1c333e22014-05-20 10:48:17 -07003825 ALOGV("getNewOutputDevice() selected device %x", device);
3826 return device;
3827}
3828
3829audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3830{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003831 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003832
3833 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3834 if (index >= 0) {
3835 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3836 if (patchDesc->mUid != mUidCached) {
3837 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3838 inputDesc->mDevice, inputDesc->mPatchHandle);
3839 return inputDesc->mDevice;
3840 }
3841 }
3842
Eric Laurent1c333e22014-05-20 10:48:17 -07003843 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3844
3845 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003846 return device;
3847}
3848
Eric Laurente0720872014-03-11 09:30:41 -07003849uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003850 return (uint32_t)getStrategy(stream);
3851}
3852
Eric Laurente0720872014-03-11 09:30:41 -07003853audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003854 // By checking the range of stream before calling getStrategy, we avoid
3855 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3856 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003857 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003858 return AUDIO_DEVICE_NONE;
3859 }
3860 audio_devices_t devices;
3861 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3862 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3863 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3864 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003865 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003866 if (outputDesc->isStrategyActive(strategy)) {
3867 devices = outputDesc->device();
3868 break;
3869 }
Eric Laurente552edb2014-03-10 17:42:56 -07003870 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003871
3872 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
3873 and doesn't really need to.*/
3874 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
3875 devices |= AUDIO_DEVICE_OUT_SPEAKER;
3876 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3877 }
3878
Eric Laurente552edb2014-03-10 17:42:56 -07003879 return devices;
3880}
3881
Eric Laurente0720872014-03-11 09:30:41 -07003882AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003883 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003884 // stream to strategy mapping
3885 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003886 case AUDIO_STREAM_VOICE_CALL:
3887 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003888 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003889 case AUDIO_STREAM_RING:
3890 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003891 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003892 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003893 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003894 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003895 return STRATEGY_DTMF;
3896 default:
3897 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003898 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003899 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3900 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003901 case AUDIO_STREAM_TTS:
3902 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003903 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003904 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003905 return STRATEGY_ENFORCED_AUDIBLE;
3906 }
3907}
3908
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003909uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3910 // flags to strategy mapping
3911 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3912 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3913 }
3914
3915 // usage to strategy mapping
3916 switch (attr->usage) {
3917 case AUDIO_USAGE_MEDIA:
3918 case AUDIO_USAGE_GAME:
3919 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3920 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3921 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3922 return (uint32_t) STRATEGY_MEDIA;
3923
3924 case AUDIO_USAGE_VOICE_COMMUNICATION:
3925 return (uint32_t) STRATEGY_PHONE;
3926
3927 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3928 return (uint32_t) STRATEGY_DTMF;
3929
3930 case AUDIO_USAGE_ALARM:
3931 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3932 return (uint32_t) STRATEGY_SONIFICATION;
3933
3934 case AUDIO_USAGE_NOTIFICATION:
3935 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3936 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3937 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3938 case AUDIO_USAGE_NOTIFICATION_EVENT:
3939 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3940
3941 case AUDIO_USAGE_UNKNOWN:
3942 default:
3943 return (uint32_t) STRATEGY_MEDIA;
3944 }
3945}
3946
Eric Laurente0720872014-03-11 09:30:41 -07003947void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003948 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003949 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003950 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3951 updateDevicesAndOutputs();
3952 break;
3953 default:
3954 break;
3955 }
3956}
3957
Eric Laurente0720872014-03-11 09:30:41 -07003958audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003959 bool fromCache)
3960{
3961 uint32_t device = AUDIO_DEVICE_NONE;
3962
3963 if (fromCache) {
3964 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3965 strategy, mDeviceForStrategy[strategy]);
3966 return mDeviceForStrategy[strategy];
3967 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003968 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003969 switch (strategy) {
3970
3971 case STRATEGY_SONIFICATION_RESPECTFUL:
3972 if (isInCall()) {
3973 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003974 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003975 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3976 // while media is playing on a remote device, use the the sonification behavior.
3977 // Note that we test this usecase before testing if media is playing because
3978 // the isStreamActive() method only informs about the activity of a stream, not
3979 // if it's for local playback. Note also that we use the same delay between both tests
3980 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05003981 //user "safe" speaker if available instead of normal speaker to avoid triggering
3982 //other acoustic safety mechanisms for notification
3983 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
3984 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003985 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003986 // while media is playing (or has recently played), use the same device
3987 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3988 } else {
3989 // when media is not playing anymore, fall back on the sonification behavior
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 Laurente552edb2014-03-10 17:42:56 -07003995 }
3996
3997 break;
3998
3999 case STRATEGY_DTMF:
4000 if (!isInCall()) {
4001 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4002 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4003 break;
4004 }
4005 // when in call, DTMF and PHONE strategies follow the same rules
4006 // FALL THROUGH
4007
4008 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004009 // Force use of only devices on primary output if:
4010 // - in call AND
4011 // - cannot route from voice call RX OR
4012 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4013 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4014 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4015 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4016 if (((mAvailableInputDevices.types() &
4017 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4018 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004019 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004020 AUDIO_DEVICE_API_VERSION_3_0))) {
4021 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4022 }
4023 }
Eric Laurente552edb2014-03-10 17:42:56 -07004024 // for phone strategy, we first consider the forced use and then the available devices by order
4025 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004026 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4027 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004028 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004029 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004030 if (device) break;
4031 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004032 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004033 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004034 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004035 if (device) break;
4036 // if SCO device is requested but no SCO device is available, fall back to default case
4037 // FALL THROUGH
4038
4039 default: // FORCE_NONE
4040 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004041 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004042 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004043 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004044 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004045 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004046 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004047 if (device) break;
4048 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004049 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004050 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004051 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004052 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004053 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4054 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004055 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004056 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004057 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004058 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004059 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004060 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004061 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004062 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004063 if (device) break;
4064 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004065 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004066 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004067 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004068 if (device == AUDIO_DEVICE_NONE) {
4069 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4070 }
4071 break;
4072
Eric Laurent3b73df72014-03-11 09:06:29 -07004073 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004074 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4075 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004076 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004077 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004078 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004079 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004080 if (device) break;
4081 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004082 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004083 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004084 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004085 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004086 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004087 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004088 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004089 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004090 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004091 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004092 if (device) break;
4093 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004094 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4095 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004096 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004097 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004098 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004099 if (device == AUDIO_DEVICE_NONE) {
4100 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4101 }
4102 break;
4103 }
4104 break;
4105
4106 case STRATEGY_SONIFICATION:
4107
4108 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4109 // handleIncallSonification().
4110 if (isInCall()) {
4111 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4112 break;
4113 }
4114 // FALL THROUGH
4115
4116 case STRATEGY_ENFORCED_AUDIBLE:
4117 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4118 // except:
4119 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4120 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4121
4122 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004123 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004124 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004125 if (device == AUDIO_DEVICE_NONE) {
4126 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4127 }
4128 }
4129 // The second device used for sonification is the same as the device used by media strategy
4130 // FALL THROUGH
4131
4132 case STRATEGY_MEDIA: {
4133 uint32_t device2 = AUDIO_DEVICE_NONE;
4134 if (strategy != STRATEGY_SONIFICATION) {
4135 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004136 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004137 }
4138 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004139 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004140 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004141 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004142 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004143 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004144 }
4145 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004146 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004147 }
4148 }
4149 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004150 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004151 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004152 if ((device2 == AUDIO_DEVICE_NONE)) {
4153 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4154 }
Eric Laurente552edb2014-03-10 17:42:56 -07004155 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004156 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004157 }
4158 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004159 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004160 }
4161 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004162 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004163 }
4164 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004165 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004166 }
4167 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4168 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004169 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004170 }
4171 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004172 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004173 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004174 }
4175 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004176 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004177 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004178 int device3 = AUDIO_DEVICE_NONE;
4179 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004180 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004181 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4182 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004183 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004184 }
Eric Laurente552edb2014-03-10 17:42:56 -07004185
Jungshik Jang839e4f32014-06-26 17:23:40 +09004186 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004187 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4188 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4189 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004190
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004191 // If hdmi system audio mode is on, remove speaker out of output list.
4192 if ((strategy == STRATEGY_MEDIA) &&
4193 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4194 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4195 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4196 }
4197
Eric Laurente552edb2014-03-10 17:42:56 -07004198 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004199 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004200 if (device == AUDIO_DEVICE_NONE) {
4201 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4202 }
4203 } break;
4204
4205 default:
4206 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4207 break;
4208 }
4209
4210 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4211 return device;
4212}
4213
Eric Laurente0720872014-03-11 09:30:41 -07004214void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004215{
4216 for (int i = 0; i < NUM_STRATEGIES; i++) {
4217 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4218 }
4219 mPreviousOutputs = mOutputs;
4220}
4221
Eric Laurent1f2f2232014-06-02 12:01:23 -07004222uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004223 audio_devices_t prevDevice,
4224 uint32_t delayMs)
4225{
4226 // mute/unmute strategies using an incompatible device combination
4227 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4228 // if unmuting, unmute only after the specified delay
4229 if (outputDesc->isDuplicated()) {
4230 return 0;
4231 }
4232
4233 uint32_t muteWaitMs = 0;
4234 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004235 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004236
4237 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4238 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4239 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4240 bool doMute = false;
4241
4242 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4243 doMute = true;
4244 outputDesc->mStrategyMutedByDevice[i] = true;
4245 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4246 doMute = true;
4247 outputDesc->mStrategyMutedByDevice[i] = false;
4248 }
Eric Laurent99401132014-05-07 19:48:15 -07004249 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004250 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004251 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004252 // skip output if it does not share any device with current output
4253 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4254 == AUDIO_DEVICE_NONE) {
4255 continue;
4256 }
4257 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4258 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4259 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4260 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4261 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004262 if (mute) {
4263 // FIXME: should not need to double latency if volume could be applied
4264 // immediately by the audioflinger mixer. We must account for the delay
4265 // between now and the next time the audioflinger thread for this output
4266 // will process a buffer (which corresponds to one buffer size,
4267 // usually 1/2 or 1/4 of the latency).
4268 if (muteWaitMs < desc->latency() * 2) {
4269 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004270 }
4271 }
4272 }
4273 }
4274 }
4275 }
4276
Eric Laurent99401132014-05-07 19:48:15 -07004277 // temporary mute output if device selection changes to avoid volume bursts due to
4278 // different per device volumes
4279 if (outputDesc->isActive() && (device != prevDevice)) {
4280 if (muteWaitMs < outputDesc->latency() * 2) {
4281 muteWaitMs = outputDesc->latency() * 2;
4282 }
4283 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4284 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004285 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004286 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004287 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004288 muteWaitMs *2, device);
4289 }
4290 }
4291 }
4292
Eric Laurente552edb2014-03-10 17:42:56 -07004293 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4294 if (muteWaitMs > delayMs) {
4295 muteWaitMs -= delayMs;
4296 usleep(muteWaitMs * 1000);
4297 return muteWaitMs;
4298 }
4299 return 0;
4300}
4301
Eric Laurente0720872014-03-11 09:30:41 -07004302uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004303 audio_devices_t device,
4304 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004305 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004306 audio_patch_handle_t *patchHandle,
4307 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004308{
4309 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004310 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004311 AudioParameter param;
4312 uint32_t muteWaitMs;
4313
4314 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004315 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4316 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004317 return muteWaitMs;
4318 }
4319 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4320 // output profile
4321 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004322 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004323 return 0;
4324 }
4325
4326 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004327 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004328
4329 audio_devices_t prevDevice = outputDesc->mDevice;
4330
4331 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4332
4333 if (device != AUDIO_DEVICE_NONE) {
4334 outputDesc->mDevice = device;
4335 }
4336 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4337
4338 // Do not change the routing if:
4339 // - the requested device is AUDIO_DEVICE_NONE
4340 // - the requested device is the same as current device and force is not specified.
4341 // Doing this check here allows the caller to call setOutputDevice() without conditions
4342 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4343 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4344 return muteWaitMs;
4345 }
4346
4347 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004348
Eric Laurente552edb2014-03-10 17:42:56 -07004349 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004350 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004351 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004352 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004353 DeviceVector deviceList = (address == NULL) ?
4354 mAvailableOutputDevices.getDevicesFromType(device)
4355 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004356 if (!deviceList.isEmpty()) {
4357 struct audio_patch patch;
4358 outputDesc->toAudioPortConfig(&patch.sources[0]);
4359 patch.num_sources = 1;
4360 patch.num_sinks = 0;
4361 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4362 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004363 patch.num_sinks++;
4364 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004365 ssize_t index;
4366 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4367 index = mAudioPatches.indexOfKey(*patchHandle);
4368 } else {
4369 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4370 }
4371 sp< AudioPatch> patchDesc;
4372 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4373 if (index >= 0) {
4374 patchDesc = mAudioPatches.valueAt(index);
4375 afPatchHandle = patchDesc->mAfPatchHandle;
4376 }
4377
Eric Laurent1c333e22014-05-20 10:48:17 -07004378 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004379 &afPatchHandle,
4380 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004381 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4382 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004383 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004384 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004385 if (index < 0) {
4386 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4387 &patch, mUidCached);
4388 addAudioPatch(patchDesc->mHandle, patchDesc);
4389 } else {
4390 patchDesc->mPatch = patch;
4391 }
4392 patchDesc->mAfPatchHandle = afPatchHandle;
4393 patchDesc->mUid = mUidCached;
4394 if (patchHandle) {
4395 *patchHandle = patchDesc->mHandle;
4396 }
4397 outputDesc->mPatchHandle = patchDesc->mHandle;
4398 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004399 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004400 }
4401 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004402
4403 // inform all input as well
4404 for (size_t i = 0; i < mInputs.size(); i++) {
4405 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4406 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4407 AudioParameter inputCmd = AudioParameter();
4408 ALOGV("%s: inform input %d of device:%d", __func__,
4409 inputDescriptor->mIoHandle, device);
4410 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4411 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4412 inputCmd.toString(),
4413 delayMs);
4414 }
4415 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004416 }
Eric Laurente552edb2014-03-10 17:42:56 -07004417
4418 // update stream volumes according to new device
4419 applyStreamVolumes(output, device, delayMs);
4420
4421 return muteWaitMs;
4422}
4423
Eric Laurent1c333e22014-05-20 10:48:17 -07004424status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004425 int delayMs,
4426 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004427{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004428 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004429 ssize_t index;
4430 if (patchHandle) {
4431 index = mAudioPatches.indexOfKey(*patchHandle);
4432 } else {
4433 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4434 }
4435 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004436 return INVALID_OPERATION;
4437 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004438 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4439 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004440 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4441 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004442 removeAudioPatch(patchDesc->mHandle);
4443 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004444 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004445 return status;
4446}
4447
4448status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4449 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004450 bool force,
4451 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004452{
4453 status_t status = NO_ERROR;
4454
Eric Laurent1f2f2232014-06-02 12:01:23 -07004455 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004456 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4457 inputDesc->mDevice = device;
4458
4459 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4460 if (!deviceList.isEmpty()) {
4461 struct audio_patch patch;
4462 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004463 // AUDIO_SOURCE_HOTWORD is for internal use only:
4464 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004465 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4466 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004467 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4468 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004469 patch.num_sinks = 1;
4470 //only one input device for now
4471 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004472 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004473 ssize_t index;
4474 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4475 index = mAudioPatches.indexOfKey(*patchHandle);
4476 } else {
4477 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4478 }
4479 sp< AudioPatch> patchDesc;
4480 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4481 if (index >= 0) {
4482 patchDesc = mAudioPatches.valueAt(index);
4483 afPatchHandle = patchDesc->mAfPatchHandle;
4484 }
4485
Eric Laurent1c333e22014-05-20 10:48:17 -07004486 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004487 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004488 0);
4489 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004490 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004491 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004492 if (index < 0) {
4493 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4494 &patch, mUidCached);
4495 addAudioPatch(patchDesc->mHandle, patchDesc);
4496 } else {
4497 patchDesc->mPatch = patch;
4498 }
4499 patchDesc->mAfPatchHandle = afPatchHandle;
4500 patchDesc->mUid = mUidCached;
4501 if (patchHandle) {
4502 *patchHandle = patchDesc->mHandle;
4503 }
4504 inputDesc->mPatchHandle = patchDesc->mHandle;
4505 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004506 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004507 }
4508 }
4509 }
4510 return status;
4511}
4512
Eric Laurent6a94d692014-05-20 11:18:06 -07004513status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4514 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004515{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004516 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004517 ssize_t index;
4518 if (patchHandle) {
4519 index = mAudioPatches.indexOfKey(*patchHandle);
4520 } else {
4521 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4522 }
4523 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004524 return INVALID_OPERATION;
4525 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004526 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4527 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004528 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4529 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004530 removeAudioPatch(patchDesc->mHandle);
4531 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004532 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004533 return status;
4534}
4535
4536sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004537 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004538 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004539 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004540 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004541{
4542 // Choose an input profile based on the requested capture parameters: select the first available
4543 // profile supporting all requested parameters.
4544
4545 for (size_t i = 0; i < mHwModules.size(); i++)
4546 {
4547 if (mHwModules[i]->mHandle == 0) {
4548 continue;
4549 }
4550 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4551 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004552 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004553 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004554 if (profile->isCompatibleProfile(device, samplingRate,
4555 &samplingRate /*updatedSamplingRate*/,
4556 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004557 return profile;
4558 }
4559 }
4560 }
4561 return NULL;
4562}
4563
Eric Laurente0720872014-03-11 09:30:41 -07004564audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004565{
4566 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004567 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4568 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004569 switch (inputSource) {
4570 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004571 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004572 device = AUDIO_DEVICE_IN_VOICE_CALL;
4573 break;
4574 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004575 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004576
4577 case AUDIO_SOURCE_DEFAULT:
4578 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004579 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4580 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004581 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4582 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4583 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4584 device = AUDIO_DEVICE_IN_USB_DEVICE;
4585 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4586 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004587 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004588 break;
4589
4590 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4591 // Allow only use of devices on primary input if in call and HAL does not support routing
4592 // to voice call path.
4593 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4594 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4595 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4596 }
4597
4598 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4599 case AUDIO_POLICY_FORCE_BT_SCO:
4600 // if SCO device is requested but no SCO device is available, fall back to default case
4601 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4602 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4603 break;
4604 }
4605 // FALL THROUGH
4606
4607 default: // FORCE_NONE
4608 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4609 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4610 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4611 device = AUDIO_DEVICE_IN_USB_DEVICE;
4612 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4613 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4614 }
4615 break;
4616
4617 case AUDIO_POLICY_FORCE_SPEAKER:
4618 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4619 device = AUDIO_DEVICE_IN_BACK_MIC;
4620 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4621 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4622 }
4623 break;
4624 }
4625 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004626
Eric Laurente552edb2014-03-10 17:42:56 -07004627 case AUDIO_SOURCE_VOICE_RECOGNITION:
4628 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004629 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004630 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004631 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004632 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004633 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004634 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4635 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004636 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004637 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4638 }
4639 break;
4640 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004641 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004642 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004643 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004644 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4645 }
4646 break;
4647 case AUDIO_SOURCE_VOICE_DOWNLINK:
4648 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004649 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004650 device = AUDIO_DEVICE_IN_VOICE_CALL;
4651 }
4652 break;
4653 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004654 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004655 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4656 }
4657 break;
4658 default:
4659 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4660 break;
4661 }
4662 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4663 return device;
4664}
4665
Eric Laurente0720872014-03-11 09:30:41 -07004666bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004667{
4668 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4669 device &= ~AUDIO_DEVICE_BIT_IN;
4670 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4671 return true;
4672 }
4673 return false;
4674}
4675
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004676bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4677 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4678}
4679
Eric Laurente0720872014-03-11 09:30:41 -07004680audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004681{
4682 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004683 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004684 if ((input_descriptor->mRefCount > 0)
4685 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4686 return mInputs.keyAt(i);
4687 }
4688 }
4689 return 0;
4690}
4691
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004692uint32_t AudioPolicyManager::activeInputsCount() const
4693{
4694 uint32_t count = 0;
4695 for (size_t i = 0; i < mInputs.size(); i++) {
4696 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4697 if (desc->mRefCount > 0) {
4698 return count++;
4699 }
4700 }
4701 return count;
4702}
4703
Eric Laurente552edb2014-03-10 17:42:56 -07004704
Eric Laurente0720872014-03-11 09:30:41 -07004705audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004706{
4707 if (device == AUDIO_DEVICE_NONE) {
4708 // this happens when forcing a route update and no track is active on an output.
4709 // In this case the returned category is not important.
4710 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004711 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004712 // Multiple device selection is either:
4713 // - speaker + one other device: give priority to speaker in this case.
4714 // - one A2DP device + another device: happens with duplicated output. In this case
4715 // retain the device on the A2DP output as the other must not correspond to an active
4716 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004717 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004718 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4719 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004720 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4721 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4722 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4723 device = AUDIO_DEVICE_OUT_AUX_LINE;
4724 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4725 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004726 } else {
4727 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4728 }
4729 }
4730
Jon Eklund11c9fb12014-06-23 14:47:03 -05004731 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4732 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4733 device = AUDIO_DEVICE_OUT_SPEAKER;
4734
Eric Laurent3b73df72014-03-11 09:06:29 -07004735 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004736 "getDeviceForVolume() invalid device combination: %08x",
4737 device);
4738
4739 return device;
4740}
4741
Eric Laurente0720872014-03-11 09:30:41 -07004742AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004743{
4744 switch(getDeviceForVolume(device)) {
4745 case AUDIO_DEVICE_OUT_EARPIECE:
4746 return DEVICE_CATEGORY_EARPIECE;
4747 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4748 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4749 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4750 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4751 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4752 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4753 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004754 case AUDIO_DEVICE_OUT_LINE:
4755 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4756 /*USB? Remote submix?*/
4757 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004758 case AUDIO_DEVICE_OUT_SPEAKER:
4759 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4760 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004761 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4762 case AUDIO_DEVICE_OUT_USB_DEVICE:
4763 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4764 default:
4765 return DEVICE_CATEGORY_SPEAKER;
4766 }
4767}
4768
Eric Laurente0720872014-03-11 09:30:41 -07004769float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004770 int indexInUi)
4771{
4772 device_category deviceCategory = getDeviceCategory(device);
4773 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4774
4775 // the volume index in the UI is relative to the min and max volume indices for this stream type
4776 int nbSteps = 1 + curve[VOLMAX].mIndex -
4777 curve[VOLMIN].mIndex;
4778 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4779 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4780
4781 // find what part of the curve this index volume belongs to, or if it's out of bounds
4782 int segment = 0;
4783 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4784 return 0.0f;
4785 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4786 segment = 0;
4787 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4788 segment = 1;
4789 } else if (volIdx <= curve[VOLMAX].mIndex) {
4790 segment = 2;
4791 } else { // out of bounds
4792 return 1.0f;
4793 }
4794
4795 // linear interpolation in the attenuation table in dB
4796 float decibels = curve[segment].mDBAttenuation +
4797 ((float)(volIdx - curve[segment].mIndex)) *
4798 ( (curve[segment+1].mDBAttenuation -
4799 curve[segment].mDBAttenuation) /
4800 ((float)(curve[segment+1].mIndex -
4801 curve[segment].mIndex)) );
4802
4803 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4804
4805 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4806 curve[segment].mIndex, volIdx,
4807 curve[segment+1].mIndex,
4808 curve[segment].mDBAttenuation,
4809 decibels,
4810 curve[segment+1].mDBAttenuation,
4811 amplification);
4812
4813 return amplification;
4814}
4815
Eric Laurente0720872014-03-11 09:30:41 -07004816const AudioPolicyManager::VolumeCurvePoint
4817 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004818 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4819};
4820
Eric Laurente0720872014-03-11 09:30:41 -07004821const AudioPolicyManager::VolumeCurvePoint
4822 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004823 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4824};
4825
Eric Laurente0720872014-03-11 09:30:41 -07004826const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004827 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4828 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4829};
4830
4831const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004832 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004833 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4834};
4835
Eric Laurente0720872014-03-11 09:30:41 -07004836const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004837 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004838 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004839};
4840
4841const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004842 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004843 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4844};
4845
Eric Laurente0720872014-03-11 09:30:41 -07004846const AudioPolicyManager::VolumeCurvePoint
4847 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004848 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4849};
4850
4851// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4852// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4853// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4854// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4855
Eric Laurente0720872014-03-11 09:30:41 -07004856const AudioPolicyManager::VolumeCurvePoint
4857 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004858 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4859};
4860
Eric Laurente0720872014-03-11 09:30:41 -07004861const AudioPolicyManager::VolumeCurvePoint
4862 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004863 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4864};
4865
Eric Laurente0720872014-03-11 09:30:41 -07004866const AudioPolicyManager::VolumeCurvePoint
4867 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004868 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4869};
4870
Eric Laurente0720872014-03-11 09:30:41 -07004871const AudioPolicyManager::VolumeCurvePoint
4872 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004873 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4874};
4875
Eric Laurente0720872014-03-11 09:30:41 -07004876const AudioPolicyManager::VolumeCurvePoint
4877 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004878 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4879};
4880
Eric Laurente0720872014-03-11 09:30:41 -07004881const AudioPolicyManager::VolumeCurvePoint
4882 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4883 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004884 { // AUDIO_STREAM_VOICE_CALL
4885 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4886 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004887 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4888 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004889 },
4890 { // AUDIO_STREAM_SYSTEM
4891 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4892 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004893 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4894 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004895 },
4896 { // AUDIO_STREAM_RING
4897 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4898 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004899 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4900 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004901 },
4902 { // AUDIO_STREAM_MUSIC
4903 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4904 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004905 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4906 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004907 },
4908 { // AUDIO_STREAM_ALARM
4909 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4910 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004911 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4912 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004913 },
4914 { // AUDIO_STREAM_NOTIFICATION
4915 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4916 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004917 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4918 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004919 },
4920 { // AUDIO_STREAM_BLUETOOTH_SCO
4921 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4922 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004923 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4924 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004925 },
4926 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4927 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4928 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004929 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4930 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004931 },
4932 { // AUDIO_STREAM_DTMF
4933 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4934 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004935 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4936 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004937 },
4938 { // AUDIO_STREAM_TTS
4939 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4940 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004941 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4942 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004943 },
4944};
4945
Eric Laurente0720872014-03-11 09:30:41 -07004946void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004947{
4948 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4949 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4950 mStreams[i].mVolumeCurve[j] =
4951 sVolumeProfiles[i][j];
4952 }
4953 }
4954
4955 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4956 if (mSpeakerDrcEnabled) {
4957 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4958 sDefaultSystemVolumeCurveDrc;
4959 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4960 sSpeakerSonificationVolumeCurveDrc;
4961 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4962 sSpeakerSonificationVolumeCurveDrc;
4963 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4964 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004965 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4966 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004967 }
4968}
4969
Eric Laurente0720872014-03-11 09:30:41 -07004970float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004971 int index,
4972 audio_io_handle_t output,
4973 audio_devices_t device)
4974{
4975 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004976 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004977 StreamDescriptor &streamDesc = mStreams[stream];
4978
4979 if (device == AUDIO_DEVICE_NONE) {
4980 device = outputDesc->device();
4981 }
4982
Eric Laurente552edb2014-03-10 17:42:56 -07004983 volume = volIndexToAmpl(device, streamDesc, index);
4984
4985 // if a headset is connected, apply the following rules to ring tones and notifications
4986 // to avoid sound level bursts in user's ears:
4987 // - always attenuate ring tones and notifications volume by 6dB
4988 // - if music is playing, always limit the volume to current music volume,
4989 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004990 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004991 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4992 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4993 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4994 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4995 ((stream_strategy == STRATEGY_SONIFICATION)
4996 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004997 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004998 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004999 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005000 streamDesc.mCanBeMuted) {
5001 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5002 // when the phone is ringing we must consider that music could have been paused just before
5003 // by the music application and behave as if music was active if the last music track was
5004 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005005 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005006 mLimitRingtoneVolume) {
5007 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005008 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5009 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005010 output,
5011 musicDevice);
5012 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5013 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5014 if (volume > minVol) {
5015 volume = minVol;
5016 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5017 }
5018 }
5019 }
5020
5021 return volume;
5022}
5023
Eric Laurente0720872014-03-11 09:30:41 -07005024status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005025 int index,
5026 audio_io_handle_t output,
5027 audio_devices_t device,
5028 int delayMs,
5029 bool force)
5030{
5031
5032 // do not change actual stream volume if the stream is muted
5033 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5034 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5035 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5036 return NO_ERROR;
5037 }
5038
5039 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005040 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5041 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5042 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5043 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005044 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005045 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005046 return INVALID_OPERATION;
5047 }
5048
5049 float volume = computeVolume(stream, index, output, device);
5050 // We actually change the volume if:
5051 // - the float value returned by computeVolume() changed
5052 // - the force flag is set
5053 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5054 force) {
5055 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5056 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5057 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5058 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005059 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5060 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005061 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005062 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005063 }
5064
Eric Laurent3b73df72014-03-11 09:06:29 -07005065 if (stream == AUDIO_STREAM_VOICE_CALL ||
5066 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005067 float voiceVolume;
5068 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005069 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005070 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5071 } else {
5072 voiceVolume = 1.0;
5073 }
5074
5075 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5076 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5077 mLastVoiceVolume = voiceVolume;
5078 }
5079 }
5080
5081 return NO_ERROR;
5082}
5083
Eric Laurente0720872014-03-11 09:30:41 -07005084void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005085 audio_devices_t device,
5086 int delayMs,
5087 bool force)
5088{
5089 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5090
Eric Laurent3b73df72014-03-11 09:06:29 -07005091 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5092 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005093 mStreams[stream].getVolumeIndex(device),
5094 output,
5095 device,
5096 delayMs,
5097 force);
5098 }
5099}
5100
Eric Laurente0720872014-03-11 09:30:41 -07005101void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005102 bool on,
5103 audio_io_handle_t output,
5104 int delayMs,
5105 audio_devices_t device)
5106{
5107 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005108 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5109 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5110 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005111 }
5112 }
5113}
5114
Eric Laurente0720872014-03-11 09:30:41 -07005115void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005116 bool on,
5117 audio_io_handle_t output,
5118 int delayMs,
5119 audio_devices_t device)
5120{
5121 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005122 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005123 if (device == AUDIO_DEVICE_NONE) {
5124 device = outputDesc->device();
5125 }
5126
5127 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5128 stream, on, output, outputDesc->mMuteCount[stream], device);
5129
5130 if (on) {
5131 if (outputDesc->mMuteCount[stream] == 0) {
5132 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005133 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5134 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005135 checkAndSetVolume(stream, 0, output, device, delayMs);
5136 }
5137 }
5138 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5139 outputDesc->mMuteCount[stream]++;
5140 } else {
5141 if (outputDesc->mMuteCount[stream] == 0) {
5142 ALOGV("setStreamMute() unmuting non muted stream!");
5143 return;
5144 }
5145 if (--outputDesc->mMuteCount[stream] == 0) {
5146 checkAndSetVolume(stream,
5147 streamDesc.getVolumeIndex(device),
5148 output,
5149 device,
5150 delayMs);
5151 }
5152 }
5153}
5154
Eric Laurente0720872014-03-11 09:30:41 -07005155void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005156 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005157{
5158 // if the stream pertains to sonification strategy and we are in call we must
5159 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5160 // in the device used for phone strategy and play the tone if the selected device does not
5161 // interfere with the device used for phone strategy
5162 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5163 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005164 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005165 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5166 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005167 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005168 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5169 stream, starting, outputDesc->mDevice, stateChange);
5170 if (outputDesc->mRefCount[stream]) {
5171 int muteCount = 1;
5172 if (stateChange) {
5173 muteCount = outputDesc->mRefCount[stream];
5174 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005175 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005176 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5177 for (int i = 0; i < muteCount; i++) {
5178 setStreamMute(stream, starting, mPrimaryOutput);
5179 }
5180 } else {
5181 ALOGV("handleIncallSonification() high visibility");
5182 if (outputDesc->device() &
5183 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5184 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5185 for (int i = 0; i < muteCount; i++) {
5186 setStreamMute(stream, starting, mPrimaryOutput);
5187 }
5188 }
5189 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005190 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5191 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005192 } else {
5193 mpClientInterface->stopTone();
5194 }
5195 }
5196 }
5197 }
5198}
5199
Eric Laurente0720872014-03-11 09:30:41 -07005200bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005201{
5202 return isStateInCall(mPhoneState);
5203}
5204
Eric Laurente0720872014-03-11 09:30:41 -07005205bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005206 return ((state == AUDIO_MODE_IN_CALL) ||
5207 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005208}
5209
Eric Laurente0720872014-03-11 09:30:41 -07005210uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005211{
5212 return MAX_EFFECTS_CPU_LOAD;
5213}
5214
Eric Laurente0720872014-03-11 09:30:41 -07005215uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005216{
5217 return MAX_EFFECTS_MEMORY;
5218}
5219
Eric Laurent6a94d692014-05-20 11:18:06 -07005220
Eric Laurente552edb2014-03-10 17:42:56 -07005221// --- AudioOutputDescriptor class implementation
5222
Eric Laurente0720872014-03-11 09:30:41 -07005223AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005224 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005225 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005226 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005227 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5228{
5229 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005230 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005231 mRefCount[i] = 0;
5232 mCurVolume[i] = -1.0;
5233 mMuteCount[i] = 0;
5234 mStopTime[i] = 0;
5235 }
5236 for (int i = 0; i < NUM_STRATEGIES; i++) {
5237 mStrategyMutedByDevice[i] = false;
5238 }
5239 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005240 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005241 mSamplingRate = profile->pickSamplingRate();
5242 mFormat = profile->pickFormat();
5243 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005244 if (profile->mGains.size() > 0) {
5245 profile->mGains[0]->getDefaultConfig(&mGain);
5246 }
Eric Laurente552edb2014-03-10 17:42:56 -07005247 }
5248}
5249
Eric Laurente0720872014-03-11 09:30:41 -07005250audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005251{
5252 if (isDuplicated()) {
5253 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5254 } else {
5255 return mDevice;
5256 }
5257}
5258
Eric Laurente0720872014-03-11 09:30:41 -07005259uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005260{
5261 if (isDuplicated()) {
5262 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5263 } else {
5264 return mLatency;
5265 }
5266}
5267
Eric Laurente0720872014-03-11 09:30:41 -07005268bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005269 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005270{
5271 if (isDuplicated()) {
5272 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5273 } else if (outputDesc->isDuplicated()){
5274 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5275 } else {
5276 return (mProfile->mModule == outputDesc->mProfile->mModule);
5277 }
5278}
5279
Eric Laurente0720872014-03-11 09:30:41 -07005280void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005281 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005282{
5283 // forward usage count change to attached outputs
5284 if (isDuplicated()) {
5285 mOutput1->changeRefCount(stream, delta);
5286 mOutput2->changeRefCount(stream, delta);
5287 }
5288 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005289 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5290 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005291 mRefCount[stream] = 0;
5292 return;
5293 }
5294 mRefCount[stream] += delta;
5295 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5296}
5297
Eric Laurente0720872014-03-11 09:30:41 -07005298audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005299{
5300 if (isDuplicated()) {
5301 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5302 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005303 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005304 }
5305}
5306
Eric Laurente0720872014-03-11 09:30:41 -07005307bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005308{
5309 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5310}
5311
Eric Laurente0720872014-03-11 09:30:41 -07005312bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005313 uint32_t inPastMs,
5314 nsecs_t sysTime) const
5315{
5316 if ((sysTime == 0) && (inPastMs != 0)) {
5317 sysTime = systemTime();
5318 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005319 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5320 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005321 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005322 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005323 return true;
5324 }
5325 }
5326 return false;
5327}
5328
Eric Laurente0720872014-03-11 09:30:41 -07005329bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005330 uint32_t inPastMs,
5331 nsecs_t sysTime) const
5332{
5333 if (mRefCount[stream] != 0) {
5334 return true;
5335 }
5336 if (inPastMs == 0) {
5337 return false;
5338 }
5339 if (sysTime == 0) {
5340 sysTime = systemTime();
5341 }
5342 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5343 return true;
5344 }
5345 return false;
5346}
5347
Eric Laurent1c333e22014-05-20 10:48:17 -07005348void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005349 struct audio_port_config *dstConfig,
5350 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005351{
Eric Laurent84c70242014-06-23 08:46:27 -07005352 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5353
Eric Laurent1f2f2232014-06-02 12:01:23 -07005354 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5355 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5356 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005357 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005358 }
5359 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5360
Eric Laurent6a94d692014-05-20 11:18:06 -07005361 dstConfig->id = mId;
5362 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5363 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005364 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5365 dstConfig->ext.mix.handle = mIoHandle;
5366 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005367}
5368
5369void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5370 struct audio_port *port) const
5371{
Eric Laurent84c70242014-06-23 08:46:27 -07005372 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005373 mProfile->toAudioPort(port);
5374 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005375 toAudioPortConfig(&port->active_config);
5376 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005377 port->ext.mix.handle = mIoHandle;
5378 port->ext.mix.latency_class =
5379 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5380}
Eric Laurente552edb2014-03-10 17:42:56 -07005381
Eric Laurente0720872014-03-11 09:30:41 -07005382status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005383{
5384 const size_t SIZE = 256;
5385 char buffer[SIZE];
5386 String8 result;
5387
Eric Laurent4d416952014-08-10 14:07:09 -07005388 snprintf(buffer, SIZE, " ID: %d\n", mId);
5389 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005390 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5391 result.append(buffer);
5392 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5393 result.append(buffer);
5394 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5395 result.append(buffer);
5396 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5397 result.append(buffer);
5398 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5399 result.append(buffer);
5400 snprintf(buffer, SIZE, " Devices %08x\n", device());
5401 result.append(buffer);
5402 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5403 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005404 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5405 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5406 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005407 result.append(buffer);
5408 }
5409 write(fd, result.string(), result.size());
5410
5411 return NO_ERROR;
5412}
5413
5414// --- AudioInputDescriptor class implementation
5415
Eric Laurent1c333e22014-05-20 10:48:17 -07005416AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005417 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005418 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005419 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005420{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005421 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005422 mSamplingRate = profile->pickSamplingRate();
5423 mFormat = profile->pickFormat();
5424 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005425 if (profile->mGains.size() > 0) {
5426 profile->mGains[0]->getDefaultConfig(&mGain);
5427 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005428 }
Eric Laurente552edb2014-03-10 17:42:56 -07005429}
5430
Eric Laurent1c333e22014-05-20 10:48:17 -07005431void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005432 struct audio_port_config *dstConfig,
5433 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005434{
Eric Laurent84c70242014-06-23 08:46:27 -07005435 ALOG_ASSERT(mProfile != 0,
5436 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005437 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5438 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5439 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005440 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005441 }
5442
5443 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5444
Eric Laurent6a94d692014-05-20 11:18:06 -07005445 dstConfig->id = mId;
5446 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5447 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005448 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5449 dstConfig->ext.mix.handle = mIoHandle;
5450 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005451}
5452
5453void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5454 struct audio_port *port) const
5455{
Eric Laurent84c70242014-06-23 08:46:27 -07005456 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5457
Eric Laurent1c333e22014-05-20 10:48:17 -07005458 mProfile->toAudioPort(port);
5459 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005460 toAudioPortConfig(&port->active_config);
5461 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005462 port->ext.mix.handle = mIoHandle;
5463 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5464}
5465
Eric Laurente0720872014-03-11 09:30:41 -07005466status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005467{
5468 const size_t SIZE = 256;
5469 char buffer[SIZE];
5470 String8 result;
5471
Eric Laurent4d416952014-08-10 14:07:09 -07005472 snprintf(buffer, SIZE, " ID: %d\n", mId);
5473 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005474 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5475 result.append(buffer);
5476 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5477 result.append(buffer);
5478 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5479 result.append(buffer);
5480 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5481 result.append(buffer);
5482 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5483 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005484 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5485 result.append(buffer);
5486
Eric Laurente552edb2014-03-10 17:42:56 -07005487 write(fd, result.string(), result.size());
5488
5489 return NO_ERROR;
5490}
5491
5492// --- StreamDescriptor class implementation
5493
Eric Laurente0720872014-03-11 09:30:41 -07005494AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005495 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5496{
5497 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5498}
5499
Eric Laurente0720872014-03-11 09:30:41 -07005500int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005501{
Eric Laurente0720872014-03-11 09:30:41 -07005502 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005503 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5504 if (mIndexCur.indexOfKey(device) < 0) {
5505 device = AUDIO_DEVICE_OUT_DEFAULT;
5506 }
5507 return mIndexCur.valueFor(device);
5508}
5509
Eric Laurente0720872014-03-11 09:30:41 -07005510void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005511{
5512 const size_t SIZE = 256;
5513 char buffer[SIZE];
5514 String8 result;
5515
5516 snprintf(buffer, SIZE, "%s %02d %02d ",
5517 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5518 result.append(buffer);
5519 for (size_t i = 0; i < mIndexCur.size(); i++) {
5520 snprintf(buffer, SIZE, "%04x : %02d, ",
5521 mIndexCur.keyAt(i),
5522 mIndexCur.valueAt(i));
5523 result.append(buffer);
5524 }
5525 result.append("\n");
5526
5527 write(fd, result.string(), result.size());
5528}
5529
5530// --- EffectDescriptor class implementation
5531
Eric Laurente0720872014-03-11 09:30:41 -07005532status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005533{
5534 const size_t SIZE = 256;
5535 char buffer[SIZE];
5536 String8 result;
5537
5538 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5539 result.append(buffer);
5540 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5541 result.append(buffer);
5542 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5543 result.append(buffer);
5544 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5545 result.append(buffer);
5546 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5547 result.append(buffer);
5548 write(fd, result.string(), result.size());
5549
5550 return NO_ERROR;
5551}
5552
Eric Laurent1c333e22014-05-20 10:48:17 -07005553// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005554
Eric Laurente0720872014-03-11 09:30:41 -07005555AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005556 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5557 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005558{
5559}
5560
Eric Laurente0720872014-03-11 09:30:41 -07005561AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005562{
5563 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005564 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005565 }
5566 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005567 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005568 }
5569 free((void *)mName);
5570}
5571
Eric Laurent1afeecb2014-05-14 08:52:28 -07005572status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5573{
5574 cnode *node = root->first_child;
5575
5576 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5577
5578 while (node) {
5579 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5580 profile->loadSamplingRates((char *)node->value);
5581 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5582 profile->loadFormats((char *)node->value);
5583 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5584 profile->loadInChannels((char *)node->value);
5585 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5586 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5587 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005588 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5589 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005590 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5591 profile->loadGains(node);
5592 }
5593 node = node->next;
5594 }
5595 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5596 "loadInput() invalid supported devices");
5597 ALOGW_IF(profile->mChannelMasks.size() == 0,
5598 "loadInput() invalid supported channel masks");
5599 ALOGW_IF(profile->mSamplingRates.size() == 0,
5600 "loadInput() invalid supported sampling rates");
5601 ALOGW_IF(profile->mFormats.size() == 0,
5602 "loadInput() invalid supported formats");
5603 if (!profile->mSupportedDevices.isEmpty() &&
5604 (profile->mChannelMasks.size() != 0) &&
5605 (profile->mSamplingRates.size() != 0) &&
5606 (profile->mFormats.size() != 0)) {
5607
5608 ALOGV("loadInput() adding input Supported Devices %04x",
5609 profile->mSupportedDevices.types());
5610
5611 mInputProfiles.add(profile);
5612 return NO_ERROR;
5613 } else {
5614 return BAD_VALUE;
5615 }
5616}
5617
5618status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5619{
5620 cnode *node = root->first_child;
5621
5622 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5623
5624 while (node) {
5625 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5626 profile->loadSamplingRates((char *)node->value);
5627 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5628 profile->loadFormats((char *)node->value);
5629 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5630 profile->loadOutChannels((char *)node->value);
5631 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5632 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5633 mDeclaredDevices);
5634 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005635 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005636 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5637 profile->loadGains(node);
5638 }
5639 node = node->next;
5640 }
5641 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5642 "loadOutput() invalid supported devices");
5643 ALOGW_IF(profile->mChannelMasks.size() == 0,
5644 "loadOutput() invalid supported channel masks");
5645 ALOGW_IF(profile->mSamplingRates.size() == 0,
5646 "loadOutput() invalid supported sampling rates");
5647 ALOGW_IF(profile->mFormats.size() == 0,
5648 "loadOutput() invalid supported formats");
5649 if (!profile->mSupportedDevices.isEmpty() &&
5650 (profile->mChannelMasks.size() != 0) &&
5651 (profile->mSamplingRates.size() != 0) &&
5652 (profile->mFormats.size() != 0)) {
5653
5654 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5655 profile->mSupportedDevices.types(), profile->mFlags);
5656
5657 mOutputProfiles.add(profile);
5658 return NO_ERROR;
5659 } else {
5660 return BAD_VALUE;
5661 }
5662}
5663
5664status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5665{
5666 cnode *node = root->first_child;
5667
5668 audio_devices_t type = AUDIO_DEVICE_NONE;
5669 while (node) {
5670 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5671 type = parseDeviceNames((char *)node->value);
5672 break;
5673 }
5674 node = node->next;
5675 }
5676 if (type == AUDIO_DEVICE_NONE ||
5677 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5678 ALOGW("loadDevice() bad type %08x", type);
5679 return BAD_VALUE;
5680 }
5681 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5682 deviceDesc->mModule = this;
5683
5684 node = root->first_child;
5685 while (node) {
5686 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5687 deviceDesc->mAddress = String8((char *)node->value);
5688 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5689 if (audio_is_input_device(type)) {
5690 deviceDesc->loadInChannels((char *)node->value);
5691 } else {
5692 deviceDesc->loadOutChannels((char *)node->value);
5693 }
5694 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5695 deviceDesc->loadGains(node);
5696 }
5697 node = node->next;
5698 }
5699
5700 ALOGV("loadDevice() adding device name %s type %08x address %s",
5701 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5702
5703 mDeclaredDevices.add(deviceDesc);
5704
5705 return NO_ERROR;
5706}
5707
Eric Laurente0720872014-03-11 09:30:41 -07005708void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005709{
5710 const size_t SIZE = 256;
5711 char buffer[SIZE];
5712 String8 result;
5713
5714 snprintf(buffer, SIZE, " - name: %s\n", mName);
5715 result.append(buffer);
5716 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5717 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005718 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5719 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005720 write(fd, result.string(), result.size());
5721 if (mOutputProfiles.size()) {
5722 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5723 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005724 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005725 write(fd, buffer, strlen(buffer));
5726 mOutputProfiles[i]->dump(fd);
5727 }
5728 }
5729 if (mInputProfiles.size()) {
5730 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5731 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005732 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005733 write(fd, buffer, strlen(buffer));
5734 mInputProfiles[i]->dump(fd);
5735 }
5736 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005737 if (mDeclaredDevices.size()) {
5738 write(fd, " - devices:\n", strlen(" - devices:\n"));
5739 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5740 mDeclaredDevices[i]->dump(fd, 4, i);
5741 }
5742 }
Eric Laurente552edb2014-03-10 17:42:56 -07005743}
5744
Eric Laurent1c333e22014-05-20 10:48:17 -07005745// --- AudioPort class implementation
5746
Eric Laurenta121f902014-06-03 13:32:54 -07005747
5748AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5749 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07005750 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07005751{
5752 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5753 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5754}
5755
Eric Laurent1c333e22014-05-20 10:48:17 -07005756void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5757{
5758 port->role = mRole;
5759 port->type = mType;
5760 unsigned int i;
5761 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005762 if (mSamplingRates[i] != 0) {
5763 port->sample_rates[i] = mSamplingRates[i];
5764 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005765 }
5766 port->num_sample_rates = i;
5767 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005768 if (mChannelMasks[i] != 0) {
5769 port->channel_masks[i] = mChannelMasks[i];
5770 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005771 }
5772 port->num_channel_masks = i;
5773 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005774 if (mFormats[i] != 0) {
5775 port->formats[i] = mFormats[i];
5776 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005777 }
5778 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005779
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005780 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005781
5782 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5783 port->gains[i] = mGains[i]->mGain;
5784 }
5785 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005786}
5787
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005788void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5789 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5790 const uint32_t rate = port->mSamplingRates.itemAt(k);
5791 if (rate != 0) { // skip "dynamic" rates
5792 bool hasRate = false;
5793 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5794 if (rate == mSamplingRates.itemAt(l)) {
5795 hasRate = true;
5796 break;
5797 }
5798 }
5799 if (!hasRate) { // never import a sampling rate twice
5800 mSamplingRates.add(rate);
5801 }
5802 }
5803 }
5804 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5805 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5806 if (mask != 0) { // skip "dynamic" masks
5807 bool hasMask = false;
5808 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5809 if (mask == mChannelMasks.itemAt(l)) {
5810 hasMask = true;
5811 break;
5812 }
5813 }
5814 if (!hasMask) { // never import a channel mask twice
5815 mChannelMasks.add(mask);
5816 }
5817 }
5818 }
5819 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5820 const audio_format_t format = port->mFormats.itemAt(k);
5821 if (format != 0) { // skip "dynamic" formats
5822 bool hasFormat = false;
5823 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5824 if (format == mFormats.itemAt(l)) {
5825 hasFormat = true;
5826 break;
5827 }
5828 }
5829 if (!hasFormat) { // never import a channel mask twice
5830 mFormats.add(format);
5831 }
5832 }
5833 }
5834}
5835
5836void AudioPolicyManager::AudioPort::clearCapabilities() {
5837 mChannelMasks.clear();
5838 mFormats.clear();
5839 mSamplingRates.clear();
5840}
Eric Laurent1c333e22014-05-20 10:48:17 -07005841
5842void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5843{
5844 char *str = strtok(name, "|");
5845
5846 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5847 // rates should be read from the output stream after it is opened for the first time
5848 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5849 mSamplingRates.add(0);
5850 return;
5851 }
5852
5853 while (str != NULL) {
5854 uint32_t rate = atoi(str);
5855 if (rate != 0) {
5856 ALOGV("loadSamplingRates() adding rate %d", rate);
5857 mSamplingRates.add(rate);
5858 }
5859 str = strtok(NULL, "|");
5860 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005861}
5862
5863void AudioPolicyManager::AudioPort::loadFormats(char *name)
5864{
5865 char *str = strtok(name, "|");
5866
5867 // by convention, "0' in the first entry in mFormats indicates the supported formats
5868 // should be read from the output stream after it is opened for the first time
5869 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5870 mFormats.add(AUDIO_FORMAT_DEFAULT);
5871 return;
5872 }
5873
5874 while (str != NULL) {
5875 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5876 ARRAY_SIZE(sFormatNameToEnumTable),
5877 str);
5878 if (format != AUDIO_FORMAT_DEFAULT) {
5879 mFormats.add(format);
5880 }
5881 str = strtok(NULL, "|");
5882 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005883}
5884
5885void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5886{
5887 const char *str = strtok(name, "|");
5888
5889 ALOGV("loadInChannels() %s", name);
5890
5891 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5892 mChannelMasks.add(0);
5893 return;
5894 }
5895
5896 while (str != NULL) {
5897 audio_channel_mask_t channelMask =
5898 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5899 ARRAY_SIZE(sInChannelsNameToEnumTable),
5900 str);
5901 if (channelMask != 0) {
5902 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5903 mChannelMasks.add(channelMask);
5904 }
5905 str = strtok(NULL, "|");
5906 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005907}
5908
5909void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5910{
5911 const char *str = strtok(name, "|");
5912
5913 ALOGV("loadOutChannels() %s", name);
5914
5915 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5916 // masks should be read from the output stream after it is opened for the first time
5917 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5918 mChannelMasks.add(0);
5919 return;
5920 }
5921
5922 while (str != NULL) {
5923 audio_channel_mask_t channelMask =
5924 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5925 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5926 str);
5927 if (channelMask != 0) {
5928 mChannelMasks.add(channelMask);
5929 }
5930 str = strtok(NULL, "|");
5931 }
5932 return;
5933}
5934
Eric Laurent1afeecb2014-05-14 08:52:28 -07005935audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5936{
5937 const char *str = strtok(name, "|");
5938
5939 ALOGV("loadGainMode() %s", name);
5940 audio_gain_mode_t mode = 0;
5941 while (str != NULL) {
5942 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5943 ARRAY_SIZE(sGainModeNameToEnumTable),
5944 str);
5945 str = strtok(NULL, "|");
5946 }
5947 return mode;
5948}
5949
Eric Laurenta121f902014-06-03 13:32:54 -07005950void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005951{
5952 cnode *node = root->first_child;
5953
Eric Laurenta121f902014-06-03 13:32:54 -07005954 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005955
5956 while (node) {
5957 if (strcmp(node->name, GAIN_MODE) == 0) {
5958 gain->mGain.mode = loadGainMode((char *)node->value);
5959 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005960 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005961 gain->mGain.channel_mask =
5962 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5963 ARRAY_SIZE(sInChannelsNameToEnumTable),
5964 (char *)node->value);
5965 } else {
5966 gain->mGain.channel_mask =
5967 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5968 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5969 (char *)node->value);
5970 }
5971 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5972 gain->mGain.min_value = atoi((char *)node->value);
5973 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5974 gain->mGain.max_value = atoi((char *)node->value);
5975 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5976 gain->mGain.default_value = atoi((char *)node->value);
5977 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5978 gain->mGain.step_value = atoi((char *)node->value);
5979 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5980 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5981 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5982 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5983 }
5984 node = node->next;
5985 }
5986
5987 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5988 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5989
5990 if (gain->mGain.mode == 0) {
5991 return;
5992 }
5993 mGains.add(gain);
5994}
5995
5996void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5997{
5998 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005999 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006000 while (node) {
6001 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006002 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006003 node = node->next;
6004 }
6005}
6006
Glenn Kastencbd48022014-07-24 13:46:44 -07006007status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006008{
6009 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6010 if (mSamplingRates[i] == samplingRate) {
6011 return NO_ERROR;
6012 }
6013 }
6014 return BAD_VALUE;
6015}
6016
Glenn Kastencbd48022014-07-24 13:46:44 -07006017status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6018 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006019{
Glenn Kastencbd48022014-07-24 13:46:44 -07006020 // Search for the closest supported sampling rate that is above (preferred)
6021 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6022 // The sampling rates do not need to be sorted in ascending order.
6023 ssize_t maxBelow = -1;
6024 ssize_t minAbove = -1;
6025 uint32_t candidate;
6026 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6027 candidate = mSamplingRates[i];
6028 if (candidate == samplingRate) {
6029 if (updatedSamplingRate != NULL) {
6030 *updatedSamplingRate = candidate;
6031 }
6032 return NO_ERROR;
6033 }
6034 // candidate < desired
6035 if (candidate < samplingRate) {
6036 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6037 maxBelow = i;
6038 }
6039 // candidate > desired
6040 } else {
6041 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6042 minAbove = i;
6043 }
6044 }
6045 }
6046 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6047 // TODO Move these assumptions out.
6048 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6049 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6050 // due to approximation by an int32_t of the
6051 // phase increments
6052 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6053 if (minAbove >= 0) {
6054 candidate = mSamplingRates[minAbove];
6055 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6056 if (updatedSamplingRate != NULL) {
6057 *updatedSamplingRate = candidate;
6058 }
6059 return NO_ERROR;
6060 }
6061 }
6062 // But if we have to up-sample from a lower sampling rate, that's OK.
6063 if (maxBelow >= 0) {
6064 candidate = mSamplingRates[maxBelow];
6065 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6066 if (updatedSamplingRate != NULL) {
6067 *updatedSamplingRate = candidate;
6068 }
6069 return NO_ERROR;
6070 }
6071 }
6072 // leave updatedSamplingRate unmodified
6073 return BAD_VALUE;
6074}
6075
6076status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6077{
6078 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006079 if (mChannelMasks[i] == channelMask) {
6080 return NO_ERROR;
6081 }
6082 }
6083 return BAD_VALUE;
6084}
6085
Glenn Kastencbd48022014-07-24 13:46:44 -07006086status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6087 const
6088{
6089 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6090 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6091 // FIXME Does not handle multi-channel automatic conversions yet
6092 audio_channel_mask_t supported = mChannelMasks[i];
6093 if (supported == channelMask) {
6094 return NO_ERROR;
6095 }
6096 if (isRecordThread) {
6097 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6098 // FIXME Abstract this out to a table.
6099 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6100 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6101 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6102 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6103 return NO_ERROR;
6104 }
6105 }
6106 }
6107 return BAD_VALUE;
6108}
6109
Eric Laurenta121f902014-06-03 13:32:54 -07006110status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6111{
6112 for (size_t i = 0; i < mFormats.size(); i ++) {
6113 if (mFormats[i] == format) {
6114 return NO_ERROR;
6115 }
6116 }
6117 return BAD_VALUE;
6118}
6119
Eric Laurent1e693b52014-07-09 15:03:28 -07006120
6121uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6122{
6123 // special case for uninitialized dynamic profile
6124 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6125 return 0;
6126 }
6127
Eric Laurent828bcff2014-09-07 12:26:06 -07006128 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6129 // channel count / sampling rate combination chosen will be supported by the connected
6130 // sink
6131 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6132 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6133 uint32_t samplingRate = UINT_MAX;
6134 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6135 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6136 samplingRate = mSamplingRates[i];
6137 }
6138 }
6139 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6140 }
6141
Eric Laurent1e693b52014-07-09 15:03:28 -07006142 uint32_t samplingRate = 0;
6143 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6144
6145 // For mixed output and inputs, use max mixer sampling rates. Do not
6146 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006147 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006148 maxRate = UINT_MAX;
6149 }
6150 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6151 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6152 samplingRate = mSamplingRates[i];
6153 }
6154 }
6155 return samplingRate;
6156}
6157
6158audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6159{
6160 // special case for uninitialized dynamic profile
6161 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6162 return AUDIO_CHANNEL_NONE;
6163 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006164 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006165
6166 // For direct outputs, pick minimum channel count: this helps ensuring that the
6167 // channel count / sampling rate combination chosen will be supported by the connected
6168 // sink
6169 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6170 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6171 uint32_t channelCount = UINT_MAX;
6172 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6173 uint32_t cnlCount;
6174 if (mUseInChannelMask) {
6175 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6176 } else {
6177 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6178 }
6179 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6180 channelMask = mChannelMasks[i];
6181 channelCount = cnlCount;
6182 }
6183 }
6184 return channelMask;
6185 }
6186
Eric Laurent1e693b52014-07-09 15:03:28 -07006187 uint32_t channelCount = 0;
6188 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6189
6190 // For mixed output and inputs, use max mixer channel count. Do not
6191 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006192 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006193 maxCount = UINT_MAX;
6194 }
6195 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6196 uint32_t cnlCount;
6197 if (mUseInChannelMask) {
6198 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6199 } else {
6200 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6201 }
6202 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6203 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006204 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006205 }
6206 }
6207 return channelMask;
6208}
6209
Andy Hung9a605382014-07-28 16:16:31 -07006210/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006211const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6212 AUDIO_FORMAT_DEFAULT,
6213 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006214 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006215 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006216 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006217 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006218};
6219
6220int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6221 audio_format_t format2)
6222{
6223 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6224 // compressed format and better than any PCM format. This is by design of pickFormat()
6225 if (!audio_is_linear_pcm(format1)) {
6226 if (!audio_is_linear_pcm(format2)) {
6227 return 0;
6228 }
6229 return 1;
6230 }
6231 if (!audio_is_linear_pcm(format2)) {
6232 return -1;
6233 }
6234
6235 int index1 = -1, index2 = -1;
6236 for (size_t i = 0;
6237 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6238 i ++) {
6239 if (sPcmFormatCompareTable[i] == format1) {
6240 index1 = i;
6241 }
6242 if (sPcmFormatCompareTable[i] == format2) {
6243 index2 = i;
6244 }
6245 }
6246 // format1 not found => index1 < 0 => format2 > format1
6247 // format2 not found => index2 < 0 => format2 < format1
6248 return index1 - index2;
6249}
6250
6251audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6252{
6253 // special case for uninitialized dynamic profile
6254 if (mFormats.size() == 1 && mFormats[0] == 0) {
6255 return AUDIO_FORMAT_DEFAULT;
6256 }
6257
6258 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006259 audio_format_t bestFormat =
6260 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6261 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006262 // For mixed output and inputs, use best mixer output format. Do not
6263 // limit format otherwise
6264 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6265 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006266 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006267 bestFormat = AUDIO_FORMAT_INVALID;
6268 }
6269
6270 for (size_t i = 0; i < mFormats.size(); i ++) {
6271 if ((compareFormats(mFormats[i], format) > 0) &&
6272 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6273 format = mFormats[i];
6274 }
6275 }
6276 return format;
6277}
6278
Eric Laurenta121f902014-06-03 13:32:54 -07006279status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6280 int index) const
6281{
6282 if (index < 0 || (size_t)index >= mGains.size()) {
6283 return BAD_VALUE;
6284 }
6285 return mGains[index]->checkConfig(gainConfig);
6286}
6287
Eric Laurent1afeecb2014-05-14 08:52:28 -07006288void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6289{
6290 const size_t SIZE = 256;
6291 char buffer[SIZE];
6292 String8 result;
6293
6294 if (mName.size() != 0) {
6295 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6296 result.append(buffer);
6297 }
6298
6299 if (mSamplingRates.size() != 0) {
6300 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6301 result.append(buffer);
6302 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006303 if (i == 0 && mSamplingRates[i] == 0) {
6304 snprintf(buffer, SIZE, "Dynamic");
6305 } else {
6306 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6307 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006308 result.append(buffer);
6309 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6310 }
6311 result.append("\n");
6312 }
6313
6314 if (mChannelMasks.size() != 0) {
6315 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6316 result.append(buffer);
6317 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006318 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6319
6320 if (i == 0 && mChannelMasks[i] == 0) {
6321 snprintf(buffer, SIZE, "Dynamic");
6322 } else {
6323 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6324 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006325 result.append(buffer);
6326 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6327 }
6328 result.append("\n");
6329 }
6330
6331 if (mFormats.size() != 0) {
6332 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6333 result.append(buffer);
6334 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006335 const char *formatStr = enumToString(sFormatNameToEnumTable,
6336 ARRAY_SIZE(sFormatNameToEnumTable),
6337 mFormats[i]);
6338 if (i == 0 && strcmp(formatStr, "") == 0) {
6339 snprintf(buffer, SIZE, "Dynamic");
6340 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006341 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006342 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006343 result.append(buffer);
6344 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6345 }
6346 result.append("\n");
6347 }
6348 write(fd, result.string(), result.size());
6349 if (mGains.size() != 0) {
6350 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6351 write(fd, buffer, strlen(buffer) + 1);
6352 result.append(buffer);
6353 for (size_t i = 0; i < mGains.size(); i++) {
6354 mGains[i]->dump(fd, spaces + 2, i);
6355 }
6356 }
6357}
6358
6359// --- AudioGain class implementation
6360
Eric Laurenta121f902014-06-03 13:32:54 -07006361AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006362{
Eric Laurenta121f902014-06-03 13:32:54 -07006363 mIndex = index;
6364 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006365 memset(&mGain, 0, sizeof(struct audio_gain));
6366}
6367
Eric Laurenta121f902014-06-03 13:32:54 -07006368void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6369{
6370 config->index = mIndex;
6371 config->mode = mGain.mode;
6372 config->channel_mask = mGain.channel_mask;
6373 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6374 config->values[0] = mGain.default_value;
6375 } else {
6376 uint32_t numValues;
6377 if (mUseInChannelMask) {
6378 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6379 } else {
6380 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6381 }
6382 for (size_t i = 0; i < numValues; i++) {
6383 config->values[i] = mGain.default_value;
6384 }
6385 }
6386 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6387 config->ramp_duration_ms = mGain.min_ramp_ms;
6388 }
6389}
6390
6391status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6392{
6393 if ((config->mode & ~mGain.mode) != 0) {
6394 return BAD_VALUE;
6395 }
6396 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6397 if ((config->values[0] < mGain.min_value) ||
6398 (config->values[0] > mGain.max_value)) {
6399 return BAD_VALUE;
6400 }
6401 } else {
6402 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6403 return BAD_VALUE;
6404 }
6405 uint32_t numValues;
6406 if (mUseInChannelMask) {
6407 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6408 } else {
6409 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6410 }
6411 for (size_t i = 0; i < numValues; i++) {
6412 if ((config->values[i] < mGain.min_value) ||
6413 (config->values[i] > mGain.max_value)) {
6414 return BAD_VALUE;
6415 }
6416 }
6417 }
6418 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6419 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6420 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6421 return BAD_VALUE;
6422 }
6423 }
6424 return NO_ERROR;
6425}
6426
Eric Laurent1afeecb2014-05-14 08:52:28 -07006427void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6428{
6429 const size_t SIZE = 256;
6430 char buffer[SIZE];
6431 String8 result;
6432
6433 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6434 result.append(buffer);
6435 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6436 result.append(buffer);
6437 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6438 result.append(buffer);
6439 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6440 result.append(buffer);
6441 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6442 result.append(buffer);
6443 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6444 result.append(buffer);
6445 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6446 result.append(buffer);
6447 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6448 result.append(buffer);
6449 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6450 result.append(buffer);
6451
6452 write(fd, result.string(), result.size());
6453}
6454
Eric Laurent1f2f2232014-06-02 12:01:23 -07006455// --- AudioPortConfig class implementation
6456
6457AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6458{
6459 mSamplingRate = 0;
6460 mChannelMask = AUDIO_CHANNEL_NONE;
6461 mFormat = AUDIO_FORMAT_INVALID;
6462 mGain.index = -1;
6463}
6464
Eric Laurenta121f902014-06-03 13:32:54 -07006465status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6466 const struct audio_port_config *config,
6467 struct audio_port_config *backupConfig)
6468{
6469 struct audio_port_config localBackupConfig;
6470 status_t status = NO_ERROR;
6471
6472 localBackupConfig.config_mask = config->config_mask;
6473 toAudioPortConfig(&localBackupConfig);
6474
Marco Nelissen961ec212014-08-25 15:58:39 -07006475 sp<AudioPort> audioport = getAudioPort();
6476 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006477 status = NO_INIT;
6478 goto exit;
6479 }
6480 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006481 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006482 if (status != NO_ERROR) {
6483 goto exit;
6484 }
6485 mSamplingRate = config->sample_rate;
6486 }
6487 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006488 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006489 if (status != NO_ERROR) {
6490 goto exit;
6491 }
6492 mChannelMask = config->channel_mask;
6493 }
6494 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006495 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006496 if (status != NO_ERROR) {
6497 goto exit;
6498 }
6499 mFormat = config->format;
6500 }
6501 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006502 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006503 if (status != NO_ERROR) {
6504 goto exit;
6505 }
6506 mGain = config->gain;
6507 }
6508
6509exit:
6510 if (status != NO_ERROR) {
6511 applyAudioPortConfig(&localBackupConfig);
6512 }
6513 if (backupConfig != NULL) {
6514 *backupConfig = localBackupConfig;
6515 }
6516 return status;
6517}
6518
Eric Laurent1f2f2232014-06-02 12:01:23 -07006519void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6520 struct audio_port_config *dstConfig,
6521 const struct audio_port_config *srcConfig) const
6522{
6523 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6524 dstConfig->sample_rate = mSamplingRate;
6525 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6526 dstConfig->sample_rate = srcConfig->sample_rate;
6527 }
6528 } else {
6529 dstConfig->sample_rate = 0;
6530 }
6531 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6532 dstConfig->channel_mask = mChannelMask;
6533 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6534 dstConfig->channel_mask = srcConfig->channel_mask;
6535 }
6536 } else {
6537 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6538 }
6539 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6540 dstConfig->format = mFormat;
6541 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6542 dstConfig->format = srcConfig->format;
6543 }
6544 } else {
6545 dstConfig->format = AUDIO_FORMAT_INVALID;
6546 }
6547 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6548 dstConfig->gain = mGain;
6549 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6550 dstConfig->gain = srcConfig->gain;
6551 }
6552 } else {
6553 dstConfig->gain.index = -1;
6554 }
6555 if (dstConfig->gain.index != -1) {
6556 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6557 } else {
6558 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6559 }
6560}
6561
Eric Laurent1c333e22014-05-20 10:48:17 -07006562// --- IOProfile class implementation
6563
Eric Laurent1afeecb2014-05-14 08:52:28 -07006564AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006565 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006566 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006567{
6568}
6569
Eric Laurente0720872014-03-11 09:30:41 -07006570AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006571{
6572}
6573
6574// checks if the IO profile is compatible with specified parameters.
6575// Sampling rate, format and channel mask must be specified in order to
6576// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006577bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006578 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006579 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006580 audio_format_t format,
6581 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006582 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006583{
Glenn Kastencbd48022014-07-24 13:46:44 -07006584 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6585 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6586 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006587
Glenn Kastencbd48022014-07-24 13:46:44 -07006588 if ((mSupportedDevices.types() & device) != device) {
6589 return false;
6590 }
6591
6592 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006593 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006594 }
6595 uint32_t myUpdatedSamplingRate = samplingRate;
6596 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006597 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006598 }
6599 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6600 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006601 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006602 }
6603
6604 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6605 return false;
6606 }
6607
6608 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6609 checkExactChannelMask(channelMask) != NO_ERROR)) {
6610 return false;
6611 }
6612 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6613 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6614 return false;
6615 }
6616
6617 if (isPlaybackThread && (mFlags & flags) != flags) {
6618 return false;
6619 }
6620 // The only input flag that is allowed to be different is the fast flag.
6621 // An existing fast stream is compatible with a normal track request.
6622 // An existing normal stream is compatible with a fast track request,
6623 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006624 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006625 ~AUDIO_INPUT_FLAG_FAST)) {
6626 return false;
6627 }
6628
6629 if (updatedSamplingRate != NULL) {
6630 *updatedSamplingRate = myUpdatedSamplingRate;
6631 }
6632 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006633}
6634
Eric Laurente0720872014-03-11 09:30:41 -07006635void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006636{
6637 const size_t SIZE = 256;
6638 char buffer[SIZE];
6639 String8 result;
6640
Eric Laurent1afeecb2014-05-14 08:52:28 -07006641 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006642
Eric Laurente552edb2014-03-10 17:42:56 -07006643 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6644 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006645 snprintf(buffer, SIZE, " - devices:\n");
6646 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006647 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006648 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6649 mSupportedDevices[i]->dump(fd, 6, i);
6650 }
Eric Laurente552edb2014-03-10 17:42:56 -07006651}
6652
Eric Laurentd4692962014-05-05 18:13:44 -07006653void AudioPolicyManager::IOProfile::log()
6654{
6655 const size_t SIZE = 256;
6656 char buffer[SIZE];
6657 String8 result;
6658
6659 ALOGV(" - sampling rates: ");
6660 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6661 ALOGV(" %d", mSamplingRates[i]);
6662 }
6663
6664 ALOGV(" - channel masks: ");
6665 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6666 ALOGV(" 0x%04x", mChannelMasks[i]);
6667 }
6668
6669 ALOGV(" - formats: ");
6670 for (size_t i = 0; i < mFormats.size(); i++) {
6671 ALOGV(" 0x%08x", mFormats[i]);
6672 }
6673
6674 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6675 ALOGV(" - flags: 0x%04x\n", mFlags);
6676}
6677
6678
Eric Laurent3a4311c2014-03-17 12:00:47 -07006679// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006680
Eric Laurent1f2f2232014-06-02 12:01:23 -07006681
6682AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6683 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6684 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6685 AUDIO_PORT_ROLE_SOURCE,
6686 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006687 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006688{
Eric Laurenta121f902014-06-03 13:32:54 -07006689 if (mGains.size() > 0) {
6690 mGains[0]->getDefaultConfig(&mGain);
6691 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006692}
6693
Eric Laurent3a4311c2014-03-17 12:00:47 -07006694bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006695{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006696 // Devices are considered equal if they:
6697 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6698 // - have the same address or one device does not specify the address
6699 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006700 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006701 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006702 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006703 mChannelMask == other->mChannelMask);
6704}
6705
6706void AudioPolicyManager::DeviceVector::refreshTypes()
6707{
Eric Laurent1c333e22014-05-20 10:48:17 -07006708 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006709 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006710 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006711 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006712 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006713}
6714
6715ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6716{
6717 for(size_t i = 0; i < size(); i++) {
6718 if (item->equals(itemAt(i))) {
6719 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006720 }
6721 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006722 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006723}
6724
Eric Laurent3a4311c2014-03-17 12:00:47 -07006725ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006726{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006727 ssize_t ret = indexOf(item);
6728
6729 if (ret < 0) {
6730 ret = SortedVector::add(item);
6731 if (ret >= 0) {
6732 refreshTypes();
6733 }
6734 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006735 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006736 ret = -1;
6737 }
6738 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006739}
6740
Eric Laurent3a4311c2014-03-17 12:00:47 -07006741ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6742{
6743 size_t i;
6744 ssize_t ret = indexOf(item);
6745
6746 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006747 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006748 } else {
6749 ret = SortedVector::removeAt(ret);
6750 if (ret >= 0) {
6751 refreshTypes();
6752 }
6753 }
6754 return ret;
6755}
6756
6757void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6758{
6759 DeviceVector deviceList;
6760
6761 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6762 types &= ~role_bit;
6763
6764 while (types) {
6765 uint32_t i = 31 - __builtin_clz(types);
6766 uint32_t type = 1 << i;
6767 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006768 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006769 }
6770}
6771
Eric Laurent1afeecb2014-05-14 08:52:28 -07006772void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6773 const DeviceVector& declaredDevices)
6774{
6775 char *devName = strtok(name, "|");
6776 while (devName != NULL) {
6777 if (strlen(devName) != 0) {
6778 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6779 ARRAY_SIZE(sDeviceNameToEnumTable),
6780 devName);
6781 if (type != AUDIO_DEVICE_NONE) {
6782 add(new DeviceDescriptor(String8(""), type));
6783 } else {
6784 sp<DeviceDescriptor> deviceDesc =
6785 declaredDevices.getDeviceFromName(String8(devName));
6786 if (deviceDesc != 0) {
6787 add(deviceDesc);
6788 }
6789 }
6790 }
6791 devName = strtok(NULL, "|");
6792 }
6793}
6794
Eric Laurent1c333e22014-05-20 10:48:17 -07006795sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6796 audio_devices_t type, String8 address) const
6797{
6798 sp<DeviceDescriptor> device;
6799 for (size_t i = 0; i < size(); i++) {
6800 if (itemAt(i)->mDeviceType == type) {
6801 device = itemAt(i);
6802 if (itemAt(i)->mAddress = address) {
6803 break;
6804 }
6805 }
6806 }
6807 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6808 type, address.string(), device.get());
6809 return device;
6810}
6811
Eric Laurent6a94d692014-05-20 11:18:06 -07006812sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6813 audio_port_handle_t id) const
6814{
6815 sp<DeviceDescriptor> device;
6816 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006817 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006818 if (itemAt(i)->mId == id) {
6819 device = itemAt(i);
6820 break;
6821 }
6822 }
6823 return device;
6824}
6825
Eric Laurent1c333e22014-05-20 10:48:17 -07006826AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6827 audio_devices_t type) const
6828{
6829 DeviceVector devices;
6830 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6831 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6832 devices.add(itemAt(i));
6833 type &= ~itemAt(i)->mDeviceType;
6834 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6835 itemAt(i)->mDeviceType, itemAt(i).get());
6836 }
6837 }
6838 return devices;
6839}
6840
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006841AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6842 audio_devices_t type, String8 address) const
6843{
6844 DeviceVector devices;
6845 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6846 for (size_t i = 0; i < size(); i++) {
6847 //ALOGV(" at i=%d: device=%x, addr=%s",
6848 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6849 if (itemAt(i)->mDeviceType == type) {
6850 if (itemAt(i)->mAddress == address) {
6851 //ALOGV(" found matching address %s", address.string());
6852 devices.add(itemAt(i));
6853 }
6854 }
6855 }
6856 return devices;
6857}
6858
Eric Laurent1afeecb2014-05-14 08:52:28 -07006859sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6860 const String8& name) const
6861{
6862 sp<DeviceDescriptor> device;
6863 for (size_t i = 0; i < size(); i++) {
6864 if (itemAt(i)->mName == name) {
6865 device = itemAt(i);
6866 break;
6867 }
6868 }
6869 return device;
6870}
6871
Eric Laurent6a94d692014-05-20 11:18:06 -07006872void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6873 struct audio_port_config *dstConfig,
6874 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006875{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006876 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6877 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006878 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006879 }
6880
6881 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6882
Eric Laurent6a94d692014-05-20 11:18:06 -07006883 dstConfig->id = mId;
6884 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006885 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006886 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006887 dstConfig->ext.device.type = mDeviceType;
6888 dstConfig->ext.device.hw_module = mModule->mHandle;
6889 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006890}
6891
6892void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6893{
Eric Laurent83b88082014-06-20 18:31:16 -07006894 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006895 AudioPort::toAudioPort(port);
6896 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006897 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006898 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006899 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006900 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6901}
6902
Eric Laurent1afeecb2014-05-14 08:52:28 -07006903status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006904{
6905 const size_t SIZE = 256;
6906 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006907 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006908
Eric Laurent1afeecb2014-05-14 08:52:28 -07006909 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6910 result.append(buffer);
6911 if (mId != 0) {
6912 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6913 result.append(buffer);
6914 }
6915 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6916 enumToString(sDeviceNameToEnumTable,
6917 ARRAY_SIZE(sDeviceNameToEnumTable),
6918 mDeviceType));
6919 result.append(buffer);
6920 if (mAddress.size() != 0) {
6921 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6922 result.append(buffer);
6923 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006924 write(fd, result.string(), result.size());
6925 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006926
6927 return NO_ERROR;
6928}
6929
Eric Laurent4d416952014-08-10 14:07:09 -07006930status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6931{
6932 const size_t SIZE = 256;
6933 char buffer[SIZE];
6934 String8 result;
6935
6936
6937 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6938 result.append(buffer);
6939 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6940 result.append(buffer);
6941 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6942 result.append(buffer);
6943 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6944 result.append(buffer);
6945 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6946 result.append(buffer);
6947 for (size_t i = 0; i < mPatch.num_sources; i++) {
6948 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6949 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6950 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6951 ARRAY_SIZE(sDeviceNameToEnumTable),
6952 mPatch.sources[i].ext.device.type));
6953 } else {
6954 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6955 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6956 }
6957 result.append(buffer);
6958 }
6959 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6960 result.append(buffer);
6961 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6962 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
6963 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6964 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
6965 ARRAY_SIZE(sDeviceNameToEnumTable),
6966 mPatch.sinks[i].ext.device.type));
6967 } else {
6968 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6969 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
6970 }
6971 result.append(buffer);
6972 }
6973
6974 write(fd, result.string(), result.size());
6975 return NO_ERROR;
6976}
Eric Laurent3a4311c2014-03-17 12:00:47 -07006977
6978// --- audio_policy.conf file parsing
6979
Eric Laurent5dbe4712014-09-19 19:04:57 -07006980uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006981{
6982 uint32_t flag = 0;
6983
6984 // it is OK to cast name to non const here as we are not going to use it after
6985 // strtok() modifies it
6986 char *flagName = strtok(name, "|");
6987 while (flagName != NULL) {
6988 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006989 flag |= stringToEnum(sOutputFlagNameToEnumTable,
6990 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07006991 flagName);
6992 }
6993 flagName = strtok(NULL, "|");
6994 }
6995 //force direct flag if offload flag is set: offloading implies a direct output stream
6996 // and all common behaviors are driven by checking only the direct flag
6997 // this should normally be set appropriately in the policy configuration file
6998 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6999 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7000 }
7001
Eric Laurent5dbe4712014-09-19 19:04:57 -07007002 return flag;
7003}
7004
7005uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7006{
7007 uint32_t flag = 0;
7008
7009 // it is OK to cast name to non const here as we are not going to use it after
7010 // strtok() modifies it
7011 char *flagName = strtok(name, "|");
7012 while (flagName != NULL) {
7013 if (strlen(flagName) != 0) {
7014 flag |= stringToEnum(sInputFlagNameToEnumTable,
7015 ARRAY_SIZE(sInputFlagNameToEnumTable),
7016 flagName);
7017 }
7018 flagName = strtok(NULL, "|");
7019 }
7020 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007021}
7022
Eric Laurente0720872014-03-11 09:30:41 -07007023audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007024{
7025 uint32_t device = 0;
7026
7027 char *devName = strtok(name, "|");
7028 while (devName != NULL) {
7029 if (strlen(devName) != 0) {
7030 device |= stringToEnum(sDeviceNameToEnumTable,
7031 ARRAY_SIZE(sDeviceNameToEnumTable),
7032 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007033 }
Eric Laurente552edb2014-03-10 17:42:56 -07007034 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007035 }
Eric Laurente552edb2014-03-10 17:42:56 -07007036 return device;
7037}
7038
Eric Laurente0720872014-03-11 09:30:41 -07007039void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007040{
Eric Laurente552edb2014-03-10 17:42:56 -07007041 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007042 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007043 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007044
Eric Laurent1afeecb2014-05-14 08:52:28 -07007045 node = config_find(root, DEVICES_TAG);
7046 if (node != NULL) {
7047 node = node->first_child;
7048 while (node) {
7049 ALOGV("loadHwModule() loading device %s", node->name);
7050 status_t tmpStatus = module->loadDevice(node);
7051 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7052 status = tmpStatus;
7053 }
7054 node = node->next;
7055 }
7056 }
7057 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007058 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007059 node = node->first_child;
7060 while (node) {
7061 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007062 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007063 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7064 status = tmpStatus;
7065 }
7066 node = node->next;
7067 }
7068 }
7069 node = config_find(root, INPUTS_TAG);
7070 if (node != NULL) {
7071 node = node->first_child;
7072 while (node) {
7073 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007074 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007075 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7076 status = tmpStatus;
7077 }
7078 node = node->next;
7079 }
7080 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007081 loadGlobalConfig(root, module);
7082
Eric Laurente552edb2014-03-10 17:42:56 -07007083 if (status == NO_ERROR) {
7084 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007085 }
7086}
7087
Eric Laurente0720872014-03-11 09:30:41 -07007088void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007089{
7090 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7091 if (node == NULL) {
7092 return;
7093 }
7094
7095 node = node->first_child;
7096 while (node) {
7097 ALOGV("loadHwModules() loading module %s", node->name);
7098 loadHwModule(node);
7099 node = node->next;
7100 }
7101}
7102
Eric Laurent1f2f2232014-06-02 12:01:23 -07007103void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007104{
7105 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007106
Eric Laurente552edb2014-03-10 17:42:56 -07007107 if (node == NULL) {
7108 return;
7109 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007110 DeviceVector declaredDevices;
7111 if (module != NULL) {
7112 declaredDevices = module->mDeclaredDevices;
7113 }
7114
Eric Laurente552edb2014-03-10 17:42:56 -07007115 node = node->first_child;
7116 while (node) {
7117 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007118 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7119 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007120 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7121 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007122 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007123 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007124 ARRAY_SIZE(sDeviceNameToEnumTable),
7125 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007126 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007127 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007128 } else {
7129 ALOGW("loadGlobalConfig() default device not specified");
7130 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007131 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007132 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007133 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7134 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007135 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007136 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7137 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7138 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007139 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7140 uint32_t major, minor;
7141 sscanf((char *)node->value, "%u.%u", &major, &minor);
7142 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7143 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7144 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007145 }
7146 node = node->next;
7147 }
7148}
7149
Eric Laurente0720872014-03-11 09:30:41 -07007150status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007151{
7152 cnode *root;
7153 char *data;
7154
7155 data = (char *)load_file(path, NULL);
7156 if (data == NULL) {
7157 return -ENODEV;
7158 }
7159 root = config_node("", "");
7160 config_load(root, data);
7161
Eric Laurente552edb2014-03-10 17:42:56 -07007162 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007163 // legacy audio_policy.conf files have one global_configuration section
7164 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007165 config_free(root);
7166 free(root);
7167 free(data);
7168
7169 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7170
7171 return NO_ERROR;
7172}
7173
Eric Laurente0720872014-03-11 09:30:41 -07007174void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007175{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007176 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007177 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007178 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7179 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007180 mAvailableOutputDevices.add(mDefaultOutputDevice);
7181 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007182
7183 module = new HwModule("primary");
7184
Eric Laurent1afeecb2014-05-14 08:52:28 -07007185 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007186 profile->mSamplingRates.add(44100);
7187 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7188 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007189 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007190 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7191 module->mOutputProfiles.add(profile);
7192
Eric Laurent1afeecb2014-05-14 08:52:28 -07007193 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007194 profile->mSamplingRates.add(8000);
7195 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7196 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007197 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007198 module->mInputProfiles.add(profile);
7199
7200 mHwModules.add(module);
7201}
7202
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007203audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7204{
7205 // flags to stream type mapping
7206 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7207 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7208 }
7209 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7210 return AUDIO_STREAM_BLUETOOTH_SCO;
7211 }
7212
7213 // usage to stream type mapping
7214 switch (attr->usage) {
7215 case AUDIO_USAGE_MEDIA:
7216 case AUDIO_USAGE_GAME:
7217 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7218 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7219 return AUDIO_STREAM_MUSIC;
7220 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7221 return AUDIO_STREAM_SYSTEM;
7222 case AUDIO_USAGE_VOICE_COMMUNICATION:
7223 return AUDIO_STREAM_VOICE_CALL;
7224
7225 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7226 return AUDIO_STREAM_DTMF;
7227
7228 case AUDIO_USAGE_ALARM:
7229 return AUDIO_STREAM_ALARM;
7230 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7231 return AUDIO_STREAM_RING;
7232
7233 case AUDIO_USAGE_NOTIFICATION:
7234 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7235 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7236 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7237 case AUDIO_USAGE_NOTIFICATION_EVENT:
7238 return AUDIO_STREAM_NOTIFICATION;
7239
7240 case AUDIO_USAGE_UNKNOWN:
7241 default:
7242 return AUDIO_STREAM_MUSIC;
7243 }
7244}
Eric Laurente552edb2014-03-10 17:42:56 -07007245}; // namespace android