blob: e4d785cefe0cdc64af12d3c402ce47fec1556544 [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 Laurent95511ad2014-10-10 15:31:38 -0700929 if (mForceDeepBufferForMedia && (flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0 &&
930 stream == AUDIO_STREAM_MUSIC) {
931 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
932 }
Eric Laurente552edb2014-03-10 17:42:56 -0700933
Eric Laurentb732cf52014-09-24 19:08:21 -0700934 sp<IOProfile> profile;
935
936 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700937 // and not explicitly requested
938 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
939 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700940 audio_channel_count_from_out_mask(channelMask) <= 2) {
941 goto non_direct_output;
942 }
943
Eric Laurente552edb2014-03-10 17:42:56 -0700944 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
945 // creating an offloaded track and tearing it down immediately after start when audioflinger
946 // detects there is an active non offloadable effect.
947 // FIXME: We should check the audio session here but we do not have it in this context.
948 // This may prevent offloading in rare situations where effects are left active by apps
949 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700950
Eric Laurente552edb2014-03-10 17:42:56 -0700951 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
952 !isNonOffloadableEffectEnabled()) {
953 profile = getProfileForDirectOutput(device,
954 samplingRate,
955 format,
956 channelMask,
957 (audio_output_flags_t)flags);
958 }
959
Eric Laurent1c333e22014-05-20 10:48:17 -0700960 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700961 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700962
963 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700964 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700965 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
966 outputDesc = desc;
967 // reuse direct output if currently open and configured with same parameters
968 if ((samplingRate == outputDesc->mSamplingRate) &&
969 (format == outputDesc->mFormat) &&
970 (channelMask == outputDesc->mChannelMask)) {
971 outputDesc->mDirectOpenCount++;
972 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
973 return mOutputs.keyAt(i);
974 }
975 }
976 }
977 // close direct output if currently open and configured with different parameters
978 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700979 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700980 }
981 outputDesc = new AudioOutputDescriptor(profile);
982 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700983 outputDesc->mLatency = 0;
984 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700985 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
986 config.sample_rate = samplingRate;
987 config.channel_mask = channelMask;
988 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700989 if (offloadInfo != NULL) {
990 config.offload_info = *offloadInfo;
991 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700992 status = mpClientInterface->openOutput(profile->mModule->mHandle,
993 &output,
994 &config,
995 &outputDesc->mDevice,
996 String8(""),
997 &outputDesc->mLatency,
998 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700999
1000 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001001 if (status != NO_ERROR ||
1002 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1003 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1004 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001005 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1006 "format %d %d, channelMask %04x %04x", output, samplingRate,
1007 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1008 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001009 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001010 mpClientInterface->closeOutput(output);
1011 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001012 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001013 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001014 outputDesc->mSamplingRate = config.sample_rate;
1015 outputDesc->mChannelMask = config.channel_mask;
1016 outputDesc->mFormat = config.format;
1017 outputDesc->mRefCount[stream] = 0;
1018 outputDesc->mStopTime[stream] = 0;
1019 outputDesc->mDirectOpenCount = 1;
1020
Eric Laurente552edb2014-03-10 17:42:56 -07001021 audio_io_handle_t srcOutput = getOutputForEffect();
1022 addOutput(output, outputDesc);
1023 audio_io_handle_t dstOutput = getOutputForEffect();
1024 if (dstOutput == output) {
1025 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1026 }
1027 mPreviousOutputs = mOutputs;
1028 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001029 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001030 return output;
1031 }
1032
Eric Laurentb732cf52014-09-24 19:08:21 -07001033non_direct_output:
1034
Eric Laurente552edb2014-03-10 17:42:56 -07001035 // ignoring channel mask due to downmix capability in mixer
1036
1037 // open a non direct output
1038
1039 // for non direct outputs, only PCM is supported
1040 if (audio_is_linear_pcm(format)) {
1041 // get which output is suitable for the specified stream. The actual
1042 // routing change will happen when startOutput() will be called
1043 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1044
Eric Laurent8838a382014-09-08 16:44:28 -07001045 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1046 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1047 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001048 }
1049 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1050 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1051
1052 ALOGV("getOutput() returns output %d", output);
1053
1054 return output;
1055}
1056
Eric Laurente0720872014-03-11 09:30:41 -07001057audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001058 audio_output_flags_t flags,
1059 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001060{
1061 // select one output among several that provide a path to a particular device or set of
1062 // devices (the list was previously build by getOutputsForDevice()).
1063 // The priority is as follows:
1064 // 1: the output with the highest number of requested policy flags
1065 // 2: the primary output
1066 // 3: the first output in the list
1067
1068 if (outputs.size() == 0) {
1069 return 0;
1070 }
1071 if (outputs.size() == 1) {
1072 return outputs[0];
1073 }
1074
1075 int maxCommonFlags = 0;
1076 audio_io_handle_t outputFlags = 0;
1077 audio_io_handle_t outputPrimary = 0;
1078
1079 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001080 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001081 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001082 // if a valid format is specified, skip output if not compatible
1083 if (format != AUDIO_FORMAT_INVALID) {
1084 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1085 if (format != outputDesc->mFormat) {
1086 continue;
1087 }
1088 } else if (!audio_is_linear_pcm(format)) {
1089 continue;
1090 }
1091 }
1092
Eric Laurent3b73df72014-03-11 09:06:29 -07001093 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001094 if (commonFlags > maxCommonFlags) {
1095 outputFlags = outputs[i];
1096 maxCommonFlags = commonFlags;
1097 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1098 }
1099 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1100 outputPrimary = outputs[i];
1101 }
1102 }
1103 }
1104
1105 if (outputFlags != 0) {
1106 return outputFlags;
1107 }
1108 if (outputPrimary != 0) {
1109 return outputPrimary;
1110 }
1111
1112 return outputs[0];
1113}
1114
Eric Laurente0720872014-03-11 09:30:41 -07001115status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001116 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001117 int session)
1118{
1119 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1120 ssize_t index = mOutputs.indexOfKey(output);
1121 if (index < 0) {
1122 ALOGW("startOutput() unknown output %d", output);
1123 return BAD_VALUE;
1124 }
1125
Eric Laurent1f2f2232014-06-02 12:01:23 -07001126 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001127
1128 // increment usage count for this stream on the requested output:
1129 // NOTE that the usage count is the same for duplicated output and hardware output which is
1130 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1131 outputDesc->changeRefCount(stream, 1);
1132
1133 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001134 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001135 routing_strategy strategy = getStrategy(stream);
1136 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1137 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1138 uint32_t waitMs = 0;
1139 bool force = false;
1140 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001141 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001142 if (desc != outputDesc) {
1143 // force a device change if any other output is managed by the same hw
1144 // module and has a current device selection that differs from selected device.
1145 // In this case, the audio HAL must receive the new device selection so that it can
1146 // change the device currently selected by the other active output.
1147 if (outputDesc->sharesHwModuleWith(desc) &&
1148 desc->device() != newDevice) {
1149 force = true;
1150 }
1151 // wait for audio on other active outputs to be presented when starting
1152 // a notification so that audio focus effect can propagate.
1153 uint32_t latency = desc->latency();
1154 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1155 waitMs = latency;
1156 }
1157 }
1158 }
1159 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1160
1161 // handle special case for sonification while in call
1162 if (isInCall()) {
1163 handleIncallSonification(stream, true, false);
1164 }
1165
1166 // apply volume rules for current stream and device if necessary
1167 checkAndSetVolume(stream,
1168 mStreams[stream].getVolumeIndex(newDevice),
1169 output,
1170 newDevice);
1171
1172 // update the outputs if starting an output with a stream that can affect notification
1173 // routing
1174 handleNotificationRoutingForStream(stream);
1175 if (waitMs > muteWaitMs) {
1176 usleep((waitMs - muteWaitMs) * 2 * 1000);
1177 }
1178 }
1179 return NO_ERROR;
1180}
1181
1182
Eric Laurente0720872014-03-11 09:30:41 -07001183status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001184 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001185 int session)
1186{
1187 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1188 ssize_t index = mOutputs.indexOfKey(output);
1189 if (index < 0) {
1190 ALOGW("stopOutput() unknown output %d", output);
1191 return BAD_VALUE;
1192 }
1193
Eric Laurent1f2f2232014-06-02 12:01:23 -07001194 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001195
1196 // handle special case for sonification while in call
1197 if (isInCall()) {
1198 handleIncallSonification(stream, false, false);
1199 }
1200
1201 if (outputDesc->mRefCount[stream] > 0) {
1202 // decrement usage count of this stream on the output
1203 outputDesc->changeRefCount(stream, -1);
1204 // store time at which the stream was stopped - see isStreamActive()
1205 if (outputDesc->mRefCount[stream] == 0) {
1206 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001207 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001208 // delay the device switch by twice the latency because stopOutput() is executed when
1209 // the track stop() command is received and at that time the audio track buffer can
1210 // still contain data that needs to be drained. The latency only covers the audio HAL
1211 // and kernel buffers. Also the latency does not always include additional delay in the
1212 // audio path (audio DSP, CODEC ...)
1213 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1214
1215 // force restoring the device selection on other active outputs if it differs from the
1216 // one being selected for this output
1217 for (size_t i = 0; i < mOutputs.size(); i++) {
1218 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001219 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001220 if (curOutput != output &&
1221 desc->isActive() &&
1222 outputDesc->sharesHwModuleWith(desc) &&
1223 (newDevice != desc->device())) {
1224 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001225 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001226 true,
1227 outputDesc->mLatency*2);
1228 }
1229 }
1230 // update the outputs if stopping one with a stream that can affect notification routing
1231 handleNotificationRoutingForStream(stream);
1232 }
1233 return NO_ERROR;
1234 } else {
1235 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1236 return INVALID_OPERATION;
1237 }
1238}
1239
Eric Laurente0720872014-03-11 09:30:41 -07001240void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001241{
1242 ALOGV("releaseOutput() %d", output);
1243 ssize_t index = mOutputs.indexOfKey(output);
1244 if (index < 0) {
1245 ALOGW("releaseOutput() releasing unknown output %d", output);
1246 return;
1247 }
1248
1249#ifdef AUDIO_POLICY_TEST
1250 int testIndex = testOutputIndex(output);
1251 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001252 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001253 if (outputDesc->isActive()) {
1254 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001255 mOutputs.removeItem(output);
1256 mTestOutputs[testIndex] = 0;
1257 }
1258 return;
1259 }
1260#endif //AUDIO_POLICY_TEST
1261
Eric Laurent1f2f2232014-06-02 12:01:23 -07001262 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001263 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001264 if (desc->mDirectOpenCount <= 0) {
1265 ALOGW("releaseOutput() invalid open count %d for output %d",
1266 desc->mDirectOpenCount, output);
1267 return;
1268 }
1269 if (--desc->mDirectOpenCount == 0) {
1270 closeOutput(output);
1271 // If effects where present on the output, audioflinger moved them to the primary
1272 // output by default: move them back to the appropriate output.
1273 audio_io_handle_t dstOutput = getOutputForEffect();
1274 if (dstOutput != mPrimaryOutput) {
1275 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1276 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001277 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001278 }
1279 }
1280}
1281
1282
Eric Laurente0720872014-03-11 09:30:41 -07001283audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001284 uint32_t samplingRate,
1285 audio_format_t format,
1286 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001287 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001288 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001289{
Eric Laurent4dc68062014-07-28 17:26:49 -07001290 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001291 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001292 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001293
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001294 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001295
1296 if (device == AUDIO_DEVICE_NONE) {
1297 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001298 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001299 }
1300
1301 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001302 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001303 case AUDIO_SOURCE_VOICE_UPLINK:
1304 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1305 break;
1306 case AUDIO_SOURCE_VOICE_DOWNLINK:
1307 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1308 break;
1309 case AUDIO_SOURCE_VOICE_CALL:
1310 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1311 break;
1312 default:
1313 break;
1314 }
1315
Eric Laurent5dbe4712014-09-19 19:04:57 -07001316 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1317 bool isSoundTrigger = false;
1318 audio_source_t halInputSource = inputSource;
1319 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1320 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1321 if (index >= 0) {
1322 input = mSoundTriggerSessions.valueFor(session);
1323 isSoundTrigger = true;
1324 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1325 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1326 } else {
1327 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1328 }
1329 }
1330
Eric Laurent1c333e22014-05-20 10:48:17 -07001331 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001332 samplingRate,
1333 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001334 channelMask,
1335 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001336 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001337 //retry without flags
1338 audio_input_flags_t log_flags = flags;
1339 flags = AUDIO_INPUT_FLAG_NONE;
1340 profile = getInputProfile(device,
1341 samplingRate,
1342 format,
1343 channelMask,
1344 flags);
1345 if (profile == 0) {
1346 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1347 "channelMask 0x%X, flags %#x",
1348 device, samplingRate, format, channelMask, log_flags);
1349 return AUDIO_IO_HANDLE_NONE;
1350 }
Eric Laurente552edb2014-03-10 17:42:56 -07001351 }
1352
1353 if (profile->mModule->mHandle == 0) {
1354 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001355 return AUDIO_IO_HANDLE_NONE;
1356 }
1357
1358 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1359 config.sample_rate = samplingRate;
1360 config.channel_mask = channelMask;
1361 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001362
Eric Laurentcf2c0212014-07-25 16:20:43 -07001363 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1364 &input,
1365 &config,
1366 &device,
1367 String8(""),
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001368 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001369 flags);
1370
1371 // only accept input with the exact requested set of parameters
1372 if (status != NO_ERROR ||
1373 (samplingRate != config.sample_rate) ||
1374 (format != config.format) ||
1375 (channelMask != config.channel_mask)) {
1376 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1377 samplingRate, format, channelMask);
1378 if (input != AUDIO_IO_HANDLE_NONE) {
1379 mpClientInterface->closeInput(input);
1380 }
1381 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001382 }
1383
Eric Laurent1f2f2232014-06-02 12:01:23 -07001384 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001385 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001386 inputDesc->mRefCount = 0;
1387 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001388 inputDesc->mSamplingRate = samplingRate;
1389 inputDesc->mFormat = format;
1390 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001391 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001392 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001393 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001394
Eric Laurentd4692962014-05-05 18:13:44 -07001395 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001396 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001397 return input;
1398}
1399
Eric Laurent4dc68062014-07-28 17:26:49 -07001400status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1401 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001402{
1403 ALOGV("startInput() input %d", input);
1404 ssize_t index = mInputs.indexOfKey(input);
1405 if (index < 0) {
1406 ALOGW("startInput() unknown input %d", input);
1407 return BAD_VALUE;
1408 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001409 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001410
Eric Laurent4dc68062014-07-28 17:26:49 -07001411 index = inputDesc->mSessions.indexOf(session);
1412 if (index < 0) {
1413 ALOGW("startInput() unknown session %d on input %d", session, input);
1414 return BAD_VALUE;
1415 }
1416
Glenn Kasten74a8e252014-07-24 14:09:55 -07001417 // virtual input devices are compatible with other input devices
1418 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1419
1420 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001421 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001422 if (activeInput != 0 && activeInput != input) {
1423
1424 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1425 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001426 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001427 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001428 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001429 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1430 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001431 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001432 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001433 return INVALID_OPERATION;
1434 }
1435 }
1436 }
1437
Glenn Kasten74a8e252014-07-24 14:09:55 -07001438 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001439 if (activeInputsCount() == 0) {
1440 SoundTrigger::setCaptureState(true);
1441 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001442 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001443
Glenn Kasten74a8e252014-07-24 14:09:55 -07001444 // Automatically enable the remote submix output when input is started.
1445 // For remote submix (a virtual device), we open only one input per capture request.
1446 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1447 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1448 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1449 }
Eric Laurente552edb2014-03-10 17:42:56 -07001450 }
1451
Eric Laurente552edb2014-03-10 17:42:56 -07001452 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1453
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001454 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001455 return NO_ERROR;
1456}
1457
Eric Laurent4dc68062014-07-28 17:26:49 -07001458status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1459 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001460{
1461 ALOGV("stopInput() input %d", input);
1462 ssize_t index = mInputs.indexOfKey(input);
1463 if (index < 0) {
1464 ALOGW("stopInput() unknown input %d", input);
1465 return BAD_VALUE;
1466 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001467 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001468
Eric Laurent4dc68062014-07-28 17:26:49 -07001469 index = inputDesc->mSessions.indexOf(session);
1470 if (index < 0) {
1471 ALOGW("stopInput() unknown session %d on input %d", session, input);
1472 return BAD_VALUE;
1473 }
1474
Eric Laurente552edb2014-03-10 17:42:56 -07001475 if (inputDesc->mRefCount == 0) {
1476 ALOGW("stopInput() input %d already stopped", input);
1477 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001478 }
1479
1480 inputDesc->mRefCount--;
1481 if (inputDesc->mRefCount == 0) {
1482
Eric Laurente552edb2014-03-10 17:42:56 -07001483 // automatically disable the remote submix output when input is stopped
1484 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1485 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001486 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001487 }
1488
Eric Laurent1c333e22014-05-20 10:48:17 -07001489 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001490
1491 if (activeInputsCount() == 0) {
1492 SoundTrigger::setCaptureState(false);
1493 }
Eric Laurente552edb2014-03-10 17:42:56 -07001494 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001495 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001496}
1497
Eric Laurent4dc68062014-07-28 17:26:49 -07001498void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1499 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001500{
1501 ALOGV("releaseInput() %d", input);
1502 ssize_t index = mInputs.indexOfKey(input);
1503 if (index < 0) {
1504 ALOGW("releaseInput() releasing unknown input %d", input);
1505 return;
1506 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001507 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1508 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001509
1510 index = inputDesc->mSessions.indexOf(session);
1511 if (index < 0) {
1512 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1513 return;
1514 }
1515 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001516 if (inputDesc->mOpenRefCount == 0) {
1517 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1518 return;
1519 }
1520 inputDesc->mOpenRefCount--;
1521 if (inputDesc->mOpenRefCount > 0) {
1522 ALOGV("releaseInput() exit > 0");
1523 return;
1524 }
1525
Eric Laurent05b90f82014-08-27 15:32:29 -07001526 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001527 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001528 ALOGV("releaseInput() exit");
1529}
1530
Eric Laurentd4692962014-05-05 18:13:44 -07001531void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001532 bool patchRemoved = false;
1533
Eric Laurentd4692962014-05-05 18:13:44 -07001534 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001535 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1536 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1537 if (patch_index >= 0) {
1538 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1539 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1540 mAudioPatches.removeItemsAt(patch_index);
1541 patchRemoved = true;
1542 }
Eric Laurentd4692962014-05-05 18:13:44 -07001543 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1544 }
1545 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001546 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001547
1548 if (patchRemoved) {
1549 mpClientInterface->onAudioPatchListUpdate();
1550 }
Eric Laurentd4692962014-05-05 18:13:44 -07001551}
1552
Eric Laurente0720872014-03-11 09:30:41 -07001553void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001554 int indexMin,
1555 int indexMax)
1556{
1557 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1558 if (indexMin < 0 || indexMin >= indexMax) {
1559 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1560 return;
1561 }
1562 mStreams[stream].mIndexMin = indexMin;
1563 mStreams[stream].mIndexMax = indexMax;
1564}
1565
Eric Laurente0720872014-03-11 09:30:41 -07001566status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001567 int index,
1568 audio_devices_t device)
1569{
1570
1571 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1572 return BAD_VALUE;
1573 }
1574 if (!audio_is_output_device(device)) {
1575 return BAD_VALUE;
1576 }
1577
1578 // Force max volume if stream cannot be muted
1579 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1580
1581 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1582 stream, device, index);
1583
1584 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1585 // clear all device specific values
1586 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1587 mStreams[stream].mIndexCur.clear();
1588 }
1589 mStreams[stream].mIndexCur.add(device, index);
1590
1591 // compute and apply stream volume on all outputs according to connected device
1592 status_t status = NO_ERROR;
1593 for (size_t i = 0; i < mOutputs.size(); i++) {
1594 audio_devices_t curDevice =
1595 getDeviceForVolume(mOutputs.valueAt(i)->device());
1596 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1597 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1598 if (volStatus != NO_ERROR) {
1599 status = volStatus;
1600 }
1601 }
1602 }
1603 return status;
1604}
1605
Eric Laurente0720872014-03-11 09:30:41 -07001606status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001607 int *index,
1608 audio_devices_t device)
1609{
1610 if (index == NULL) {
1611 return BAD_VALUE;
1612 }
1613 if (!audio_is_output_device(device)) {
1614 return BAD_VALUE;
1615 }
1616 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1617 // the strategy the stream belongs to.
1618 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1619 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1620 }
1621 device = getDeviceForVolume(device);
1622
1623 *index = mStreams[stream].getVolumeIndex(device);
1624 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1625 return NO_ERROR;
1626}
1627
Eric Laurente0720872014-03-11 09:30:41 -07001628audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001629 const SortedVector<audio_io_handle_t>& outputs)
1630{
1631 // select one output among several suitable for global effects.
1632 // The priority is as follows:
1633 // 1: An offloaded output. If the effect ends up not being offloadable,
1634 // AudioFlinger will invalidate the track and the offloaded output
1635 // will be closed causing the effect to be moved to a PCM output.
1636 // 2: A deep buffer output
1637 // 3: the first output in the list
1638
1639 if (outputs.size() == 0) {
1640 return 0;
1641 }
1642
1643 audio_io_handle_t outputOffloaded = 0;
1644 audio_io_handle_t outputDeepBuffer = 0;
1645
1646 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001647 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001648 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001649 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1650 outputOffloaded = outputs[i];
1651 }
1652 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1653 outputDeepBuffer = outputs[i];
1654 }
1655 }
1656
1657 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1658 outputOffloaded, outputDeepBuffer);
1659 if (outputOffloaded != 0) {
1660 return outputOffloaded;
1661 }
1662 if (outputDeepBuffer != 0) {
1663 return outputDeepBuffer;
1664 }
1665
1666 return outputs[0];
1667}
1668
Eric Laurente0720872014-03-11 09:30:41 -07001669audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001670{
1671 // apply simple rule where global effects are attached to the same output as MUSIC streams
1672
Eric Laurent3b73df72014-03-11 09:06:29 -07001673 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001674 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1675 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1676
1677 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1678 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1679 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1680
1681 return output;
1682}
1683
Eric Laurente0720872014-03-11 09:30:41 -07001684status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001685 audio_io_handle_t io,
1686 uint32_t strategy,
1687 int session,
1688 int id)
1689{
1690 ssize_t index = mOutputs.indexOfKey(io);
1691 if (index < 0) {
1692 index = mInputs.indexOfKey(io);
1693 if (index < 0) {
1694 ALOGW("registerEffect() unknown io %d", io);
1695 return INVALID_OPERATION;
1696 }
1697 }
1698
1699 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1700 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1701 desc->name, desc->memoryUsage);
1702 return INVALID_OPERATION;
1703 }
1704 mTotalEffectsMemory += desc->memoryUsage;
1705 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1706 desc->name, io, strategy, session, id);
1707 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1708
Eric Laurent1f2f2232014-06-02 12:01:23 -07001709 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1710 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1711 effectDesc->mIo = io;
1712 effectDesc->mStrategy = (routing_strategy)strategy;
1713 effectDesc->mSession = session;
1714 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001715
Eric Laurent1f2f2232014-06-02 12:01:23 -07001716 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001717
1718 return NO_ERROR;
1719}
1720
Eric Laurente0720872014-03-11 09:30:41 -07001721status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001722{
1723 ssize_t index = mEffects.indexOfKey(id);
1724 if (index < 0) {
1725 ALOGW("unregisterEffect() unknown effect ID %d", id);
1726 return INVALID_OPERATION;
1727 }
1728
Eric Laurent1f2f2232014-06-02 12:01:23 -07001729 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001730
Eric Laurent1f2f2232014-06-02 12:01:23 -07001731 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001732
Eric Laurent1f2f2232014-06-02 12:01:23 -07001733 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001734 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001735 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1736 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001737 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001738 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001739 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001740 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001741
1742 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001743
1744 return NO_ERROR;
1745}
1746
Eric Laurente0720872014-03-11 09:30:41 -07001747status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001748{
1749 ssize_t index = mEffects.indexOfKey(id);
1750 if (index < 0) {
1751 ALOGW("unregisterEffect() unknown effect ID %d", id);
1752 return INVALID_OPERATION;
1753 }
1754
1755 return setEffectEnabled(mEffects.valueAt(index), enabled);
1756}
1757
Eric Laurent1f2f2232014-06-02 12:01:23 -07001758status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001759{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001760 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001761 ALOGV("setEffectEnabled(%s) effect already %s",
1762 enabled?"true":"false", enabled?"enabled":"disabled");
1763 return INVALID_OPERATION;
1764 }
1765
1766 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001767 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001768 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001769 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001770 return INVALID_OPERATION;
1771 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001772 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001773 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1774 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001775 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001776 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001777 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1778 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001779 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001780 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001781 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1782 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001783 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001784 return NO_ERROR;
1785}
1786
Eric Laurente0720872014-03-11 09:30:41 -07001787bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001788{
1789 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001790 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1791 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1792 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001793 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001794 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001795 return true;
1796 }
1797 }
1798 return false;
1799}
1800
Eric Laurente0720872014-03-11 09:30:41 -07001801bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001802{
1803 nsecs_t sysTime = systemTime();
1804 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001805 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001806 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001807 return true;
1808 }
1809 }
1810 return false;
1811}
1812
Eric Laurente0720872014-03-11 09:30:41 -07001813bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001814 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001815{
1816 nsecs_t sysTime = systemTime();
1817 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001818 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001819 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001820 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001821 return true;
1822 }
1823 }
1824 return false;
1825}
1826
Eric Laurente0720872014-03-11 09:30:41 -07001827bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001828{
1829 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001830 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001831 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001832 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001833 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1834 && (inputDescriptor->mRefCount > 0)) {
1835 return true;
1836 }
1837 }
1838 return false;
1839}
1840
1841
Eric Laurente0720872014-03-11 09:30:41 -07001842status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001843{
1844 const size_t SIZE = 256;
1845 char buffer[SIZE];
1846 String8 result;
1847
1848 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1849 result.append(buffer);
1850
1851 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1852 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001853 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1854 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001855 snprintf(buffer, SIZE, " Force use for communications %d\n",
1856 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001857 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001858 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001859 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001860 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001861 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001862 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001863 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001864 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001865 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001866 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1867 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1868 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001869
Eric Laurent3a4311c2014-03-17 12:00:47 -07001870 snprintf(buffer, SIZE, " Available output devices:\n");
1871 result.append(buffer);
1872 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001873 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001874 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001875 }
1876 snprintf(buffer, SIZE, "\n Available input devices:\n");
1877 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001878 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001879 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001880 }
Eric Laurente552edb2014-03-10 17:42:56 -07001881
1882 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1883 write(fd, buffer, strlen(buffer));
1884 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001885 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001886 write(fd, buffer, strlen(buffer));
1887 mHwModules[i]->dump(fd);
1888 }
1889
1890 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1891 write(fd, buffer, strlen(buffer));
1892 for (size_t i = 0; i < mOutputs.size(); i++) {
1893 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1894 write(fd, buffer, strlen(buffer));
1895 mOutputs.valueAt(i)->dump(fd);
1896 }
1897
1898 snprintf(buffer, SIZE, "\nInputs dump:\n");
1899 write(fd, buffer, strlen(buffer));
1900 for (size_t i = 0; i < mInputs.size(); i++) {
1901 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1902 write(fd, buffer, strlen(buffer));
1903 mInputs.valueAt(i)->dump(fd);
1904 }
1905
1906 snprintf(buffer, SIZE, "\nStreams dump:\n");
1907 write(fd, buffer, strlen(buffer));
1908 snprintf(buffer, SIZE,
1909 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1910 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001911 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001912 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001913 write(fd, buffer, strlen(buffer));
1914 mStreams[i].dump(fd);
1915 }
1916
1917 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1918 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1919 write(fd, buffer, strlen(buffer));
1920
1921 snprintf(buffer, SIZE, "Registered effects:\n");
1922 write(fd, buffer, strlen(buffer));
1923 for (size_t i = 0; i < mEffects.size(); i++) {
1924 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1925 write(fd, buffer, strlen(buffer));
1926 mEffects.valueAt(i)->dump(fd);
1927 }
1928
Eric Laurent4d416952014-08-10 14:07:09 -07001929 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1930 write(fd, buffer, strlen(buffer));
1931 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1932 mAudioPatches[i]->dump(fd, 2, i);
1933 }
Eric Laurente552edb2014-03-10 17:42:56 -07001934
1935 return NO_ERROR;
1936}
1937
1938// This function checks for the parameters which can be offloaded.
1939// This can be enhanced depending on the capability of the DSP and policy
1940// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001941bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001942{
1943 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001944 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001945 offloadInfo.sample_rate, offloadInfo.channel_mask,
1946 offloadInfo.format,
1947 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1948 offloadInfo.has_video);
1949
1950 // Check if offload has been disabled
1951 char propValue[PROPERTY_VALUE_MAX];
1952 if (property_get("audio.offload.disable", propValue, "0")) {
1953 if (atoi(propValue) != 0) {
1954 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1955 return false;
1956 }
1957 }
1958
1959 // Check if stream type is music, then only allow offload as of now.
1960 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1961 {
1962 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1963 return false;
1964 }
1965
1966 //TODO: enable audio offloading with video when ready
1967 if (offloadInfo.has_video)
1968 {
1969 ALOGV("isOffloadSupported: has_video == true, returning false");
1970 return false;
1971 }
1972
1973 //If duration is less than minimum value defined in property, return false
1974 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1975 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1976 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1977 return false;
1978 }
1979 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1980 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1981 return false;
1982 }
1983
1984 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1985 // creating an offloaded track and tearing it down immediately after start when audioflinger
1986 // detects there is an active non offloadable effect.
1987 // FIXME: We should check the audio session here but we do not have it in this context.
1988 // This may prevent offloading in rare situations where effects are left active by apps
1989 // in the background.
1990 if (isNonOffloadableEffectEnabled()) {
1991 return false;
1992 }
1993
1994 // See if there is a profile to support this.
1995 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001996 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001997 offloadInfo.sample_rate,
1998 offloadInfo.format,
1999 offloadInfo.channel_mask,
2000 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002001 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2002 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002003}
2004
Eric Laurent6a94d692014-05-20 11:18:06 -07002005status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2006 audio_port_type_t type,
2007 unsigned int *num_ports,
2008 struct audio_port *ports,
2009 unsigned int *generation)
2010{
2011 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2012 generation == NULL) {
2013 return BAD_VALUE;
2014 }
2015 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2016 if (ports == NULL) {
2017 *num_ports = 0;
2018 }
2019
2020 size_t portsWritten = 0;
2021 size_t portsMax = *num_ports;
2022 *num_ports = 0;
2023 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2024 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2025 for (size_t i = 0;
2026 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2027 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2028 }
2029 *num_ports += mAvailableOutputDevices.size();
2030 }
2031 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2032 for (size_t i = 0;
2033 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2034 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2035 }
2036 *num_ports += mAvailableInputDevices.size();
2037 }
2038 }
2039 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2040 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2041 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2042 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2043 }
2044 *num_ports += mInputs.size();
2045 }
2046 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002047 size_t numOutputs = 0;
2048 for (size_t i = 0; i < mOutputs.size(); i++) {
2049 if (!mOutputs[i]->isDuplicated()) {
2050 numOutputs++;
2051 if (portsWritten < portsMax) {
2052 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2053 }
2054 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002055 }
Eric Laurent84c70242014-06-23 08:46:27 -07002056 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002057 }
2058 }
2059 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002060 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002061 return NO_ERROR;
2062}
2063
2064status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2065{
2066 return NO_ERROR;
2067}
2068
Eric Laurent1f2f2232014-06-02 12:01:23 -07002069sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002070 audio_port_handle_t id) const
2071{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002072 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002073 for (size_t i = 0; i < mOutputs.size(); i++) {
2074 outputDesc = mOutputs.valueAt(i);
2075 if (outputDesc->mId == id) {
2076 break;
2077 }
2078 }
2079 return outputDesc;
2080}
2081
Eric Laurent1f2f2232014-06-02 12:01:23 -07002082sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002083 audio_port_handle_t id) const
2084{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002085 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002086 for (size_t i = 0; i < mInputs.size(); i++) {
2087 inputDesc = mInputs.valueAt(i);
2088 if (inputDesc->mId == id) {
2089 break;
2090 }
2091 }
2092 return inputDesc;
2093}
2094
Eric Laurent1f2f2232014-06-02 12:01:23 -07002095sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2096 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002097{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002098 sp <HwModule> module;
2099
Eric Laurent6a94d692014-05-20 11:18:06 -07002100 for (size_t i = 0; i < mHwModules.size(); i++) {
2101 if (mHwModules[i]->mHandle == 0) {
2102 continue;
2103 }
2104 if (audio_is_output_device(device)) {
2105 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2106 {
2107 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2108 return mHwModules[i];
2109 }
2110 }
2111 } else {
2112 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2113 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2114 device & ~AUDIO_DEVICE_BIT_IN) {
2115 return mHwModules[i];
2116 }
2117 }
2118 }
2119 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002120 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002121}
2122
Eric Laurent1f2f2232014-06-02 12:01:23 -07002123sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002124{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002125 sp <HwModule> module;
2126
Eric Laurent1afeecb2014-05-14 08:52:28 -07002127 for (size_t i = 0; i < mHwModules.size(); i++)
2128 {
2129 if (strcmp(mHwModules[i]->mName, name) == 0) {
2130 return mHwModules[i];
2131 }
2132 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002133 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002134}
2135
Eric Laurentc2730ba2014-07-20 15:47:07 -07002136audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2137{
2138 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2139 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2140 return devices & mAvailableOutputDevices.types();
2141}
2142
2143audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2144{
2145 audio_module_handle_t primaryHandle =
2146 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2147 audio_devices_t devices = AUDIO_DEVICE_NONE;
2148 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2149 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2150 devices |= mAvailableInputDevices[i]->mDeviceType;
2151 }
2152 }
2153 return devices;
2154}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002155
Eric Laurent6a94d692014-05-20 11:18:06 -07002156status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2157 audio_patch_handle_t *handle,
2158 uid_t uid)
2159{
2160 ALOGV("createAudioPatch()");
2161
2162 if (handle == NULL || patch == NULL) {
2163 return BAD_VALUE;
2164 }
2165 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2166
Eric Laurent874c42872014-08-08 15:13:39 -07002167 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2168 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2169 return BAD_VALUE;
2170 }
2171 // only one source per audio patch supported for now
2172 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002173 return INVALID_OPERATION;
2174 }
Eric Laurent874c42872014-08-08 15:13:39 -07002175
2176 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002177 return INVALID_OPERATION;
2178 }
Eric Laurent874c42872014-08-08 15:13:39 -07002179 for (size_t i = 0; i < patch->num_sinks; i++) {
2180 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2181 return INVALID_OPERATION;
2182 }
2183 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002184
2185 sp<AudioPatch> patchDesc;
2186 ssize_t index = mAudioPatches.indexOfKey(*handle);
2187
Eric Laurent6a94d692014-05-20 11:18:06 -07002188 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2189 patch->sources[0].role,
2190 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002191#if LOG_NDEBUG == 0
2192 for (size_t i = 0; i < patch->num_sinks; i++) {
2193 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2194 patch->sinks[i].role,
2195 patch->sinks[i].type);
2196 }
2197#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002198
2199 if (index >= 0) {
2200 patchDesc = mAudioPatches.valueAt(index);
2201 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2202 mUidCached, patchDesc->mUid, uid);
2203 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2204 return INVALID_OPERATION;
2205 }
2206 } else {
2207 *handle = 0;
2208 }
2209
2210 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002211 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002212 if (outputDesc == NULL) {
2213 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2214 return BAD_VALUE;
2215 }
Eric Laurent84c70242014-06-23 08:46:27 -07002216 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2217 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002218 if (patchDesc != 0) {
2219 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2220 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2221 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2222 return BAD_VALUE;
2223 }
2224 }
Eric Laurent874c42872014-08-08 15:13:39 -07002225 DeviceVector devices;
2226 for (size_t i = 0; i < patch->num_sinks; i++) {
2227 // Only support mix to devices connection
2228 // TODO add support for mix to mix connection
2229 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2230 ALOGV("createAudioPatch() source mix but sink is not a device");
2231 return INVALID_OPERATION;
2232 }
2233 sp<DeviceDescriptor> devDesc =
2234 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2235 if (devDesc == 0) {
2236 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2237 return BAD_VALUE;
2238 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002239
Eric Laurent874c42872014-08-08 15:13:39 -07002240 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2241 patch->sources[0].sample_rate,
2242 NULL, // updatedSamplingRate
2243 patch->sources[0].format,
2244 patch->sources[0].channel_mask,
2245 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2246 ALOGV("createAudioPatch() profile not supported for device %08x",
2247 devDesc->mDeviceType);
2248 return INVALID_OPERATION;
2249 }
2250 devices.add(devDesc);
2251 }
2252 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002253 return INVALID_OPERATION;
2254 }
Eric Laurent874c42872014-08-08 15:13:39 -07002255
Eric Laurent6a94d692014-05-20 11:18:06 -07002256 // TODO: reconfigure output format and channels here
2257 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002258 devices.types(), outputDesc->mIoHandle);
2259 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002260 index = mAudioPatches.indexOfKey(*handle);
2261 if (index >= 0) {
2262 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2263 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2264 }
2265 patchDesc = mAudioPatches.valueAt(index);
2266 patchDesc->mUid = uid;
2267 ALOGV("createAudioPatch() success");
2268 } else {
2269 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2270 return INVALID_OPERATION;
2271 }
2272 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2273 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2274 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002275 // only one sink supported when connecting an input device to a mix
2276 if (patch->num_sinks > 1) {
2277 return INVALID_OPERATION;
2278 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002279 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002280 if (inputDesc == NULL) {
2281 return BAD_VALUE;
2282 }
2283 if (patchDesc != 0) {
2284 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2285 return BAD_VALUE;
2286 }
2287 }
2288 sp<DeviceDescriptor> devDesc =
2289 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2290 if (devDesc == 0) {
2291 return BAD_VALUE;
2292 }
2293
Eric Laurent84c70242014-06-23 08:46:27 -07002294 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002295 patch->sinks[0].sample_rate,
2296 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002297 patch->sinks[0].format,
2298 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002299 // FIXME for the parameter type,
2300 // and the NONE
2301 (audio_output_flags_t)
2302 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002303 return INVALID_OPERATION;
2304 }
2305 // TODO: reconfigure output format and channels here
2306 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002307 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002308 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002309 index = mAudioPatches.indexOfKey(*handle);
2310 if (index >= 0) {
2311 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2312 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2313 }
2314 patchDesc = mAudioPatches.valueAt(index);
2315 patchDesc->mUid = uid;
2316 ALOGV("createAudioPatch() success");
2317 } else {
2318 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2319 return INVALID_OPERATION;
2320 }
2321 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2322 // device to device connection
2323 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002324 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002325 return BAD_VALUE;
2326 }
2327 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002328 sp<DeviceDescriptor> srcDeviceDesc =
2329 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002330 if (srcDeviceDesc == 0) {
2331 return BAD_VALUE;
2332 }
Eric Laurent874c42872014-08-08 15:13:39 -07002333
Eric Laurent6a94d692014-05-20 11:18:06 -07002334 //update source and sink with our own data as the data passed in the patch may
2335 // be incomplete.
2336 struct audio_patch newPatch = *patch;
2337 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002338
Eric Laurent874c42872014-08-08 15:13:39 -07002339 for (size_t i = 0; i < patch->num_sinks; i++) {
2340 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2341 ALOGV("createAudioPatch() source device but one sink is not a device");
2342 return INVALID_OPERATION;
2343 }
2344
2345 sp<DeviceDescriptor> sinkDeviceDesc =
2346 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2347 if (sinkDeviceDesc == 0) {
2348 return BAD_VALUE;
2349 }
2350 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2351
2352 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2353 // only one sink supported when connected devices across HW modules
2354 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002355 return INVALID_OPERATION;
2356 }
Eric Laurent874c42872014-08-08 15:13:39 -07002357 SortedVector<audio_io_handle_t> outputs =
2358 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2359 mOutputs);
2360 // if the sink device is reachable via an opened output stream, request to go via
2361 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002362 audio_io_handle_t output = selectOutput(outputs,
2363 AUDIO_OUTPUT_FLAG_NONE,
2364 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002365 if (output != AUDIO_IO_HANDLE_NONE) {
2366 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2367 if (outputDesc->isDuplicated()) {
2368 return INVALID_OPERATION;
2369 }
2370 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2371 newPatch.num_sources = 2;
2372 }
Eric Laurent83b88082014-06-20 18:31:16 -07002373 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002374 }
2375 // TODO: check from routing capabilities in config file and other conflicting patches
2376
2377 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2378 if (index >= 0) {
2379 afPatchHandle = patchDesc->mAfPatchHandle;
2380 }
2381
2382 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2383 &afPatchHandle,
2384 0);
2385 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2386 status, afPatchHandle);
2387 if (status == NO_ERROR) {
2388 if (index < 0) {
2389 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2390 &newPatch, uid);
2391 addAudioPatch(patchDesc->mHandle, patchDesc);
2392 } else {
2393 patchDesc->mPatch = newPatch;
2394 }
2395 patchDesc->mAfPatchHandle = afPatchHandle;
2396 *handle = patchDesc->mHandle;
2397 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002398 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002399 } else {
2400 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2401 status);
2402 return INVALID_OPERATION;
2403 }
2404 } else {
2405 return BAD_VALUE;
2406 }
2407 } else {
2408 return BAD_VALUE;
2409 }
2410 return NO_ERROR;
2411}
2412
2413status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2414 uid_t uid)
2415{
2416 ALOGV("releaseAudioPatch() patch %d", handle);
2417
2418 ssize_t index = mAudioPatches.indexOfKey(handle);
2419
2420 if (index < 0) {
2421 return BAD_VALUE;
2422 }
2423 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2424 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2425 mUidCached, patchDesc->mUid, uid);
2426 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2427 return INVALID_OPERATION;
2428 }
2429
2430 struct audio_patch *patch = &patchDesc->mPatch;
2431 patchDesc->mUid = mUidCached;
2432 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002433 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002434 if (outputDesc == NULL) {
2435 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2436 return BAD_VALUE;
2437 }
2438
2439 setOutputDevice(outputDesc->mIoHandle,
2440 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2441 true,
2442 0,
2443 NULL);
2444 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2445 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002446 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002447 if (inputDesc == NULL) {
2448 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2449 return BAD_VALUE;
2450 }
2451 setInputDevice(inputDesc->mIoHandle,
2452 getNewInputDevice(inputDesc->mIoHandle),
2453 true,
2454 NULL);
2455 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2456 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2457 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2458 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2459 status, patchDesc->mAfPatchHandle);
2460 removeAudioPatch(patchDesc->mHandle);
2461 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002462 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002463 } else {
2464 return BAD_VALUE;
2465 }
2466 } else {
2467 return BAD_VALUE;
2468 }
2469 return NO_ERROR;
2470}
2471
2472status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2473 struct audio_patch *patches,
2474 unsigned int *generation)
2475{
2476 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2477 generation == NULL) {
2478 return BAD_VALUE;
2479 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002480 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002481 *num_patches, patches, mAudioPatches.size());
2482 if (patches == NULL) {
2483 *num_patches = 0;
2484 }
2485
2486 size_t patchesWritten = 0;
2487 size_t patchesMax = *num_patches;
2488 for (size_t i = 0;
2489 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2490 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2491 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002492 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002493 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2494 }
2495 *num_patches = mAudioPatches.size();
2496
2497 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002498 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002499 return NO_ERROR;
2500}
2501
Eric Laurente1715a42014-05-20 11:30:42 -07002502status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002503{
Eric Laurente1715a42014-05-20 11:30:42 -07002504 ALOGV("setAudioPortConfig()");
2505
2506 if (config == NULL) {
2507 return BAD_VALUE;
2508 }
2509 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2510 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002511 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2512 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002513 }
2514
Eric Laurenta121f902014-06-03 13:32:54 -07002515 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002516 if (config->type == AUDIO_PORT_TYPE_MIX) {
2517 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002518 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002519 if (outputDesc == NULL) {
2520 return BAD_VALUE;
2521 }
Eric Laurent84c70242014-06-23 08:46:27 -07002522 ALOG_ASSERT(!outputDesc->isDuplicated(),
2523 "setAudioPortConfig() called on duplicated output %d",
2524 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002525 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002526 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002527 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002528 if (inputDesc == NULL) {
2529 return BAD_VALUE;
2530 }
Eric Laurenta121f902014-06-03 13:32:54 -07002531 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002532 } else {
2533 return BAD_VALUE;
2534 }
2535 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2536 sp<DeviceDescriptor> deviceDesc;
2537 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2538 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2539 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2540 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2541 } else {
2542 return BAD_VALUE;
2543 }
2544 if (deviceDesc == NULL) {
2545 return BAD_VALUE;
2546 }
Eric Laurenta121f902014-06-03 13:32:54 -07002547 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002548 } else {
2549 return BAD_VALUE;
2550 }
2551
Eric Laurenta121f902014-06-03 13:32:54 -07002552 struct audio_port_config backupConfig;
2553 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2554 if (status == NO_ERROR) {
2555 struct audio_port_config newConfig;
2556 audioPortConfig->toAudioPortConfig(&newConfig, config);
2557 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002558 }
Eric Laurenta121f902014-06-03 13:32:54 -07002559 if (status != NO_ERROR) {
2560 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002561 }
Eric Laurente1715a42014-05-20 11:30:42 -07002562
2563 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002564}
2565
2566void AudioPolicyManager::clearAudioPatches(uid_t uid)
2567{
2568 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2569 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2570 if (patchDesc->mUid == uid) {
2571 // releaseAudioPatch() removes the patch from mAudioPatches
2572 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2573 i--;
2574 }
2575 }
2576 }
2577}
2578
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002579status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2580 audio_io_handle_t *ioHandle,
2581 audio_devices_t *device)
2582{
2583 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2584 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2585 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2586
2587 mSoundTriggerSessions.add(*session, *ioHandle);
2588
2589 return NO_ERROR;
2590}
2591
2592status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2593{
2594 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2595 if (index < 0) {
2596 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2597 return BAD_VALUE;
2598 }
2599
2600 mSoundTriggerSessions.removeItem(session);
2601 return NO_ERROR;
2602}
2603
Eric Laurent6a94d692014-05-20 11:18:06 -07002604status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2605 const sp<AudioPatch>& patch)
2606{
2607 ssize_t index = mAudioPatches.indexOfKey(handle);
2608
2609 if (index >= 0) {
2610 ALOGW("addAudioPatch() patch %d already in", handle);
2611 return ALREADY_EXISTS;
2612 }
2613 mAudioPatches.add(handle, patch);
2614 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2615 "sink handle %d",
2616 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2617 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2618 return NO_ERROR;
2619}
2620
2621status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2622{
2623 ssize_t index = mAudioPatches.indexOfKey(handle);
2624
2625 if (index < 0) {
2626 ALOGW("removeAudioPatch() patch %d not in", handle);
2627 return ALREADY_EXISTS;
2628 }
2629 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2630 mAudioPatches.valueAt(index)->mAfPatchHandle);
2631 mAudioPatches.removeItemsAt(index);
2632 return NO_ERROR;
2633}
2634
Eric Laurente552edb2014-03-10 17:42:56 -07002635// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002636// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002637// ----------------------------------------------------------------------------
2638
Eric Laurent3a4311c2014-03-17 12:00:47 -07002639uint32_t AudioPolicyManager::nextUniqueId()
2640{
2641 return android_atomic_inc(&mNextUniqueId);
2642}
2643
Eric Laurent6a94d692014-05-20 11:18:06 -07002644uint32_t AudioPolicyManager::nextAudioPortGeneration()
2645{
2646 return android_atomic_inc(&mAudioPortGeneration);
2647}
2648
Eric Laurente0720872014-03-11 09:30:41 -07002649AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002650 :
2651#ifdef AUDIO_POLICY_TEST
2652 Thread(false),
2653#endif //AUDIO_POLICY_TEST
2654 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002655 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002656 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2657 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002658 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002659 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Eric Laurent95511ad2014-10-10 15:31:38 -07002660 mAudioPortGeneration(1),
2661 mForceDeepBufferForMedia(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002662{
Eric Laurent95511ad2014-10-10 15:31:38 -07002663 char propValue[PROPERTY_VALUE_MAX];
2664 if (property_get("ro.audio.media_deep_buffer", propValue, "0")) {
2665 mForceDeepBufferForMedia = atoi(propValue);
2666 }
2667
Eric Laurent6a94d692014-05-20 11:18:06 -07002668 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002669 mpClientInterface = clientInterface;
2670
Eric Laurent3b73df72014-03-11 09:06:29 -07002671 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2672 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002673 }
2674
Eric Laurent1afeecb2014-05-14 08:52:28 -07002675 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002676 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2677 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2678 ALOGE("could not load audio policy configuration file, setting defaults");
2679 defaultAudioPolicyConfig();
2680 }
2681 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002682 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002683
2684 // must be done after reading the policy
2685 initializeVolumeCurves();
2686
2687 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002688 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2689 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002690 for (size_t i = 0; i < mHwModules.size(); i++) {
2691 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2692 if (mHwModules[i]->mHandle == 0) {
2693 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2694 continue;
2695 }
2696 // open all output streams needed to access attached devices
2697 // except for direct output streams that are only opened when they are actually
2698 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002699 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002700 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2701 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002702 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002703
Eric Laurent3a4311c2014-03-17 12:00:47 -07002704 if (outProfile->mSupportedDevices.isEmpty()) {
2705 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2706 continue;
2707 }
2708
Eric Laurentd78f1532014-09-16 16:38:20 -07002709 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2710 continue;
2711 }
Eric Laurent83b88082014-06-20 18:31:16 -07002712 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2713 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2714 profileType = mDefaultOutputDevice->mDeviceType;
2715 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002716 // chose first device present in mSupportedDevices also part of
2717 // outputDeviceTypes
2718 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2719 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2720 if ((profileType & outputDeviceTypes) != 0) {
2721 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002722 }
Eric Laurente552edb2014-03-10 17:42:56 -07002723 }
2724 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002725 if ((profileType & outputDeviceTypes) == 0) {
2726 continue;
2727 }
2728 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2729
2730 outputDesc->mDevice = profileType;
2731 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2732 config.sample_rate = outputDesc->mSamplingRate;
2733 config.channel_mask = outputDesc->mChannelMask;
2734 config.format = outputDesc->mFormat;
2735 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2736 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2737 &output,
2738 &config,
2739 &outputDesc->mDevice,
2740 String8(""),
2741 &outputDesc->mLatency,
2742 outputDesc->mFlags);
2743
2744 if (status != NO_ERROR) {
2745 ALOGW("Cannot open output stream for device %08x on hw module %s",
2746 outputDesc->mDevice,
2747 mHwModules[i]->mName);
2748 } else {
2749 outputDesc->mSamplingRate = config.sample_rate;
2750 outputDesc->mChannelMask = config.channel_mask;
2751 outputDesc->mFormat = config.format;
2752
2753 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2754 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2755 ssize_t index =
2756 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2757 // give a valid ID to an attached device once confirmed it is reachable
2758 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2759 mAvailableOutputDevices[index]->mId = nextUniqueId();
2760 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2761 }
2762 }
2763 if (mPrimaryOutput == 0 &&
2764 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2765 mPrimaryOutput = output;
2766 }
2767 addOutput(output, outputDesc);
2768 setOutputDevice(output,
2769 outputDesc->mDevice,
2770 true);
2771 }
Eric Laurente552edb2014-03-10 17:42:56 -07002772 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002773 // open input streams needed to access attached devices to validate
2774 // mAvailableInputDevices list
2775 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2776 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002777 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002778
Eric Laurent3a4311c2014-03-17 12:00:47 -07002779 if (inProfile->mSupportedDevices.isEmpty()) {
2780 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2781 continue;
2782 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002783 // chose first device present in mSupportedDevices also part of
2784 // inputDeviceTypes
2785 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2786 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2787 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2788 if (profileType & inputDeviceTypes) {
2789 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002790 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002791 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002792 if ((profileType & inputDeviceTypes) == 0) {
2793 continue;
2794 }
2795 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2796
2797 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2798 inputDesc->mDevice = profileType;
2799
2800 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2801 config.sample_rate = inputDesc->mSamplingRate;
2802 config.channel_mask = inputDesc->mChannelMask;
2803 config.format = inputDesc->mFormat;
2804 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2805 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2806 &input,
2807 &config,
2808 &inputDesc->mDevice,
2809 String8(""),
2810 AUDIO_SOURCE_MIC,
2811 AUDIO_INPUT_FLAG_NONE);
2812
2813 if (status == NO_ERROR) {
2814 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2815 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2816 ssize_t index =
2817 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2818 // give a valid ID to an attached device once confirmed it is reachable
2819 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2820 mAvailableInputDevices[index]->mId = nextUniqueId();
2821 mAvailableInputDevices[index]->mModule = mHwModules[i];
2822 }
2823 }
2824 mpClientInterface->closeInput(input);
2825 } else {
2826 ALOGW("Cannot open input stream for device %08x on hw module %s",
2827 inputDesc->mDevice,
2828 mHwModules[i]->mName);
2829 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002830 }
2831 }
2832 // make sure all attached devices have been allocated a unique ID
2833 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2834 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002835 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002836 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2837 continue;
2838 }
2839 i++;
2840 }
2841 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2842 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002843 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002844 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2845 continue;
2846 }
2847 i++;
2848 }
2849 // make sure default device is reachable
2850 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002851 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002852 }
Eric Laurente552edb2014-03-10 17:42:56 -07002853
2854 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2855
2856 updateDevicesAndOutputs();
2857
2858#ifdef AUDIO_POLICY_TEST
2859 if (mPrimaryOutput != 0) {
2860 AudioParameter outputCmd = AudioParameter();
2861 outputCmd.addInt(String8("set_id"), 0);
2862 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2863
2864 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2865 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002866 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2867 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002868 mTestLatencyMs = 0;
2869 mCurOutput = 0;
2870 mDirectOutput = false;
2871 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2872 mTestOutputs[i] = 0;
2873 }
2874
2875 const size_t SIZE = 256;
2876 char buffer[SIZE];
2877 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2878 run(buffer, ANDROID_PRIORITY_AUDIO);
2879 }
2880#endif //AUDIO_POLICY_TEST
2881}
2882
Eric Laurente0720872014-03-11 09:30:41 -07002883AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002884{
2885#ifdef AUDIO_POLICY_TEST
2886 exit();
2887#endif //AUDIO_POLICY_TEST
2888 for (size_t i = 0; i < mOutputs.size(); i++) {
2889 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002890 }
2891 for (size_t i = 0; i < mInputs.size(); i++) {
2892 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002893 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002894 mAvailableOutputDevices.clear();
2895 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002896 mOutputs.clear();
2897 mInputs.clear();
2898 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002899}
2900
Eric Laurente0720872014-03-11 09:30:41 -07002901status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002902{
2903 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2904}
2905
2906#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002907bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002908{
2909 ALOGV("entering threadLoop()");
2910 while (!exitPending())
2911 {
2912 String8 command;
2913 int valueInt;
2914 String8 value;
2915
2916 Mutex::Autolock _l(mLock);
2917 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2918
2919 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2920 AudioParameter param = AudioParameter(command);
2921
2922 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2923 valueInt != 0) {
2924 ALOGV("Test command %s received", command.string());
2925 String8 target;
2926 if (param.get(String8("target"), target) != NO_ERROR) {
2927 target = "Manager";
2928 }
2929 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2930 param.remove(String8("test_cmd_policy_output"));
2931 mCurOutput = valueInt;
2932 }
2933 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2934 param.remove(String8("test_cmd_policy_direct"));
2935 if (value == "false") {
2936 mDirectOutput = false;
2937 } else if (value == "true") {
2938 mDirectOutput = true;
2939 }
2940 }
2941 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2942 param.remove(String8("test_cmd_policy_input"));
2943 mTestInput = valueInt;
2944 }
2945
2946 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2947 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002948 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002949 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002950 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002951 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002952 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002953 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002954 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002955 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002956 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002957 if (target == "Manager") {
2958 mTestFormat = format;
2959 } else if (mTestOutputs[mCurOutput] != 0) {
2960 AudioParameter outputParam = AudioParameter();
2961 outputParam.addInt(String8("format"), format);
2962 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2963 }
2964 }
2965 }
2966 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2967 param.remove(String8("test_cmd_policy_channels"));
2968 int channels = 0;
2969
2970 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002971 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002972 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002973 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002974 }
2975 if (channels != 0) {
2976 if (target == "Manager") {
2977 mTestChannels = channels;
2978 } else if (mTestOutputs[mCurOutput] != 0) {
2979 AudioParameter outputParam = AudioParameter();
2980 outputParam.addInt(String8("channels"), channels);
2981 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2982 }
2983 }
2984 }
2985 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2986 param.remove(String8("test_cmd_policy_sampleRate"));
2987 if (valueInt >= 0 && valueInt <= 96000) {
2988 int samplingRate = valueInt;
2989 if (target == "Manager") {
2990 mTestSamplingRate = samplingRate;
2991 } else if (mTestOutputs[mCurOutput] != 0) {
2992 AudioParameter outputParam = AudioParameter();
2993 outputParam.addInt(String8("sampling_rate"), samplingRate);
2994 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2995 }
2996 }
2997 }
2998
2999 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3000 param.remove(String8("test_cmd_policy_reopen"));
3001
Eric Laurent1f2f2232014-06-02 12:01:23 -07003002 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003003 mpClientInterface->closeOutput(mPrimaryOutput);
3004
3005 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3006
Eric Laurente552edb2014-03-10 17:42:56 -07003007 mOutputs.removeItem(mPrimaryOutput);
3008
Eric Laurent1f2f2232014-06-02 12:01:23 -07003009 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003010 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003011 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3012 config.sample_rate = outputDesc->mSamplingRate;
3013 config.channel_mask = outputDesc->mChannelMask;
3014 config.format = outputDesc->mFormat;
3015 status_t status = mpClientInterface->openOutput(moduleHandle,
3016 &mPrimaryOutput,
3017 &config,
3018 &outputDesc->mDevice,
3019 String8(""),
3020 &outputDesc->mLatency,
3021 outputDesc->mFlags);
3022 if (status != NO_ERROR) {
3023 ALOGE("Failed to reopen hardware output stream, "
3024 "samplingRate: %d, format %d, channels %d",
3025 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003026 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003027 outputDesc->mSamplingRate = config.sample_rate;
3028 outputDesc->mChannelMask = config.channel_mask;
3029 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003030 AudioParameter outputCmd = AudioParameter();
3031 outputCmd.addInt(String8("set_id"), 0);
3032 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3033 addOutput(mPrimaryOutput, outputDesc);
3034 }
3035 }
3036
3037
3038 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3039 }
3040 }
3041 return false;
3042}
3043
Eric Laurente0720872014-03-11 09:30:41 -07003044void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003045{
3046 {
3047 AutoMutex _l(mLock);
3048 requestExit();
3049 mWaitWorkCV.signal();
3050 }
3051 requestExitAndWait();
3052}
3053
Eric Laurente0720872014-03-11 09:30:41 -07003054int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003055{
3056 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3057 if (output == mTestOutputs[i]) return i;
3058 }
3059 return 0;
3060}
3061#endif //AUDIO_POLICY_TEST
3062
3063// ---
3064
Eric Laurent1f2f2232014-06-02 12:01:23 -07003065void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003066{
Eric Laurent1c333e22014-05-20 10:48:17 -07003067 outputDesc->mIoHandle = output;
3068 outputDesc->mId = nextUniqueId();
3069 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003070 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003071}
3072
Eric Laurent1f2f2232014-06-02 12:01:23 -07003073void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003074{
Eric Laurent1c333e22014-05-20 10:48:17 -07003075 inputDesc->mIoHandle = input;
3076 inputDesc->mId = nextUniqueId();
3077 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003078 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003079}
Eric Laurente552edb2014-03-10 17:42:56 -07003080
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003081void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3082 const String8 address /*in*/,
3083 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3084 // look for a match on the given address on the addresses of the outputs:
3085 // find the address by finding the patch that maps to this output
3086 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3087 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3088 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3089 if (patchIdx >= 0) {
3090 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3091 const int numSinks = patchDesc->mPatch.num_sinks;
3092 for (ssize_t j=0; j < numSinks; j++) {
3093 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3094 const char* patchAddr =
3095 patchDesc->mPatch.sinks[j].ext.device.address;
3096 if (strncmp(patchAddr,
3097 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003098 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003099 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3100 outputs.add(desc->mIoHandle);
3101 break;
3102 }
3103 }
3104 }
3105 }
3106}
3107
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003108status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003109 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003110 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003111 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003112{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003113 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003114 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003115 // erase all current sample rates, formats and channel masks
3116 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003117
Eric Laurent3b73df72014-03-11 09:06:29 -07003118 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003119 // first list already open outputs that can be routed to this device
3120 for (size_t i = 0; i < mOutputs.size(); i++) {
3121 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003122 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003123 if (!deviceDistinguishesOnAddress(device)) {
3124 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3125 outputs.add(mOutputs.keyAt(i));
3126 } else {
3127 ALOGV(" checking address match due to device 0x%x", device);
3128 findIoHandlesByAddress(desc, address, outputs);
3129 }
Eric Laurente552edb2014-03-10 17:42:56 -07003130 }
3131 }
3132 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003133 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003134 for (size_t i = 0; i < mHwModules.size(); i++)
3135 {
3136 if (mHwModules[i]->mHandle == 0) {
3137 continue;
3138 }
3139 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3140 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003141 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003142 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003143 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3144 }
3145 }
3146 }
3147
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003148 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3149
Eric Laurente552edb2014-03-10 17:42:56 -07003150 if (profiles.isEmpty() && outputs.isEmpty()) {
3151 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3152 return BAD_VALUE;
3153 }
3154
3155 // open outputs for matching profiles if needed. Direct outputs are also opened to
3156 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3157 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003158 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003159
3160 // nothing to do if one output is already opened for this profile
3161 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003162 for (j = 0; j < outputs.size(); j++) {
3163 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003164 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003165 // matching profile: save the sample rates, format and channel masks supported
3166 // by the profile in our device descriptor
3167 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003168 break;
3169 }
3170 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003171 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003172 continue;
3173 }
3174
Eric Laurent83b88082014-06-20 18:31:16 -07003175 ALOGV("opening output for device %08x with params %s profile %p",
3176 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003177 desc = new AudioOutputDescriptor(profile);
3178 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003179 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3180 config.sample_rate = desc->mSamplingRate;
3181 config.channel_mask = desc->mChannelMask;
3182 config.format = desc->mFormat;
3183 config.offload_info.sample_rate = desc->mSamplingRate;
3184 config.offload_info.channel_mask = desc->mChannelMask;
3185 config.offload_info.format = desc->mFormat;
3186 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3187 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3188 &output,
3189 &config,
3190 &desc->mDevice,
3191 address,
3192 &desc->mLatency,
3193 desc->mFlags);
3194 if (status == NO_ERROR) {
3195 desc->mSamplingRate = config.sample_rate;
3196 desc->mChannelMask = config.channel_mask;
3197 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003198
Eric Laurentd4692962014-05-05 18:13:44 -07003199 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003200 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003201 char *param = audio_device_address_to_parameter(device, address);
3202 mpClientInterface->setParameters(output, String8(param));
3203 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003204 }
3205
Eric Laurentd4692962014-05-05 18:13:44 -07003206 // Here is where we step through and resolve any "dynamic" fields
3207 String8 reply;
3208 char *value;
3209 if (profile->mSamplingRates[0] == 0) {
3210 reply = mpClientInterface->getParameters(output,
3211 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003212 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003213 reply.string());
3214 value = strpbrk((char *)reply.string(), "=");
3215 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003216 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003217 }
Eric Laurentd4692962014-05-05 18:13:44 -07003218 }
3219 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3220 reply = mpClientInterface->getParameters(output,
3221 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003222 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003223 reply.string());
3224 value = strpbrk((char *)reply.string(), "=");
3225 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003226 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003227 }
Eric Laurentd4692962014-05-05 18:13:44 -07003228 }
3229 if (profile->mChannelMasks[0] == 0) {
3230 reply = mpClientInterface->getParameters(output,
3231 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003232 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003233 reply.string());
3234 value = strpbrk((char *)reply.string(), "=");
3235 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003236 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003237 }
Eric Laurentd4692962014-05-05 18:13:44 -07003238 }
3239 if (((profile->mSamplingRates[0] == 0) &&
3240 (profile->mSamplingRates.size() < 2)) ||
3241 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3242 (profile->mFormats.size() < 2)) ||
3243 ((profile->mChannelMasks[0] == 0) &&
3244 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003245 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003246 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003247 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003248 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3249 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003250 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003251 config.sample_rate = profile->pickSamplingRate();
3252 config.channel_mask = profile->pickChannelMask();
3253 config.format = profile->pickFormat();
3254 config.offload_info.sample_rate = config.sample_rate;
3255 config.offload_info.channel_mask = config.channel_mask;
3256 config.offload_info.format = config.format;
3257 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3258 &output,
3259 &config,
3260 &desc->mDevice,
3261 address,
3262 &desc->mLatency,
3263 desc->mFlags);
3264 if (status == NO_ERROR) {
3265 desc->mSamplingRate = config.sample_rate;
3266 desc->mChannelMask = config.channel_mask;
3267 desc->mFormat = config.format;
3268 } else {
3269 output = AUDIO_IO_HANDLE_NONE;
3270 }
Eric Laurentd4692962014-05-05 18:13:44 -07003271 }
3272
Eric Laurentcf2c0212014-07-25 16:20:43 -07003273 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003274 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003275 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003276 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003277
Eric Laurentd4692962014-05-05 18:13:44 -07003278 // set initial stream volume for device
3279 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003280
Eric Laurentd4692962014-05-05 18:13:44 -07003281 //TODO: configure audio effect output stage here
3282
3283 // open a duplicating output thread for the new output and the primary output
3284 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3285 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003286 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003287 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003288 sp<AudioOutputDescriptor> dupOutputDesc =
3289 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003290 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3291 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3292 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3293 dupOutputDesc->mFormat = desc->mFormat;
3294 dupOutputDesc->mChannelMask = desc->mChannelMask;
3295 dupOutputDesc->mLatency = desc->mLatency;
3296 addOutput(duplicatedOutput, dupOutputDesc);
3297 applyStreamVolumes(duplicatedOutput, device, 0, true);
3298 } else {
3299 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3300 mPrimaryOutput, output);
3301 mpClientInterface->closeOutput(output);
3302 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003303 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003304 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003305 }
Eric Laurente552edb2014-03-10 17:42:56 -07003306 }
3307 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003308 } else {
3309 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003310 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003311 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003312 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003313 profiles.removeAt(profile_index);
3314 profile_index--;
3315 } else {
3316 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003317 devDesc->importAudioPort(profile);
3318
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003319 if (deviceDistinguishesOnAddress(device)) {
3320 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3321 device, address.string());
3322 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3323 NULL/*patch handle*/, address.string());
3324 }
Eric Laurente552edb2014-03-10 17:42:56 -07003325 ALOGV("checkOutputsForDevice(): adding output %d", output);
3326 }
3327 }
3328
3329 if (profiles.isEmpty()) {
3330 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3331 return BAD_VALUE;
3332 }
Eric Laurentd4692962014-05-05 18:13:44 -07003333 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003334 // check if one opened output is not needed any more after disconnecting one device
3335 for (size_t i = 0; i < mOutputs.size(); i++) {
3336 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003337 if (!desc->isDuplicated()) {
3338 if (!(desc->mProfile->mSupportedDevices.types()
3339 & mAvailableOutputDevices.types())) {
3340 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3341 mOutputs.keyAt(i));
3342 outputs.add(mOutputs.keyAt(i));
3343 } else if (deviceDistinguishesOnAddress(device) &&
3344 // exact match on device
3345 (desc->mProfile->mSupportedDevices.types() == device)) {
3346 findIoHandlesByAddress(desc, address, outputs);
3347 }
Eric Laurente552edb2014-03-10 17:42:56 -07003348 }
3349 }
Eric Laurentd4692962014-05-05 18:13:44 -07003350 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003351 for (size_t i = 0; i < mHwModules.size(); i++)
3352 {
3353 if (mHwModules[i]->mHandle == 0) {
3354 continue;
3355 }
3356 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3357 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003358 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003359 if (profile->mSupportedDevices.types() & device) {
3360 ALOGV("checkOutputsForDevice(): "
3361 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003362 if (profile->mSamplingRates[0] == 0) {
3363 profile->mSamplingRates.clear();
3364 profile->mSamplingRates.add(0);
3365 }
3366 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3367 profile->mFormats.clear();
3368 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3369 }
3370 if (profile->mChannelMasks[0] == 0) {
3371 profile->mChannelMasks.clear();
3372 profile->mChannelMasks.add(0);
3373 }
3374 }
3375 }
3376 }
3377 }
3378 return NO_ERROR;
3379}
3380
Eric Laurentd4692962014-05-05 18:13:44 -07003381status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3382 audio_policy_dev_state_t state,
3383 SortedVector<audio_io_handle_t>& inputs,
3384 const String8 address)
3385{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003386 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003387 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3388 // first list already open inputs that can be routed to this device
3389 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3390 desc = mInputs.valueAt(input_index);
3391 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3392 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3393 inputs.add(mInputs.keyAt(input_index));
3394 }
3395 }
3396
3397 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003398 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003399 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3400 {
3401 if (mHwModules[module_idx]->mHandle == 0) {
3402 continue;
3403 }
3404 for (size_t profile_index = 0;
3405 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3406 profile_index++)
3407 {
3408 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3409 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003410 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003411 profile_index, module_idx);
3412 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3413 }
3414 }
3415 }
3416
3417 if (profiles.isEmpty() && inputs.isEmpty()) {
3418 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3419 return BAD_VALUE;
3420 }
3421
3422 // open inputs for matching profiles if needed. Direct inputs are also opened to
3423 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3424 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3425
Eric Laurent1c333e22014-05-20 10:48:17 -07003426 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003427 // nothing to do if one input is already opened for this profile
3428 size_t input_index;
3429 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3430 desc = mInputs.valueAt(input_index);
3431 if (desc->mProfile == profile) {
3432 break;
3433 }
3434 }
3435 if (input_index != mInputs.size()) {
3436 continue;
3437 }
3438
3439 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3440 desc = new AudioInputDescriptor(profile);
3441 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003442 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3443 config.sample_rate = desc->mSamplingRate;
3444 config.channel_mask = desc->mChannelMask;
3445 config.format = desc->mFormat;
3446 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3447 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3448 &input,
3449 &config,
3450 &desc->mDevice,
3451 address,
3452 AUDIO_SOURCE_MIC,
3453 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003454
Eric Laurentcf2c0212014-07-25 16:20:43 -07003455 if (status == NO_ERROR) {
3456 desc->mSamplingRate = config.sample_rate;
3457 desc->mChannelMask = config.channel_mask;
3458 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003459
Eric Laurentd4692962014-05-05 18:13:44 -07003460 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003461 char *param = audio_device_address_to_parameter(device, address);
3462 mpClientInterface->setParameters(input, String8(param));
3463 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003464 }
3465
3466 // Here is where we step through and resolve any "dynamic" fields
3467 String8 reply;
3468 char *value;
3469 if (profile->mSamplingRates[0] == 0) {
3470 reply = mpClientInterface->getParameters(input,
3471 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3472 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3473 reply.string());
3474 value = strpbrk((char *)reply.string(), "=");
3475 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003476 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003477 }
3478 }
3479 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3480 reply = mpClientInterface->getParameters(input,
3481 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3482 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3483 value = strpbrk((char *)reply.string(), "=");
3484 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003485 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003486 }
3487 }
3488 if (profile->mChannelMasks[0] == 0) {
3489 reply = mpClientInterface->getParameters(input,
3490 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3491 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3492 reply.string());
3493 value = strpbrk((char *)reply.string(), "=");
3494 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003495 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003496 }
3497 }
3498 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3499 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3500 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3501 ALOGW("checkInputsForDevice() direct input missing param");
3502 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003503 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003504 }
3505
3506 if (input != 0) {
3507 addInput(input, desc);
3508 }
3509 } // endif input != 0
3510
Eric Laurentcf2c0212014-07-25 16:20:43 -07003511 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003512 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003513 profiles.removeAt(profile_index);
3514 profile_index--;
3515 } else {
3516 inputs.add(input);
3517 ALOGV("checkInputsForDevice(): adding input %d", input);
3518 }
3519 } // end scan profiles
3520
3521 if (profiles.isEmpty()) {
3522 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3523 return BAD_VALUE;
3524 }
3525 } else {
3526 // Disconnect
3527 // check if one opened input is not needed any more after disconnecting one device
3528 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3529 desc = mInputs.valueAt(input_index);
3530 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3531 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3532 mInputs.keyAt(input_index));
3533 inputs.add(mInputs.keyAt(input_index));
3534 }
3535 }
3536 // Clear any profiles associated with the disconnected device.
3537 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3538 if (mHwModules[module_index]->mHandle == 0) {
3539 continue;
3540 }
3541 for (size_t profile_index = 0;
3542 profile_index < mHwModules[module_index]->mInputProfiles.size();
3543 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003544 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003545 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003546 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003547 profile_index, module_index);
3548 if (profile->mSamplingRates[0] == 0) {
3549 profile->mSamplingRates.clear();
3550 profile->mSamplingRates.add(0);
3551 }
3552 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3553 profile->mFormats.clear();
3554 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3555 }
3556 if (profile->mChannelMasks[0] == 0) {
3557 profile->mChannelMasks.clear();
3558 profile->mChannelMasks.add(0);
3559 }
3560 }
3561 }
3562 }
3563 } // end disconnect
3564
3565 return NO_ERROR;
3566}
3567
3568
Eric Laurente0720872014-03-11 09:30:41 -07003569void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003570{
3571 ALOGV("closeOutput(%d)", output);
3572
Eric Laurent1f2f2232014-06-02 12:01:23 -07003573 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003574 if (outputDesc == NULL) {
3575 ALOGW("closeOutput() unknown output %d", output);
3576 return;
3577 }
3578
3579 // look for duplicated outputs connected to the output being removed.
3580 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003581 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003582 if (dupOutputDesc->isDuplicated() &&
3583 (dupOutputDesc->mOutput1 == outputDesc ||
3584 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003585 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003586 if (dupOutputDesc->mOutput1 == outputDesc) {
3587 outputDesc2 = dupOutputDesc->mOutput2;
3588 } else {
3589 outputDesc2 = dupOutputDesc->mOutput1;
3590 }
3591 // As all active tracks on duplicated output will be deleted,
3592 // and as they were also referenced on the other output, the reference
3593 // count for their stream type must be adjusted accordingly on
3594 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003595 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003596 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003597 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003598 }
3599 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3600 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3601
3602 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003603 mOutputs.removeItem(duplicatedOutput);
3604 }
3605 }
3606
Eric Laurent05b90f82014-08-27 15:32:29 -07003607 nextAudioPortGeneration();
3608
3609 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3610 if (index >= 0) {
3611 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3612 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3613 mAudioPatches.removeItemsAt(index);
3614 mpClientInterface->onAudioPatchListUpdate();
3615 }
3616
Eric Laurente552edb2014-03-10 17:42:56 -07003617 AudioParameter param;
3618 param.add(String8("closing"), String8("true"));
3619 mpClientInterface->setParameters(output, param.toString());
3620
3621 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003622 mOutputs.removeItem(output);
3623 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003624}
3625
3626void AudioPolicyManager::closeInput(audio_io_handle_t input)
3627{
3628 ALOGV("closeInput(%d)", input);
3629
3630 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3631 if (inputDesc == NULL) {
3632 ALOGW("closeInput() unknown input %d", input);
3633 return;
3634 }
3635
Eric Laurent6a94d692014-05-20 11:18:06 -07003636 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003637
3638 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3639 if (index >= 0) {
3640 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3641 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3642 mAudioPatches.removeItemsAt(index);
3643 mpClientInterface->onAudioPatchListUpdate();
3644 }
3645
3646 mpClientInterface->closeInput(input);
3647 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003648}
3649
Eric Laurente0720872014-03-11 09:30:41 -07003650SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003651 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003652{
3653 SortedVector<audio_io_handle_t> outputs;
3654
3655 ALOGVV("getOutputsForDevice() device %04x", device);
3656 for (size_t i = 0; i < openOutputs.size(); i++) {
3657 ALOGVV("output %d isDuplicated=%d device=%04x",
3658 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3659 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3660 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3661 outputs.add(openOutputs.keyAt(i));
3662 }
3663 }
3664 return outputs;
3665}
3666
Eric Laurente0720872014-03-11 09:30:41 -07003667bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003668 SortedVector<audio_io_handle_t>& outputs2)
3669{
3670 if (outputs1.size() != outputs2.size()) {
3671 return false;
3672 }
3673 for (size_t i = 0; i < outputs1.size(); i++) {
3674 if (outputs1[i] != outputs2[i]) {
3675 return false;
3676 }
3677 }
3678 return true;
3679}
3680
Eric Laurente0720872014-03-11 09:30:41 -07003681void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003682{
3683 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3684 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3685 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3686 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3687
3688 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3689 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3690 strategy, srcOutputs[0], dstOutputs[0]);
3691 // mute strategy while moving tracks from one output to another
3692 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003693 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003694 if (desc->isStrategyActive(strategy)) {
3695 setStrategyMute(strategy, true, srcOutputs[i]);
3696 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3697 }
3698 }
3699
3700 // Move effects associated to this strategy from previous output to new output
3701 if (strategy == STRATEGY_MEDIA) {
3702 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3703 SortedVector<audio_io_handle_t> moved;
3704 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003705 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3706 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3707 effectDesc->mIo != fxOutput) {
3708 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003709 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3710 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003711 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003712 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003713 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003714 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003715 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003716 }
3717 }
3718 }
3719 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003720 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3721 if (getStrategy((audio_stream_type_t)i) == strategy) {
3722 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003723 }
3724 }
3725 }
3726}
3727
Eric Laurente0720872014-03-11 09:30:41 -07003728void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003729{
Jon Eklund966095e2014-09-09 15:39:49 -05003730 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3731 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003732 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003733 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3734 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003735 checkOutputForStrategy(STRATEGY_SONIFICATION);
3736 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3737 checkOutputForStrategy(STRATEGY_MEDIA);
3738 checkOutputForStrategy(STRATEGY_DTMF);
3739}
3740
Eric Laurente0720872014-03-11 09:30:41 -07003741audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003742{
Eric Laurente552edb2014-03-10 17:42:56 -07003743 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003744 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003745 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3746 return mOutputs.keyAt(i);
3747 }
3748 }
3749
3750 return 0;
3751}
3752
Eric Laurente0720872014-03-11 09:30:41 -07003753void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003754{
Eric Laurente552edb2014-03-10 17:42:56 -07003755 audio_io_handle_t a2dpOutput = getA2dpOutput();
3756 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003757 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003758 return;
3759 }
3760
Eric Laurent3a4311c2014-03-17 12:00:47 -07003761 bool isScoConnected =
3762 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003763 // suspend A2DP output if:
3764 // (NOT already suspended) &&
3765 // ((SCO device is connected &&
3766 // (forced usage for communication || for record is SCO))) ||
3767 // (phone state is ringing || in call)
3768 //
3769 // restore A2DP output if:
3770 // (Already suspended) &&
3771 // ((SCO device is NOT connected ||
3772 // (forced usage NOT for communication && NOT for record is SCO))) &&
3773 // (phone state is NOT ringing && NOT in call)
3774 //
3775 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003776 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003777 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3778 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3779 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3780 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003781
3782 mpClientInterface->restoreOutput(a2dpOutput);
3783 mA2dpSuspended = false;
3784 }
3785 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003786 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003787 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3788 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3789 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3790 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003791
3792 mpClientInterface->suspendOutput(a2dpOutput);
3793 mA2dpSuspended = true;
3794 }
3795 }
3796}
3797
Eric Laurent1c333e22014-05-20 10:48:17 -07003798audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003799{
3800 audio_devices_t device = AUDIO_DEVICE_NONE;
3801
Eric Laurent1f2f2232014-06-02 12:01:23 -07003802 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003803
3804 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3805 if (index >= 0) {
3806 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3807 if (patchDesc->mUid != mUidCached) {
3808 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3809 outputDesc->device(), outputDesc->mPatchHandle);
3810 return outputDesc->device();
3811 }
3812 }
3813
Eric Laurente552edb2014-03-10 17:42:56 -07003814 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003815 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003816 // use device for strategy enforced audible
3817 // 2: we are in call or the strategy phone is active on the output:
3818 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003819 // 3: the strategy for enforced audible is active but not enforced on the output:
3820 // use the device for strategy enforced audible
3821 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003822 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003823 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003824 // use device for strategy "respectful" sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003825 // 6: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003826 // use device for strategy media
Jon Eklund966095e2014-09-09 15:39:49 -05003827 // 7: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003828 // use device for strategy DTMF
Jon Eklund966095e2014-09-09 15:39:49 -05003829 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3830 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003831 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3832 } else if (isInCall() ||
3833 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3834 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003835 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3836 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003837 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3838 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3839 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3840 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3841 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3842 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3843 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3844 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3845 }
3846
Eric Laurent1c333e22014-05-20 10:48:17 -07003847 ALOGV("getNewOutputDevice() selected device %x", device);
3848 return device;
3849}
3850
3851audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3852{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003853 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003854
3855 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3856 if (index >= 0) {
3857 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3858 if (patchDesc->mUid != mUidCached) {
3859 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3860 inputDesc->mDevice, inputDesc->mPatchHandle);
3861 return inputDesc->mDevice;
3862 }
3863 }
3864
Eric Laurent1c333e22014-05-20 10:48:17 -07003865 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3866
3867 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003868 return device;
3869}
3870
Eric Laurente0720872014-03-11 09:30:41 -07003871uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003872 return (uint32_t)getStrategy(stream);
3873}
3874
Eric Laurente0720872014-03-11 09:30:41 -07003875audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003876 // By checking the range of stream before calling getStrategy, we avoid
3877 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3878 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003879 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003880 return AUDIO_DEVICE_NONE;
3881 }
3882 audio_devices_t devices;
3883 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3884 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3885 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3886 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003887 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003888 if (outputDesc->isStrategyActive(strategy)) {
3889 devices = outputDesc->device();
3890 break;
3891 }
Eric Laurente552edb2014-03-10 17:42:56 -07003892 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003893
3894 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
3895 and doesn't really need to.*/
3896 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
3897 devices |= AUDIO_DEVICE_OUT_SPEAKER;
3898 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3899 }
3900
Eric Laurente552edb2014-03-10 17:42:56 -07003901 return devices;
3902}
3903
Eric Laurente0720872014-03-11 09:30:41 -07003904AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003905 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003906 // stream to strategy mapping
3907 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003908 case AUDIO_STREAM_VOICE_CALL:
3909 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003910 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003911 case AUDIO_STREAM_RING:
3912 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003913 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003914 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003915 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003916 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003917 return STRATEGY_DTMF;
3918 default:
3919 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003920 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003921 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3922 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003923 case AUDIO_STREAM_TTS:
3924 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003925 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003926 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003927 return STRATEGY_ENFORCED_AUDIBLE;
3928 }
3929}
3930
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003931uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3932 // flags to strategy mapping
3933 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3934 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3935 }
3936
3937 // usage to strategy mapping
3938 switch (attr->usage) {
3939 case AUDIO_USAGE_MEDIA:
3940 case AUDIO_USAGE_GAME:
3941 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3942 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3943 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3944 return (uint32_t) STRATEGY_MEDIA;
3945
3946 case AUDIO_USAGE_VOICE_COMMUNICATION:
3947 return (uint32_t) STRATEGY_PHONE;
3948
3949 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3950 return (uint32_t) STRATEGY_DTMF;
3951
3952 case AUDIO_USAGE_ALARM:
3953 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3954 return (uint32_t) STRATEGY_SONIFICATION;
3955
3956 case AUDIO_USAGE_NOTIFICATION:
3957 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3958 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3959 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3960 case AUDIO_USAGE_NOTIFICATION_EVENT:
3961 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3962
3963 case AUDIO_USAGE_UNKNOWN:
3964 default:
3965 return (uint32_t) STRATEGY_MEDIA;
3966 }
3967}
3968
Eric Laurente0720872014-03-11 09:30:41 -07003969void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003970 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003971 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003972 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3973 updateDevicesAndOutputs();
3974 break;
3975 default:
3976 break;
3977 }
3978}
3979
Eric Laurente0720872014-03-11 09:30:41 -07003980audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003981 bool fromCache)
3982{
3983 uint32_t device = AUDIO_DEVICE_NONE;
3984
3985 if (fromCache) {
3986 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3987 strategy, mDeviceForStrategy[strategy]);
3988 return mDeviceForStrategy[strategy];
3989 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003990 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003991 switch (strategy) {
3992
3993 case STRATEGY_SONIFICATION_RESPECTFUL:
3994 if (isInCall()) {
3995 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003996 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003997 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3998 // while media is playing on a remote device, use the the sonification behavior.
3999 // Note that we test this usecase before testing if media is playing because
4000 // the isStreamActive() method only informs about the activity of a stream, not
4001 // if it's for local playback. Note also that we use the same delay between both tests
4002 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004003 //user "safe" speaker if available instead of normal speaker to avoid triggering
4004 //other acoustic safety mechanisms for notification
4005 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4006 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004007 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004008 // while media is playing (or has recently played), use the same device
4009 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4010 } else {
4011 // when media is not playing anymore, fall back on the sonification behavior
4012 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004013 //user "safe" speaker if available instead of normal speaker to avoid triggering
4014 //other acoustic safety mechanisms for notification
4015 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4016 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004017 }
4018
4019 break;
4020
4021 case STRATEGY_DTMF:
4022 if (!isInCall()) {
4023 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4024 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4025 break;
4026 }
4027 // when in call, DTMF and PHONE strategies follow the same rules
4028 // FALL THROUGH
4029
4030 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004031 // Force use of only devices on primary output if:
4032 // - in call AND
4033 // - cannot route from voice call RX OR
4034 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4035 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4036 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4037 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4038 if (((mAvailableInputDevices.types() &
4039 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4040 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004041 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004042 AUDIO_DEVICE_API_VERSION_3_0))) {
4043 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4044 }
4045 }
Eric Laurente552edb2014-03-10 17:42:56 -07004046 // for phone strategy, we first consider the forced use and then the available devices by order
4047 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004048 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4049 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004050 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004051 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004052 if (device) break;
4053 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004054 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004055 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004056 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004057 if (device) break;
4058 // if SCO device is requested but no SCO device is available, fall back to default case
4059 // FALL THROUGH
4060
4061 default: // FORCE_NONE
4062 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004063 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004064 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004065 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004066 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004067 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004069 if (device) break;
4070 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004071 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004072 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004073 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004074 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004075 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4076 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004077 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004078 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004079 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004080 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004081 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004082 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004083 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004084 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004085 if (device) break;
4086 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004087 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004088 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004089 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004090 if (device == AUDIO_DEVICE_NONE) {
4091 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4092 }
4093 break;
4094
Eric Laurent3b73df72014-03-11 09:06:29 -07004095 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004096 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4097 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004098 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004099 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004100 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004101 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004102 if (device) break;
4103 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004104 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004105 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004106 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004107 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004108 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004109 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004110 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004111 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004112 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004113 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004114 if (device) break;
4115 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004116 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4117 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004118 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004119 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004120 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004121 if (device == AUDIO_DEVICE_NONE) {
4122 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4123 }
4124 break;
4125 }
4126 break;
4127
4128 case STRATEGY_SONIFICATION:
4129
4130 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4131 // handleIncallSonification().
4132 if (isInCall()) {
4133 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4134 break;
4135 }
4136 // FALL THROUGH
4137
4138 case STRATEGY_ENFORCED_AUDIBLE:
4139 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4140 // except:
4141 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4142 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4143
4144 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004145 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004146 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004147 if (device == AUDIO_DEVICE_NONE) {
4148 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4149 }
4150 }
4151 // The second device used for sonification is the same as the device used by media strategy
4152 // FALL THROUGH
4153
4154 case STRATEGY_MEDIA: {
4155 uint32_t device2 = AUDIO_DEVICE_NONE;
4156 if (strategy != STRATEGY_SONIFICATION) {
4157 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004158 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004159 }
4160 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004161 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004162 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004163 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004164 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004165 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004166 }
4167 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004168 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004169 }
4170 }
4171 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004172 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004173 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004174 if ((device2 == AUDIO_DEVICE_NONE)) {
4175 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4176 }
Eric Laurente552edb2014-03-10 17:42:56 -07004177 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004178 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004179 }
4180 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004181 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004182 }
4183 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004184 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004185 }
4186 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004187 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004188 }
4189 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4190 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004191 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004192 }
4193 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004194 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004195 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004196 }
4197 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004198 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004199 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004200 int device3 = AUDIO_DEVICE_NONE;
4201 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004202 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004203 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4204 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004205 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004206 }
Eric Laurente552edb2014-03-10 17:42:56 -07004207
Jungshik Jang839e4f32014-06-26 17:23:40 +09004208 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004209 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4210 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4211 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004212
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004213 // If hdmi system audio mode is on, remove speaker out of output list.
4214 if ((strategy == STRATEGY_MEDIA) &&
4215 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4216 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4217 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4218 }
4219
Eric Laurente552edb2014-03-10 17:42:56 -07004220 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004221 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004222 if (device == AUDIO_DEVICE_NONE) {
4223 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4224 }
4225 } break;
4226
4227 default:
4228 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4229 break;
4230 }
4231
4232 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4233 return device;
4234}
4235
Eric Laurente0720872014-03-11 09:30:41 -07004236void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004237{
4238 for (int i = 0; i < NUM_STRATEGIES; i++) {
4239 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4240 }
4241 mPreviousOutputs = mOutputs;
4242}
4243
Eric Laurent1f2f2232014-06-02 12:01:23 -07004244uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004245 audio_devices_t prevDevice,
4246 uint32_t delayMs)
4247{
4248 // mute/unmute strategies using an incompatible device combination
4249 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4250 // if unmuting, unmute only after the specified delay
4251 if (outputDesc->isDuplicated()) {
4252 return 0;
4253 }
4254
4255 uint32_t muteWaitMs = 0;
4256 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004257 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004258
4259 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4260 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4261 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4262 bool doMute = false;
4263
4264 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4265 doMute = true;
4266 outputDesc->mStrategyMutedByDevice[i] = true;
4267 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4268 doMute = true;
4269 outputDesc->mStrategyMutedByDevice[i] = false;
4270 }
Eric Laurent99401132014-05-07 19:48:15 -07004271 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004272 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004273 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004274 // skip output if it does not share any device with current output
4275 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4276 == AUDIO_DEVICE_NONE) {
4277 continue;
4278 }
4279 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4280 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4281 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4282 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4283 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004284 if (mute) {
4285 // FIXME: should not need to double latency if volume could be applied
4286 // immediately by the audioflinger mixer. We must account for the delay
4287 // between now and the next time the audioflinger thread for this output
4288 // will process a buffer (which corresponds to one buffer size,
4289 // usually 1/2 or 1/4 of the latency).
4290 if (muteWaitMs < desc->latency() * 2) {
4291 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004292 }
4293 }
4294 }
4295 }
4296 }
4297 }
4298
Eric Laurent99401132014-05-07 19:48:15 -07004299 // temporary mute output if device selection changes to avoid volume bursts due to
4300 // different per device volumes
4301 if (outputDesc->isActive() && (device != prevDevice)) {
4302 if (muteWaitMs < outputDesc->latency() * 2) {
4303 muteWaitMs = outputDesc->latency() * 2;
4304 }
4305 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4306 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004307 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004308 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004309 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004310 muteWaitMs *2, device);
4311 }
4312 }
4313 }
4314
Eric Laurente552edb2014-03-10 17:42:56 -07004315 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4316 if (muteWaitMs > delayMs) {
4317 muteWaitMs -= delayMs;
4318 usleep(muteWaitMs * 1000);
4319 return muteWaitMs;
4320 }
4321 return 0;
4322}
4323
Eric Laurente0720872014-03-11 09:30:41 -07004324uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004325 audio_devices_t device,
4326 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004327 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004328 audio_patch_handle_t *patchHandle,
4329 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004330{
4331 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004332 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004333 AudioParameter param;
4334 uint32_t muteWaitMs;
4335
4336 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004337 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4338 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004339 return muteWaitMs;
4340 }
4341 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4342 // output profile
4343 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004344 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004345 return 0;
4346 }
4347
4348 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004349 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004350
4351 audio_devices_t prevDevice = outputDesc->mDevice;
4352
4353 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4354
4355 if (device != AUDIO_DEVICE_NONE) {
4356 outputDesc->mDevice = device;
4357 }
4358 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4359
4360 // Do not change the routing if:
4361 // - the requested device is AUDIO_DEVICE_NONE
4362 // - the requested device is the same as current device and force is not specified.
4363 // Doing this check here allows the caller to call setOutputDevice() without conditions
4364 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4365 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4366 return muteWaitMs;
4367 }
4368
4369 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004370
Eric Laurente552edb2014-03-10 17:42:56 -07004371 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004372 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004373 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004374 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004375 DeviceVector deviceList = (address == NULL) ?
4376 mAvailableOutputDevices.getDevicesFromType(device)
4377 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004378 if (!deviceList.isEmpty()) {
4379 struct audio_patch patch;
4380 outputDesc->toAudioPortConfig(&patch.sources[0]);
4381 patch.num_sources = 1;
4382 patch.num_sinks = 0;
4383 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4384 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004385 patch.num_sinks++;
4386 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004387 ssize_t index;
4388 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4389 index = mAudioPatches.indexOfKey(*patchHandle);
4390 } else {
4391 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4392 }
4393 sp< AudioPatch> patchDesc;
4394 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4395 if (index >= 0) {
4396 patchDesc = mAudioPatches.valueAt(index);
4397 afPatchHandle = patchDesc->mAfPatchHandle;
4398 }
4399
Eric Laurent1c333e22014-05-20 10:48:17 -07004400 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004401 &afPatchHandle,
4402 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004403 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4404 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004405 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004406 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004407 if (index < 0) {
4408 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4409 &patch, mUidCached);
4410 addAudioPatch(patchDesc->mHandle, patchDesc);
4411 } else {
4412 patchDesc->mPatch = patch;
4413 }
4414 patchDesc->mAfPatchHandle = afPatchHandle;
4415 patchDesc->mUid = mUidCached;
4416 if (patchHandle) {
4417 *patchHandle = patchDesc->mHandle;
4418 }
4419 outputDesc->mPatchHandle = patchDesc->mHandle;
4420 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004421 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004422 }
4423 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004424
4425 // inform all input as well
4426 for (size_t i = 0; i < mInputs.size(); i++) {
4427 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4428 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4429 AudioParameter inputCmd = AudioParameter();
4430 ALOGV("%s: inform input %d of device:%d", __func__,
4431 inputDescriptor->mIoHandle, device);
4432 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4433 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4434 inputCmd.toString(),
4435 delayMs);
4436 }
4437 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004438 }
Eric Laurente552edb2014-03-10 17:42:56 -07004439
4440 // update stream volumes according to new device
4441 applyStreamVolumes(output, device, delayMs);
4442
4443 return muteWaitMs;
4444}
4445
Eric Laurent1c333e22014-05-20 10:48:17 -07004446status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004447 int delayMs,
4448 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004449{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004450 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004451 ssize_t index;
4452 if (patchHandle) {
4453 index = mAudioPatches.indexOfKey(*patchHandle);
4454 } else {
4455 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4456 }
4457 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004458 return INVALID_OPERATION;
4459 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004460 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4461 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004462 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4463 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004464 removeAudioPatch(patchDesc->mHandle);
4465 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004466 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004467 return status;
4468}
4469
4470status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4471 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004472 bool force,
4473 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004474{
4475 status_t status = NO_ERROR;
4476
Eric Laurent1f2f2232014-06-02 12:01:23 -07004477 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004478 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4479 inputDesc->mDevice = device;
4480
4481 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4482 if (!deviceList.isEmpty()) {
4483 struct audio_patch patch;
4484 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004485 // AUDIO_SOURCE_HOTWORD is for internal use only:
4486 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004487 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4488 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004489 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4490 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004491 patch.num_sinks = 1;
4492 //only one input device for now
4493 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004494 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004495 ssize_t index;
4496 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4497 index = mAudioPatches.indexOfKey(*patchHandle);
4498 } else {
4499 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4500 }
4501 sp< AudioPatch> patchDesc;
4502 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4503 if (index >= 0) {
4504 patchDesc = mAudioPatches.valueAt(index);
4505 afPatchHandle = patchDesc->mAfPatchHandle;
4506 }
4507
Eric Laurent1c333e22014-05-20 10:48:17 -07004508 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004509 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004510 0);
4511 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004512 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004513 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004514 if (index < 0) {
4515 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4516 &patch, mUidCached);
4517 addAudioPatch(patchDesc->mHandle, patchDesc);
4518 } else {
4519 patchDesc->mPatch = patch;
4520 }
4521 patchDesc->mAfPatchHandle = afPatchHandle;
4522 patchDesc->mUid = mUidCached;
4523 if (patchHandle) {
4524 *patchHandle = patchDesc->mHandle;
4525 }
4526 inputDesc->mPatchHandle = patchDesc->mHandle;
4527 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004528 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004529 }
4530 }
4531 }
4532 return status;
4533}
4534
Eric Laurent6a94d692014-05-20 11:18:06 -07004535status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4536 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004537{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004538 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004539 ssize_t index;
4540 if (patchHandle) {
4541 index = mAudioPatches.indexOfKey(*patchHandle);
4542 } else {
4543 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4544 }
4545 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004546 return INVALID_OPERATION;
4547 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004548 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4549 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004550 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4551 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004552 removeAudioPatch(patchDesc->mHandle);
4553 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004554 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004555 return status;
4556}
4557
4558sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004559 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004560 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004561 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004562 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004563{
4564 // Choose an input profile based on the requested capture parameters: select the first available
4565 // profile supporting all requested parameters.
4566
4567 for (size_t i = 0; i < mHwModules.size(); i++)
4568 {
4569 if (mHwModules[i]->mHandle == 0) {
4570 continue;
4571 }
4572 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4573 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004574 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004575 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004576 if (profile->isCompatibleProfile(device, samplingRate,
4577 &samplingRate /*updatedSamplingRate*/,
4578 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004579 return profile;
4580 }
4581 }
4582 }
4583 return NULL;
4584}
4585
Eric Laurente0720872014-03-11 09:30:41 -07004586audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004587{
4588 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004589 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4590 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004591 switch (inputSource) {
4592 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004593 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004594 device = AUDIO_DEVICE_IN_VOICE_CALL;
4595 break;
4596 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004597 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004598
4599 case AUDIO_SOURCE_DEFAULT:
4600 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004601 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4602 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004603 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4604 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4605 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4606 device = AUDIO_DEVICE_IN_USB_DEVICE;
4607 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4608 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004609 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004610 break;
4611
4612 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4613 // Allow only use of devices on primary input if in call and HAL does not support routing
4614 // to voice call path.
4615 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4616 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4617 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4618 }
4619
4620 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4621 case AUDIO_POLICY_FORCE_BT_SCO:
4622 // if SCO device is requested but no SCO device is available, fall back to default case
4623 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4624 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4625 break;
4626 }
4627 // FALL THROUGH
4628
4629 default: // FORCE_NONE
4630 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4631 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4632 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4633 device = AUDIO_DEVICE_IN_USB_DEVICE;
4634 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4635 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4636 }
4637 break;
4638
4639 case AUDIO_POLICY_FORCE_SPEAKER:
4640 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4641 device = AUDIO_DEVICE_IN_BACK_MIC;
4642 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4643 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4644 }
4645 break;
4646 }
4647 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004648
Eric Laurente552edb2014-03-10 17:42:56 -07004649 case AUDIO_SOURCE_VOICE_RECOGNITION:
4650 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004651 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004652 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004653 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004654 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004655 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004656 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4657 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004658 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004659 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4660 }
4661 break;
4662 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004663 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004664 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004665 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004666 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4667 }
4668 break;
4669 case AUDIO_SOURCE_VOICE_DOWNLINK:
4670 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004671 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004672 device = AUDIO_DEVICE_IN_VOICE_CALL;
4673 }
4674 break;
4675 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004676 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004677 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4678 }
4679 break;
4680 default:
4681 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4682 break;
4683 }
4684 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4685 return device;
4686}
4687
Eric Laurente0720872014-03-11 09:30:41 -07004688bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004689{
4690 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4691 device &= ~AUDIO_DEVICE_BIT_IN;
4692 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4693 return true;
4694 }
4695 return false;
4696}
4697
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004698bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4699 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4700}
4701
Eric Laurente0720872014-03-11 09:30:41 -07004702audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004703{
4704 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004705 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004706 if ((input_descriptor->mRefCount > 0)
4707 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4708 return mInputs.keyAt(i);
4709 }
4710 }
4711 return 0;
4712}
4713
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004714uint32_t AudioPolicyManager::activeInputsCount() const
4715{
4716 uint32_t count = 0;
4717 for (size_t i = 0; i < mInputs.size(); i++) {
4718 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4719 if (desc->mRefCount > 0) {
4720 return count++;
4721 }
4722 }
4723 return count;
4724}
4725
Eric Laurente552edb2014-03-10 17:42:56 -07004726
Eric Laurente0720872014-03-11 09:30:41 -07004727audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004728{
4729 if (device == AUDIO_DEVICE_NONE) {
4730 // this happens when forcing a route update and no track is active on an output.
4731 // In this case the returned category is not important.
4732 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004733 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004734 // Multiple device selection is either:
4735 // - speaker + one other device: give priority to speaker in this case.
4736 // - one A2DP device + another device: happens with duplicated output. In this case
4737 // retain the device on the A2DP output as the other must not correspond to an active
4738 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004739 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004740 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4741 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004742 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4743 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4744 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4745 device = AUDIO_DEVICE_OUT_AUX_LINE;
4746 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4747 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004748 } else {
4749 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4750 }
4751 }
4752
Jon Eklund11c9fb12014-06-23 14:47:03 -05004753 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4754 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4755 device = AUDIO_DEVICE_OUT_SPEAKER;
4756
Eric Laurent3b73df72014-03-11 09:06:29 -07004757 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004758 "getDeviceForVolume() invalid device combination: %08x",
4759 device);
4760
4761 return device;
4762}
4763
Eric Laurente0720872014-03-11 09:30:41 -07004764AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004765{
4766 switch(getDeviceForVolume(device)) {
4767 case AUDIO_DEVICE_OUT_EARPIECE:
4768 return DEVICE_CATEGORY_EARPIECE;
4769 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4770 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4771 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4772 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4773 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4774 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4775 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004776 case AUDIO_DEVICE_OUT_LINE:
4777 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4778 /*USB? Remote submix?*/
4779 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004780 case AUDIO_DEVICE_OUT_SPEAKER:
4781 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4782 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004783 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4784 case AUDIO_DEVICE_OUT_USB_DEVICE:
4785 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4786 default:
4787 return DEVICE_CATEGORY_SPEAKER;
4788 }
4789}
4790
Eric Laurente0720872014-03-11 09:30:41 -07004791float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004792 int indexInUi)
4793{
4794 device_category deviceCategory = getDeviceCategory(device);
4795 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4796
4797 // the volume index in the UI is relative to the min and max volume indices for this stream type
4798 int nbSteps = 1 + curve[VOLMAX].mIndex -
4799 curve[VOLMIN].mIndex;
4800 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4801 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4802
4803 // find what part of the curve this index volume belongs to, or if it's out of bounds
4804 int segment = 0;
4805 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4806 return 0.0f;
4807 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4808 segment = 0;
4809 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4810 segment = 1;
4811 } else if (volIdx <= curve[VOLMAX].mIndex) {
4812 segment = 2;
4813 } else { // out of bounds
4814 return 1.0f;
4815 }
4816
4817 // linear interpolation in the attenuation table in dB
4818 float decibels = curve[segment].mDBAttenuation +
4819 ((float)(volIdx - curve[segment].mIndex)) *
4820 ( (curve[segment+1].mDBAttenuation -
4821 curve[segment].mDBAttenuation) /
4822 ((float)(curve[segment+1].mIndex -
4823 curve[segment].mIndex)) );
4824
4825 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4826
4827 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4828 curve[segment].mIndex, volIdx,
4829 curve[segment+1].mIndex,
4830 curve[segment].mDBAttenuation,
4831 decibels,
4832 curve[segment+1].mDBAttenuation,
4833 amplification);
4834
4835 return amplification;
4836}
4837
Eric Laurente0720872014-03-11 09:30:41 -07004838const AudioPolicyManager::VolumeCurvePoint
4839 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004840 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4841};
4842
Eric Laurente0720872014-03-11 09:30:41 -07004843const AudioPolicyManager::VolumeCurvePoint
4844 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004845 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4846};
4847
Eric Laurente0720872014-03-11 09:30:41 -07004848const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004849 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4850 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4851};
4852
4853const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004854 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004855 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4856};
4857
Eric Laurente0720872014-03-11 09:30:41 -07004858const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004859 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004860 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004861};
4862
4863const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004864 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004865 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4866};
4867
Eric Laurente0720872014-03-11 09:30:41 -07004868const AudioPolicyManager::VolumeCurvePoint
4869 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004870 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4871};
4872
4873// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4874// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4875// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4876// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4877
Eric Laurente0720872014-03-11 09:30:41 -07004878const AudioPolicyManager::VolumeCurvePoint
4879 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004880 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4881};
4882
Eric Laurente0720872014-03-11 09:30:41 -07004883const AudioPolicyManager::VolumeCurvePoint
4884 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004885 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4886};
4887
Eric Laurente0720872014-03-11 09:30:41 -07004888const AudioPolicyManager::VolumeCurvePoint
4889 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004890 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4891};
4892
Eric Laurente0720872014-03-11 09:30:41 -07004893const AudioPolicyManager::VolumeCurvePoint
4894 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004895 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4896};
4897
Eric Laurente0720872014-03-11 09:30:41 -07004898const AudioPolicyManager::VolumeCurvePoint
4899 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004900 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4901};
4902
Eric Laurente0720872014-03-11 09:30:41 -07004903const AudioPolicyManager::VolumeCurvePoint
4904 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4905 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004906 { // AUDIO_STREAM_VOICE_CALL
4907 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4908 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004909 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4910 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004911 },
4912 { // AUDIO_STREAM_SYSTEM
4913 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4914 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004915 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4916 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004917 },
4918 { // AUDIO_STREAM_RING
4919 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4920 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004921 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4922 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004923 },
4924 { // AUDIO_STREAM_MUSIC
4925 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4926 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004927 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4928 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004929 },
4930 { // AUDIO_STREAM_ALARM
4931 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4932 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004933 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4934 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004935 },
4936 { // AUDIO_STREAM_NOTIFICATION
4937 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4938 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004939 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4940 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004941 },
4942 { // AUDIO_STREAM_BLUETOOTH_SCO
4943 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4944 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004945 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4946 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004947 },
4948 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4949 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4950 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004951 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4952 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004953 },
4954 { // AUDIO_STREAM_DTMF
4955 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4956 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004957 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4958 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004959 },
4960 { // AUDIO_STREAM_TTS
4961 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4962 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004963 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4964 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004965 },
4966};
4967
Eric Laurente0720872014-03-11 09:30:41 -07004968void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004969{
4970 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4971 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4972 mStreams[i].mVolumeCurve[j] =
4973 sVolumeProfiles[i][j];
4974 }
4975 }
4976
4977 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4978 if (mSpeakerDrcEnabled) {
4979 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4980 sDefaultSystemVolumeCurveDrc;
4981 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4982 sSpeakerSonificationVolumeCurveDrc;
4983 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4984 sSpeakerSonificationVolumeCurveDrc;
4985 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4986 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004987 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4988 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004989 }
4990}
4991
Eric Laurente0720872014-03-11 09:30:41 -07004992float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004993 int index,
4994 audio_io_handle_t output,
4995 audio_devices_t device)
4996{
4997 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004998 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004999 StreamDescriptor &streamDesc = mStreams[stream];
5000
5001 if (device == AUDIO_DEVICE_NONE) {
5002 device = outputDesc->device();
5003 }
5004
Eric Laurente552edb2014-03-10 17:42:56 -07005005 volume = volIndexToAmpl(device, streamDesc, index);
5006
5007 // if a headset is connected, apply the following rules to ring tones and notifications
5008 // to avoid sound level bursts in user's ears:
5009 // - always attenuate ring tones and notifications volume by 6dB
5010 // - if music is playing, always limit the volume to current music volume,
5011 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005012 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005013 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5014 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5015 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5016 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5017 ((stream_strategy == STRATEGY_SONIFICATION)
5018 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005019 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005020 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005021 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005022 streamDesc.mCanBeMuted) {
5023 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5024 // when the phone is ringing we must consider that music could have been paused just before
5025 // by the music application and behave as if music was active if the last music track was
5026 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005027 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005028 mLimitRingtoneVolume) {
5029 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005030 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5031 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005032 output,
5033 musicDevice);
5034 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5035 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5036 if (volume > minVol) {
5037 volume = minVol;
5038 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5039 }
5040 }
5041 }
5042
5043 return volume;
5044}
5045
Eric Laurente0720872014-03-11 09:30:41 -07005046status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005047 int index,
5048 audio_io_handle_t output,
5049 audio_devices_t device,
5050 int delayMs,
5051 bool force)
5052{
5053
5054 // do not change actual stream volume if the stream is muted
5055 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5056 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5057 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5058 return NO_ERROR;
5059 }
5060
5061 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005062 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5063 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5064 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5065 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005066 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005067 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005068 return INVALID_OPERATION;
5069 }
5070
5071 float volume = computeVolume(stream, index, output, device);
5072 // We actually change the volume if:
5073 // - the float value returned by computeVolume() changed
5074 // - the force flag is set
5075 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5076 force) {
5077 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5078 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5079 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5080 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005081 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5082 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005083 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005084 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005085 }
5086
Eric Laurent3b73df72014-03-11 09:06:29 -07005087 if (stream == AUDIO_STREAM_VOICE_CALL ||
5088 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005089 float voiceVolume;
5090 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005091 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005092 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5093 } else {
5094 voiceVolume = 1.0;
5095 }
5096
5097 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5098 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5099 mLastVoiceVolume = voiceVolume;
5100 }
5101 }
5102
5103 return NO_ERROR;
5104}
5105
Eric Laurente0720872014-03-11 09:30:41 -07005106void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005107 audio_devices_t device,
5108 int delayMs,
5109 bool force)
5110{
5111 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5112
Eric Laurent3b73df72014-03-11 09:06:29 -07005113 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5114 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005115 mStreams[stream].getVolumeIndex(device),
5116 output,
5117 device,
5118 delayMs,
5119 force);
5120 }
5121}
5122
Eric Laurente0720872014-03-11 09:30:41 -07005123void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005124 bool on,
5125 audio_io_handle_t output,
5126 int delayMs,
5127 audio_devices_t device)
5128{
5129 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005130 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5131 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5132 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005133 }
5134 }
5135}
5136
Eric Laurente0720872014-03-11 09:30:41 -07005137void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005138 bool on,
5139 audio_io_handle_t output,
5140 int delayMs,
5141 audio_devices_t device)
5142{
5143 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005144 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005145 if (device == AUDIO_DEVICE_NONE) {
5146 device = outputDesc->device();
5147 }
5148
5149 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5150 stream, on, output, outputDesc->mMuteCount[stream], device);
5151
5152 if (on) {
5153 if (outputDesc->mMuteCount[stream] == 0) {
5154 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005155 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5156 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005157 checkAndSetVolume(stream, 0, output, device, delayMs);
5158 }
5159 }
5160 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5161 outputDesc->mMuteCount[stream]++;
5162 } else {
5163 if (outputDesc->mMuteCount[stream] == 0) {
5164 ALOGV("setStreamMute() unmuting non muted stream!");
5165 return;
5166 }
5167 if (--outputDesc->mMuteCount[stream] == 0) {
5168 checkAndSetVolume(stream,
5169 streamDesc.getVolumeIndex(device),
5170 output,
5171 device,
5172 delayMs);
5173 }
5174 }
5175}
5176
Eric Laurente0720872014-03-11 09:30:41 -07005177void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005178 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005179{
5180 // if the stream pertains to sonification strategy and we are in call we must
5181 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5182 // in the device used for phone strategy and play the tone if the selected device does not
5183 // interfere with the device used for phone strategy
5184 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5185 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005186 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005187 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5188 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005189 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005190 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5191 stream, starting, outputDesc->mDevice, stateChange);
5192 if (outputDesc->mRefCount[stream]) {
5193 int muteCount = 1;
5194 if (stateChange) {
5195 muteCount = outputDesc->mRefCount[stream];
5196 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005197 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005198 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5199 for (int i = 0; i < muteCount; i++) {
5200 setStreamMute(stream, starting, mPrimaryOutput);
5201 }
5202 } else {
5203 ALOGV("handleIncallSonification() high visibility");
5204 if (outputDesc->device() &
5205 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5206 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5207 for (int i = 0; i < muteCount; i++) {
5208 setStreamMute(stream, starting, mPrimaryOutput);
5209 }
5210 }
5211 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005212 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5213 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005214 } else {
5215 mpClientInterface->stopTone();
5216 }
5217 }
5218 }
5219 }
5220}
5221
Eric Laurente0720872014-03-11 09:30:41 -07005222bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005223{
5224 return isStateInCall(mPhoneState);
5225}
5226
Eric Laurente0720872014-03-11 09:30:41 -07005227bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005228 return ((state == AUDIO_MODE_IN_CALL) ||
5229 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005230}
5231
Eric Laurente0720872014-03-11 09:30:41 -07005232uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005233{
5234 return MAX_EFFECTS_CPU_LOAD;
5235}
5236
Eric Laurente0720872014-03-11 09:30:41 -07005237uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005238{
5239 return MAX_EFFECTS_MEMORY;
5240}
5241
Eric Laurent6a94d692014-05-20 11:18:06 -07005242
Eric Laurente552edb2014-03-10 17:42:56 -07005243// --- AudioOutputDescriptor class implementation
5244
Eric Laurente0720872014-03-11 09:30:41 -07005245AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005246 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005247 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005248 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005249 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5250{
5251 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005252 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005253 mRefCount[i] = 0;
5254 mCurVolume[i] = -1.0;
5255 mMuteCount[i] = 0;
5256 mStopTime[i] = 0;
5257 }
5258 for (int i = 0; i < NUM_STRATEGIES; i++) {
5259 mStrategyMutedByDevice[i] = false;
5260 }
5261 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005262 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005263 mSamplingRate = profile->pickSamplingRate();
5264 mFormat = profile->pickFormat();
5265 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005266 if (profile->mGains.size() > 0) {
5267 profile->mGains[0]->getDefaultConfig(&mGain);
5268 }
Eric Laurente552edb2014-03-10 17:42:56 -07005269 }
5270}
5271
Eric Laurente0720872014-03-11 09:30:41 -07005272audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005273{
5274 if (isDuplicated()) {
5275 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5276 } else {
5277 return mDevice;
5278 }
5279}
5280
Eric Laurente0720872014-03-11 09:30:41 -07005281uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005282{
5283 if (isDuplicated()) {
5284 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5285 } else {
5286 return mLatency;
5287 }
5288}
5289
Eric Laurente0720872014-03-11 09:30:41 -07005290bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005291 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005292{
5293 if (isDuplicated()) {
5294 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5295 } else if (outputDesc->isDuplicated()){
5296 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5297 } else {
5298 return (mProfile->mModule == outputDesc->mProfile->mModule);
5299 }
5300}
5301
Eric Laurente0720872014-03-11 09:30:41 -07005302void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005303 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005304{
5305 // forward usage count change to attached outputs
5306 if (isDuplicated()) {
5307 mOutput1->changeRefCount(stream, delta);
5308 mOutput2->changeRefCount(stream, delta);
5309 }
5310 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005311 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5312 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005313 mRefCount[stream] = 0;
5314 return;
5315 }
5316 mRefCount[stream] += delta;
5317 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5318}
5319
Eric Laurente0720872014-03-11 09:30:41 -07005320audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005321{
5322 if (isDuplicated()) {
5323 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5324 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005325 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005326 }
5327}
5328
Eric Laurente0720872014-03-11 09:30:41 -07005329bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005330{
5331 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5332}
5333
Eric Laurente0720872014-03-11 09:30:41 -07005334bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005335 uint32_t inPastMs,
5336 nsecs_t sysTime) const
5337{
5338 if ((sysTime == 0) && (inPastMs != 0)) {
5339 sysTime = systemTime();
5340 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005341 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5342 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005343 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005344 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005345 return true;
5346 }
5347 }
5348 return false;
5349}
5350
Eric Laurente0720872014-03-11 09:30:41 -07005351bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005352 uint32_t inPastMs,
5353 nsecs_t sysTime) const
5354{
5355 if (mRefCount[stream] != 0) {
5356 return true;
5357 }
5358 if (inPastMs == 0) {
5359 return false;
5360 }
5361 if (sysTime == 0) {
5362 sysTime = systemTime();
5363 }
5364 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5365 return true;
5366 }
5367 return false;
5368}
5369
Eric Laurent1c333e22014-05-20 10:48:17 -07005370void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005371 struct audio_port_config *dstConfig,
5372 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005373{
Eric Laurent84c70242014-06-23 08:46:27 -07005374 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5375
Eric Laurent1f2f2232014-06-02 12:01:23 -07005376 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5377 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5378 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005379 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005380 }
5381 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5382
Eric Laurent6a94d692014-05-20 11:18:06 -07005383 dstConfig->id = mId;
5384 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5385 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005386 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5387 dstConfig->ext.mix.handle = mIoHandle;
5388 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005389}
5390
5391void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5392 struct audio_port *port) const
5393{
Eric Laurent84c70242014-06-23 08:46:27 -07005394 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005395 mProfile->toAudioPort(port);
5396 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005397 toAudioPortConfig(&port->active_config);
5398 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005399 port->ext.mix.handle = mIoHandle;
5400 port->ext.mix.latency_class =
5401 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5402}
Eric Laurente552edb2014-03-10 17:42:56 -07005403
Eric Laurente0720872014-03-11 09:30:41 -07005404status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005405{
5406 const size_t SIZE = 256;
5407 char buffer[SIZE];
5408 String8 result;
5409
Eric Laurent4d416952014-08-10 14:07:09 -07005410 snprintf(buffer, SIZE, " ID: %d\n", mId);
5411 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005412 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5413 result.append(buffer);
5414 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5415 result.append(buffer);
5416 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5417 result.append(buffer);
5418 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5419 result.append(buffer);
5420 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5421 result.append(buffer);
5422 snprintf(buffer, SIZE, " Devices %08x\n", device());
5423 result.append(buffer);
5424 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5425 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005426 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5427 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5428 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005429 result.append(buffer);
5430 }
5431 write(fd, result.string(), result.size());
5432
5433 return NO_ERROR;
5434}
5435
5436// --- AudioInputDescriptor class implementation
5437
Eric Laurent1c333e22014-05-20 10:48:17 -07005438AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005439 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005440 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005441 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005442{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005443 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005444 mSamplingRate = profile->pickSamplingRate();
5445 mFormat = profile->pickFormat();
5446 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005447 if (profile->mGains.size() > 0) {
5448 profile->mGains[0]->getDefaultConfig(&mGain);
5449 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005450 }
Eric Laurente552edb2014-03-10 17:42:56 -07005451}
5452
Eric Laurent1c333e22014-05-20 10:48:17 -07005453void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005454 struct audio_port_config *dstConfig,
5455 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005456{
Eric Laurent84c70242014-06-23 08:46:27 -07005457 ALOG_ASSERT(mProfile != 0,
5458 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005459 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5460 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5461 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005462 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005463 }
5464
5465 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5466
Eric Laurent6a94d692014-05-20 11:18:06 -07005467 dstConfig->id = mId;
5468 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5469 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005470 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5471 dstConfig->ext.mix.handle = mIoHandle;
5472 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005473}
5474
5475void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5476 struct audio_port *port) const
5477{
Eric Laurent84c70242014-06-23 08:46:27 -07005478 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5479
Eric Laurent1c333e22014-05-20 10:48:17 -07005480 mProfile->toAudioPort(port);
5481 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005482 toAudioPortConfig(&port->active_config);
5483 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005484 port->ext.mix.handle = mIoHandle;
5485 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5486}
5487
Eric Laurente0720872014-03-11 09:30:41 -07005488status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005489{
5490 const size_t SIZE = 256;
5491 char buffer[SIZE];
5492 String8 result;
5493
Eric Laurent4d416952014-08-10 14:07:09 -07005494 snprintf(buffer, SIZE, " ID: %d\n", mId);
5495 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005496 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5497 result.append(buffer);
5498 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5499 result.append(buffer);
5500 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5501 result.append(buffer);
5502 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5503 result.append(buffer);
5504 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5505 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005506 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5507 result.append(buffer);
5508
Eric Laurente552edb2014-03-10 17:42:56 -07005509 write(fd, result.string(), result.size());
5510
5511 return NO_ERROR;
5512}
5513
5514// --- StreamDescriptor class implementation
5515
Eric Laurente0720872014-03-11 09:30:41 -07005516AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005517 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5518{
5519 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5520}
5521
Eric Laurente0720872014-03-11 09:30:41 -07005522int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005523{
Eric Laurente0720872014-03-11 09:30:41 -07005524 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005525 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5526 if (mIndexCur.indexOfKey(device) < 0) {
5527 device = AUDIO_DEVICE_OUT_DEFAULT;
5528 }
5529 return mIndexCur.valueFor(device);
5530}
5531
Eric Laurente0720872014-03-11 09:30:41 -07005532void AudioPolicyManager::StreamDescriptor::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, "%s %02d %02d ",
5539 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5540 result.append(buffer);
5541 for (size_t i = 0; i < mIndexCur.size(); i++) {
5542 snprintf(buffer, SIZE, "%04x : %02d, ",
5543 mIndexCur.keyAt(i),
5544 mIndexCur.valueAt(i));
5545 result.append(buffer);
5546 }
5547 result.append("\n");
5548
5549 write(fd, result.string(), result.size());
5550}
5551
5552// --- EffectDescriptor class implementation
5553
Eric Laurente0720872014-03-11 09:30:41 -07005554status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005555{
5556 const size_t SIZE = 256;
5557 char buffer[SIZE];
5558 String8 result;
5559
5560 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5561 result.append(buffer);
5562 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5563 result.append(buffer);
5564 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5565 result.append(buffer);
5566 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5567 result.append(buffer);
5568 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5569 result.append(buffer);
5570 write(fd, result.string(), result.size());
5571
5572 return NO_ERROR;
5573}
5574
Eric Laurent1c333e22014-05-20 10:48:17 -07005575// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005576
Eric Laurente0720872014-03-11 09:30:41 -07005577AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005578 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5579 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005580{
5581}
5582
Eric Laurente0720872014-03-11 09:30:41 -07005583AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005584{
5585 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005586 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005587 }
5588 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005589 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005590 }
5591 free((void *)mName);
5592}
5593
Eric Laurent1afeecb2014-05-14 08:52:28 -07005594status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5595{
5596 cnode *node = root->first_child;
5597
5598 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5599
5600 while (node) {
5601 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5602 profile->loadSamplingRates((char *)node->value);
5603 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5604 profile->loadFormats((char *)node->value);
5605 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5606 profile->loadInChannels((char *)node->value);
5607 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5608 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5609 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005610 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5611 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005612 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5613 profile->loadGains(node);
5614 }
5615 node = node->next;
5616 }
5617 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5618 "loadInput() invalid supported devices");
5619 ALOGW_IF(profile->mChannelMasks.size() == 0,
5620 "loadInput() invalid supported channel masks");
5621 ALOGW_IF(profile->mSamplingRates.size() == 0,
5622 "loadInput() invalid supported sampling rates");
5623 ALOGW_IF(profile->mFormats.size() == 0,
5624 "loadInput() invalid supported formats");
5625 if (!profile->mSupportedDevices.isEmpty() &&
5626 (profile->mChannelMasks.size() != 0) &&
5627 (profile->mSamplingRates.size() != 0) &&
5628 (profile->mFormats.size() != 0)) {
5629
5630 ALOGV("loadInput() adding input Supported Devices %04x",
5631 profile->mSupportedDevices.types());
5632
5633 mInputProfiles.add(profile);
5634 return NO_ERROR;
5635 } else {
5636 return BAD_VALUE;
5637 }
5638}
5639
5640status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5641{
5642 cnode *node = root->first_child;
5643
5644 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5645
5646 while (node) {
5647 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5648 profile->loadSamplingRates((char *)node->value);
5649 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5650 profile->loadFormats((char *)node->value);
5651 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5652 profile->loadOutChannels((char *)node->value);
5653 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5654 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5655 mDeclaredDevices);
5656 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005657 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005658 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5659 profile->loadGains(node);
5660 }
5661 node = node->next;
5662 }
5663 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5664 "loadOutput() invalid supported devices");
5665 ALOGW_IF(profile->mChannelMasks.size() == 0,
5666 "loadOutput() invalid supported channel masks");
5667 ALOGW_IF(profile->mSamplingRates.size() == 0,
5668 "loadOutput() invalid supported sampling rates");
5669 ALOGW_IF(profile->mFormats.size() == 0,
5670 "loadOutput() invalid supported formats");
5671 if (!profile->mSupportedDevices.isEmpty() &&
5672 (profile->mChannelMasks.size() != 0) &&
5673 (profile->mSamplingRates.size() != 0) &&
5674 (profile->mFormats.size() != 0)) {
5675
5676 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5677 profile->mSupportedDevices.types(), profile->mFlags);
5678
5679 mOutputProfiles.add(profile);
5680 return NO_ERROR;
5681 } else {
5682 return BAD_VALUE;
5683 }
5684}
5685
5686status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5687{
5688 cnode *node = root->first_child;
5689
5690 audio_devices_t type = AUDIO_DEVICE_NONE;
5691 while (node) {
5692 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5693 type = parseDeviceNames((char *)node->value);
5694 break;
5695 }
5696 node = node->next;
5697 }
5698 if (type == AUDIO_DEVICE_NONE ||
5699 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5700 ALOGW("loadDevice() bad type %08x", type);
5701 return BAD_VALUE;
5702 }
5703 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5704 deviceDesc->mModule = this;
5705
5706 node = root->first_child;
5707 while (node) {
5708 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5709 deviceDesc->mAddress = String8((char *)node->value);
5710 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5711 if (audio_is_input_device(type)) {
5712 deviceDesc->loadInChannels((char *)node->value);
5713 } else {
5714 deviceDesc->loadOutChannels((char *)node->value);
5715 }
5716 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5717 deviceDesc->loadGains(node);
5718 }
5719 node = node->next;
5720 }
5721
5722 ALOGV("loadDevice() adding device name %s type %08x address %s",
5723 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5724
5725 mDeclaredDevices.add(deviceDesc);
5726
5727 return NO_ERROR;
5728}
5729
Eric Laurente0720872014-03-11 09:30:41 -07005730void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005731{
5732 const size_t SIZE = 256;
5733 char buffer[SIZE];
5734 String8 result;
5735
5736 snprintf(buffer, SIZE, " - name: %s\n", mName);
5737 result.append(buffer);
5738 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5739 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005740 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5741 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005742 write(fd, result.string(), result.size());
5743 if (mOutputProfiles.size()) {
5744 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5745 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005746 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005747 write(fd, buffer, strlen(buffer));
5748 mOutputProfiles[i]->dump(fd);
5749 }
5750 }
5751 if (mInputProfiles.size()) {
5752 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5753 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005754 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005755 write(fd, buffer, strlen(buffer));
5756 mInputProfiles[i]->dump(fd);
5757 }
5758 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005759 if (mDeclaredDevices.size()) {
5760 write(fd, " - devices:\n", strlen(" - devices:\n"));
5761 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5762 mDeclaredDevices[i]->dump(fd, 4, i);
5763 }
5764 }
Eric Laurente552edb2014-03-10 17:42:56 -07005765}
5766
Eric Laurent1c333e22014-05-20 10:48:17 -07005767// --- AudioPort class implementation
5768
Eric Laurenta121f902014-06-03 13:32:54 -07005769
5770AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5771 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07005772 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07005773{
5774 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5775 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5776}
5777
Eric Laurent1c333e22014-05-20 10:48:17 -07005778void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5779{
5780 port->role = mRole;
5781 port->type = mType;
5782 unsigned int i;
5783 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005784 if (mSamplingRates[i] != 0) {
5785 port->sample_rates[i] = mSamplingRates[i];
5786 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005787 }
5788 port->num_sample_rates = i;
5789 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005790 if (mChannelMasks[i] != 0) {
5791 port->channel_masks[i] = mChannelMasks[i];
5792 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005793 }
5794 port->num_channel_masks = i;
5795 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005796 if (mFormats[i] != 0) {
5797 port->formats[i] = mFormats[i];
5798 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005799 }
5800 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005801
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005802 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005803
5804 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5805 port->gains[i] = mGains[i]->mGain;
5806 }
5807 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005808}
5809
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005810void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5811 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5812 const uint32_t rate = port->mSamplingRates.itemAt(k);
5813 if (rate != 0) { // skip "dynamic" rates
5814 bool hasRate = false;
5815 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5816 if (rate == mSamplingRates.itemAt(l)) {
5817 hasRate = true;
5818 break;
5819 }
5820 }
5821 if (!hasRate) { // never import a sampling rate twice
5822 mSamplingRates.add(rate);
5823 }
5824 }
5825 }
5826 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5827 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5828 if (mask != 0) { // skip "dynamic" masks
5829 bool hasMask = false;
5830 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5831 if (mask == mChannelMasks.itemAt(l)) {
5832 hasMask = true;
5833 break;
5834 }
5835 }
5836 if (!hasMask) { // never import a channel mask twice
5837 mChannelMasks.add(mask);
5838 }
5839 }
5840 }
5841 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5842 const audio_format_t format = port->mFormats.itemAt(k);
5843 if (format != 0) { // skip "dynamic" formats
5844 bool hasFormat = false;
5845 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5846 if (format == mFormats.itemAt(l)) {
5847 hasFormat = true;
5848 break;
5849 }
5850 }
5851 if (!hasFormat) { // never import a channel mask twice
5852 mFormats.add(format);
5853 }
5854 }
5855 }
5856}
5857
5858void AudioPolicyManager::AudioPort::clearCapabilities() {
5859 mChannelMasks.clear();
5860 mFormats.clear();
5861 mSamplingRates.clear();
5862}
Eric Laurent1c333e22014-05-20 10:48:17 -07005863
5864void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5865{
5866 char *str = strtok(name, "|");
5867
5868 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5869 // rates should be read from the output stream after it is opened for the first time
5870 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5871 mSamplingRates.add(0);
5872 return;
5873 }
5874
5875 while (str != NULL) {
5876 uint32_t rate = atoi(str);
5877 if (rate != 0) {
5878 ALOGV("loadSamplingRates() adding rate %d", rate);
5879 mSamplingRates.add(rate);
5880 }
5881 str = strtok(NULL, "|");
5882 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005883}
5884
5885void AudioPolicyManager::AudioPort::loadFormats(char *name)
5886{
5887 char *str = strtok(name, "|");
5888
5889 // by convention, "0' in the first entry in mFormats indicates the supported formats
5890 // should be read from the output stream after it is opened for the first time
5891 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5892 mFormats.add(AUDIO_FORMAT_DEFAULT);
5893 return;
5894 }
5895
5896 while (str != NULL) {
5897 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5898 ARRAY_SIZE(sFormatNameToEnumTable),
5899 str);
5900 if (format != AUDIO_FORMAT_DEFAULT) {
5901 mFormats.add(format);
5902 }
5903 str = strtok(NULL, "|");
5904 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005905}
5906
5907void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5908{
5909 const char *str = strtok(name, "|");
5910
5911 ALOGV("loadInChannels() %s", name);
5912
5913 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5914 mChannelMasks.add(0);
5915 return;
5916 }
5917
5918 while (str != NULL) {
5919 audio_channel_mask_t channelMask =
5920 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5921 ARRAY_SIZE(sInChannelsNameToEnumTable),
5922 str);
5923 if (channelMask != 0) {
5924 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5925 mChannelMasks.add(channelMask);
5926 }
5927 str = strtok(NULL, "|");
5928 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005929}
5930
5931void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5932{
5933 const char *str = strtok(name, "|");
5934
5935 ALOGV("loadOutChannels() %s", name);
5936
5937 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5938 // masks should be read from the output stream after it is opened for the first time
5939 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5940 mChannelMasks.add(0);
5941 return;
5942 }
5943
5944 while (str != NULL) {
5945 audio_channel_mask_t channelMask =
5946 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5947 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5948 str);
5949 if (channelMask != 0) {
5950 mChannelMasks.add(channelMask);
5951 }
5952 str = strtok(NULL, "|");
5953 }
5954 return;
5955}
5956
Eric Laurent1afeecb2014-05-14 08:52:28 -07005957audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5958{
5959 const char *str = strtok(name, "|");
5960
5961 ALOGV("loadGainMode() %s", name);
5962 audio_gain_mode_t mode = 0;
5963 while (str != NULL) {
5964 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5965 ARRAY_SIZE(sGainModeNameToEnumTable),
5966 str);
5967 str = strtok(NULL, "|");
5968 }
5969 return mode;
5970}
5971
Eric Laurenta121f902014-06-03 13:32:54 -07005972void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005973{
5974 cnode *node = root->first_child;
5975
Eric Laurenta121f902014-06-03 13:32:54 -07005976 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005977
5978 while (node) {
5979 if (strcmp(node->name, GAIN_MODE) == 0) {
5980 gain->mGain.mode = loadGainMode((char *)node->value);
5981 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005982 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005983 gain->mGain.channel_mask =
5984 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5985 ARRAY_SIZE(sInChannelsNameToEnumTable),
5986 (char *)node->value);
5987 } else {
5988 gain->mGain.channel_mask =
5989 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5990 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5991 (char *)node->value);
5992 }
5993 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5994 gain->mGain.min_value = atoi((char *)node->value);
5995 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5996 gain->mGain.max_value = atoi((char *)node->value);
5997 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5998 gain->mGain.default_value = atoi((char *)node->value);
5999 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6000 gain->mGain.step_value = atoi((char *)node->value);
6001 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6002 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6003 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6004 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6005 }
6006 node = node->next;
6007 }
6008
6009 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6010 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6011
6012 if (gain->mGain.mode == 0) {
6013 return;
6014 }
6015 mGains.add(gain);
6016}
6017
6018void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6019{
6020 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006021 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006022 while (node) {
6023 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006024 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006025 node = node->next;
6026 }
6027}
6028
Glenn Kastencbd48022014-07-24 13:46:44 -07006029status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006030{
6031 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6032 if (mSamplingRates[i] == samplingRate) {
6033 return NO_ERROR;
6034 }
6035 }
6036 return BAD_VALUE;
6037}
6038
Glenn Kastencbd48022014-07-24 13:46:44 -07006039status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6040 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006041{
Glenn Kastencbd48022014-07-24 13:46:44 -07006042 // Search for the closest supported sampling rate that is above (preferred)
6043 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6044 // The sampling rates do not need to be sorted in ascending order.
6045 ssize_t maxBelow = -1;
6046 ssize_t minAbove = -1;
6047 uint32_t candidate;
6048 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6049 candidate = mSamplingRates[i];
6050 if (candidate == samplingRate) {
6051 if (updatedSamplingRate != NULL) {
6052 *updatedSamplingRate = candidate;
6053 }
6054 return NO_ERROR;
6055 }
6056 // candidate < desired
6057 if (candidate < samplingRate) {
6058 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6059 maxBelow = i;
6060 }
6061 // candidate > desired
6062 } else {
6063 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6064 minAbove = i;
6065 }
6066 }
6067 }
6068 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6069 // TODO Move these assumptions out.
6070 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6071 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6072 // due to approximation by an int32_t of the
6073 // phase increments
6074 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6075 if (minAbove >= 0) {
6076 candidate = mSamplingRates[minAbove];
6077 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6078 if (updatedSamplingRate != NULL) {
6079 *updatedSamplingRate = candidate;
6080 }
6081 return NO_ERROR;
6082 }
6083 }
6084 // But if we have to up-sample from a lower sampling rate, that's OK.
6085 if (maxBelow >= 0) {
6086 candidate = mSamplingRates[maxBelow];
6087 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6088 if (updatedSamplingRate != NULL) {
6089 *updatedSamplingRate = candidate;
6090 }
6091 return NO_ERROR;
6092 }
6093 }
6094 // leave updatedSamplingRate unmodified
6095 return BAD_VALUE;
6096}
6097
6098status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6099{
6100 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006101 if (mChannelMasks[i] == channelMask) {
6102 return NO_ERROR;
6103 }
6104 }
6105 return BAD_VALUE;
6106}
6107
Glenn Kastencbd48022014-07-24 13:46:44 -07006108status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6109 const
6110{
6111 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6112 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6113 // FIXME Does not handle multi-channel automatic conversions yet
6114 audio_channel_mask_t supported = mChannelMasks[i];
6115 if (supported == channelMask) {
6116 return NO_ERROR;
6117 }
6118 if (isRecordThread) {
6119 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6120 // FIXME Abstract this out to a table.
6121 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6122 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6123 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6124 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6125 return NO_ERROR;
6126 }
6127 }
6128 }
6129 return BAD_VALUE;
6130}
6131
Eric Laurenta121f902014-06-03 13:32:54 -07006132status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6133{
6134 for (size_t i = 0; i < mFormats.size(); i ++) {
6135 if (mFormats[i] == format) {
6136 return NO_ERROR;
6137 }
6138 }
6139 return BAD_VALUE;
6140}
6141
Eric Laurent1e693b52014-07-09 15:03:28 -07006142
6143uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6144{
6145 // special case for uninitialized dynamic profile
6146 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6147 return 0;
6148 }
6149
Eric Laurent828bcff2014-09-07 12:26:06 -07006150 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6151 // channel count / sampling rate combination chosen will be supported by the connected
6152 // sink
6153 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6154 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6155 uint32_t samplingRate = UINT_MAX;
6156 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6157 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6158 samplingRate = mSamplingRates[i];
6159 }
6160 }
6161 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6162 }
6163
Eric Laurent1e693b52014-07-09 15:03:28 -07006164 uint32_t samplingRate = 0;
6165 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6166
6167 // For mixed output and inputs, use max mixer sampling rates. Do not
6168 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006169 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006170 maxRate = UINT_MAX;
6171 }
6172 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6173 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6174 samplingRate = mSamplingRates[i];
6175 }
6176 }
6177 return samplingRate;
6178}
6179
6180audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6181{
6182 // special case for uninitialized dynamic profile
6183 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6184 return AUDIO_CHANNEL_NONE;
6185 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006186 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006187
6188 // For direct outputs, pick minimum channel count: this helps ensuring that the
6189 // channel count / sampling rate combination chosen will be supported by the connected
6190 // sink
6191 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6192 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6193 uint32_t channelCount = UINT_MAX;
6194 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6195 uint32_t cnlCount;
6196 if (mUseInChannelMask) {
6197 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6198 } else {
6199 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6200 }
6201 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6202 channelMask = mChannelMasks[i];
6203 channelCount = cnlCount;
6204 }
6205 }
6206 return channelMask;
6207 }
6208
Eric Laurent1e693b52014-07-09 15:03:28 -07006209 uint32_t channelCount = 0;
6210 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6211
6212 // For mixed output and inputs, use max mixer channel count. Do not
6213 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006214 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006215 maxCount = UINT_MAX;
6216 }
6217 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6218 uint32_t cnlCount;
6219 if (mUseInChannelMask) {
6220 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6221 } else {
6222 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6223 }
6224 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6225 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006226 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006227 }
6228 }
6229 return channelMask;
6230}
6231
Andy Hung9a605382014-07-28 16:16:31 -07006232/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006233const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6234 AUDIO_FORMAT_DEFAULT,
6235 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006236 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006237 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006238 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006239 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006240};
6241
6242int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6243 audio_format_t format2)
6244{
6245 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6246 // compressed format and better than any PCM format. This is by design of pickFormat()
6247 if (!audio_is_linear_pcm(format1)) {
6248 if (!audio_is_linear_pcm(format2)) {
6249 return 0;
6250 }
6251 return 1;
6252 }
6253 if (!audio_is_linear_pcm(format2)) {
6254 return -1;
6255 }
6256
6257 int index1 = -1, index2 = -1;
6258 for (size_t i = 0;
6259 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6260 i ++) {
6261 if (sPcmFormatCompareTable[i] == format1) {
6262 index1 = i;
6263 }
6264 if (sPcmFormatCompareTable[i] == format2) {
6265 index2 = i;
6266 }
6267 }
6268 // format1 not found => index1 < 0 => format2 > format1
6269 // format2 not found => index2 < 0 => format2 < format1
6270 return index1 - index2;
6271}
6272
6273audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6274{
6275 // special case for uninitialized dynamic profile
6276 if (mFormats.size() == 1 && mFormats[0] == 0) {
6277 return AUDIO_FORMAT_DEFAULT;
6278 }
6279
6280 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006281 audio_format_t bestFormat =
6282 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6283 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006284 // For mixed output and inputs, use best mixer output format. Do not
6285 // limit format otherwise
6286 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6287 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006288 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006289 bestFormat = AUDIO_FORMAT_INVALID;
6290 }
6291
6292 for (size_t i = 0; i < mFormats.size(); i ++) {
6293 if ((compareFormats(mFormats[i], format) > 0) &&
6294 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6295 format = mFormats[i];
6296 }
6297 }
6298 return format;
6299}
6300
Eric Laurenta121f902014-06-03 13:32:54 -07006301status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6302 int index) const
6303{
6304 if (index < 0 || (size_t)index >= mGains.size()) {
6305 return BAD_VALUE;
6306 }
6307 return mGains[index]->checkConfig(gainConfig);
6308}
6309
Eric Laurent1afeecb2014-05-14 08:52:28 -07006310void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6311{
6312 const size_t SIZE = 256;
6313 char buffer[SIZE];
6314 String8 result;
6315
6316 if (mName.size() != 0) {
6317 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6318 result.append(buffer);
6319 }
6320
6321 if (mSamplingRates.size() != 0) {
6322 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6323 result.append(buffer);
6324 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006325 if (i == 0 && mSamplingRates[i] == 0) {
6326 snprintf(buffer, SIZE, "Dynamic");
6327 } else {
6328 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6329 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006330 result.append(buffer);
6331 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6332 }
6333 result.append("\n");
6334 }
6335
6336 if (mChannelMasks.size() != 0) {
6337 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6338 result.append(buffer);
6339 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006340 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6341
6342 if (i == 0 && mChannelMasks[i] == 0) {
6343 snprintf(buffer, SIZE, "Dynamic");
6344 } else {
6345 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6346 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006347 result.append(buffer);
6348 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6349 }
6350 result.append("\n");
6351 }
6352
6353 if (mFormats.size() != 0) {
6354 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6355 result.append(buffer);
6356 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006357 const char *formatStr = enumToString(sFormatNameToEnumTable,
6358 ARRAY_SIZE(sFormatNameToEnumTable),
6359 mFormats[i]);
6360 if (i == 0 && strcmp(formatStr, "") == 0) {
6361 snprintf(buffer, SIZE, "Dynamic");
6362 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006363 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006364 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006365 result.append(buffer);
6366 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6367 }
6368 result.append("\n");
6369 }
6370 write(fd, result.string(), result.size());
6371 if (mGains.size() != 0) {
6372 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6373 write(fd, buffer, strlen(buffer) + 1);
6374 result.append(buffer);
6375 for (size_t i = 0; i < mGains.size(); i++) {
6376 mGains[i]->dump(fd, spaces + 2, i);
6377 }
6378 }
6379}
6380
6381// --- AudioGain class implementation
6382
Eric Laurenta121f902014-06-03 13:32:54 -07006383AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006384{
Eric Laurenta121f902014-06-03 13:32:54 -07006385 mIndex = index;
6386 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006387 memset(&mGain, 0, sizeof(struct audio_gain));
6388}
6389
Eric Laurenta121f902014-06-03 13:32:54 -07006390void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6391{
6392 config->index = mIndex;
6393 config->mode = mGain.mode;
6394 config->channel_mask = mGain.channel_mask;
6395 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6396 config->values[0] = mGain.default_value;
6397 } else {
6398 uint32_t numValues;
6399 if (mUseInChannelMask) {
6400 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6401 } else {
6402 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6403 }
6404 for (size_t i = 0; i < numValues; i++) {
6405 config->values[i] = mGain.default_value;
6406 }
6407 }
6408 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6409 config->ramp_duration_ms = mGain.min_ramp_ms;
6410 }
6411}
6412
6413status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6414{
6415 if ((config->mode & ~mGain.mode) != 0) {
6416 return BAD_VALUE;
6417 }
6418 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6419 if ((config->values[0] < mGain.min_value) ||
6420 (config->values[0] > mGain.max_value)) {
6421 return BAD_VALUE;
6422 }
6423 } else {
6424 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6425 return BAD_VALUE;
6426 }
6427 uint32_t numValues;
6428 if (mUseInChannelMask) {
6429 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6430 } else {
6431 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6432 }
6433 for (size_t i = 0; i < numValues; i++) {
6434 if ((config->values[i] < mGain.min_value) ||
6435 (config->values[i] > mGain.max_value)) {
6436 return BAD_VALUE;
6437 }
6438 }
6439 }
6440 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6441 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6442 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6443 return BAD_VALUE;
6444 }
6445 }
6446 return NO_ERROR;
6447}
6448
Eric Laurent1afeecb2014-05-14 08:52:28 -07006449void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6450{
6451 const size_t SIZE = 256;
6452 char buffer[SIZE];
6453 String8 result;
6454
6455 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6456 result.append(buffer);
6457 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6458 result.append(buffer);
6459 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6460 result.append(buffer);
6461 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6462 result.append(buffer);
6463 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6464 result.append(buffer);
6465 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6466 result.append(buffer);
6467 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6468 result.append(buffer);
6469 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6470 result.append(buffer);
6471 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6472 result.append(buffer);
6473
6474 write(fd, result.string(), result.size());
6475}
6476
Eric Laurent1f2f2232014-06-02 12:01:23 -07006477// --- AudioPortConfig class implementation
6478
6479AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6480{
6481 mSamplingRate = 0;
6482 mChannelMask = AUDIO_CHANNEL_NONE;
6483 mFormat = AUDIO_FORMAT_INVALID;
6484 mGain.index = -1;
6485}
6486
Eric Laurenta121f902014-06-03 13:32:54 -07006487status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6488 const struct audio_port_config *config,
6489 struct audio_port_config *backupConfig)
6490{
6491 struct audio_port_config localBackupConfig;
6492 status_t status = NO_ERROR;
6493
6494 localBackupConfig.config_mask = config->config_mask;
6495 toAudioPortConfig(&localBackupConfig);
6496
Marco Nelissen961ec212014-08-25 15:58:39 -07006497 sp<AudioPort> audioport = getAudioPort();
6498 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006499 status = NO_INIT;
6500 goto exit;
6501 }
6502 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006503 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006504 if (status != NO_ERROR) {
6505 goto exit;
6506 }
6507 mSamplingRate = config->sample_rate;
6508 }
6509 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006510 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006511 if (status != NO_ERROR) {
6512 goto exit;
6513 }
6514 mChannelMask = config->channel_mask;
6515 }
6516 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006517 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006518 if (status != NO_ERROR) {
6519 goto exit;
6520 }
6521 mFormat = config->format;
6522 }
6523 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006524 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006525 if (status != NO_ERROR) {
6526 goto exit;
6527 }
6528 mGain = config->gain;
6529 }
6530
6531exit:
6532 if (status != NO_ERROR) {
6533 applyAudioPortConfig(&localBackupConfig);
6534 }
6535 if (backupConfig != NULL) {
6536 *backupConfig = localBackupConfig;
6537 }
6538 return status;
6539}
6540
Eric Laurent1f2f2232014-06-02 12:01:23 -07006541void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6542 struct audio_port_config *dstConfig,
6543 const struct audio_port_config *srcConfig) const
6544{
6545 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6546 dstConfig->sample_rate = mSamplingRate;
6547 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6548 dstConfig->sample_rate = srcConfig->sample_rate;
6549 }
6550 } else {
6551 dstConfig->sample_rate = 0;
6552 }
6553 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6554 dstConfig->channel_mask = mChannelMask;
6555 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6556 dstConfig->channel_mask = srcConfig->channel_mask;
6557 }
6558 } else {
6559 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6560 }
6561 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6562 dstConfig->format = mFormat;
6563 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6564 dstConfig->format = srcConfig->format;
6565 }
6566 } else {
6567 dstConfig->format = AUDIO_FORMAT_INVALID;
6568 }
6569 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6570 dstConfig->gain = mGain;
6571 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6572 dstConfig->gain = srcConfig->gain;
6573 }
6574 } else {
6575 dstConfig->gain.index = -1;
6576 }
6577 if (dstConfig->gain.index != -1) {
6578 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6579 } else {
6580 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6581 }
6582}
6583
Eric Laurent1c333e22014-05-20 10:48:17 -07006584// --- IOProfile class implementation
6585
Eric Laurent1afeecb2014-05-14 08:52:28 -07006586AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006587 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006588 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006589{
6590}
6591
Eric Laurente0720872014-03-11 09:30:41 -07006592AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006593{
6594}
6595
6596// checks if the IO profile is compatible with specified parameters.
6597// Sampling rate, format and channel mask must be specified in order to
6598// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006599bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006600 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006601 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006602 audio_format_t format,
6603 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006604 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006605{
Glenn Kastencbd48022014-07-24 13:46:44 -07006606 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6607 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6608 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006609
Glenn Kastencbd48022014-07-24 13:46:44 -07006610 if ((mSupportedDevices.types() & device) != device) {
6611 return false;
6612 }
6613
6614 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006615 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006616 }
6617 uint32_t myUpdatedSamplingRate = samplingRate;
6618 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006619 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006620 }
6621 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6622 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006623 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006624 }
6625
6626 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6627 return false;
6628 }
6629
6630 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6631 checkExactChannelMask(channelMask) != NO_ERROR)) {
6632 return false;
6633 }
6634 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6635 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6636 return false;
6637 }
6638
6639 if (isPlaybackThread && (mFlags & flags) != flags) {
6640 return false;
6641 }
6642 // The only input flag that is allowed to be different is the fast flag.
6643 // An existing fast stream is compatible with a normal track request.
6644 // An existing normal stream is compatible with a fast track request,
6645 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006646 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006647 ~AUDIO_INPUT_FLAG_FAST)) {
6648 return false;
6649 }
6650
6651 if (updatedSamplingRate != NULL) {
6652 *updatedSamplingRate = myUpdatedSamplingRate;
6653 }
6654 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006655}
6656
Eric Laurente0720872014-03-11 09:30:41 -07006657void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006658{
6659 const size_t SIZE = 256;
6660 char buffer[SIZE];
6661 String8 result;
6662
Eric Laurent1afeecb2014-05-14 08:52:28 -07006663 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006664
Eric Laurente552edb2014-03-10 17:42:56 -07006665 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6666 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006667 snprintf(buffer, SIZE, " - devices:\n");
6668 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006669 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006670 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6671 mSupportedDevices[i]->dump(fd, 6, i);
6672 }
Eric Laurente552edb2014-03-10 17:42:56 -07006673}
6674
Eric Laurentd4692962014-05-05 18:13:44 -07006675void AudioPolicyManager::IOProfile::log()
6676{
6677 const size_t SIZE = 256;
6678 char buffer[SIZE];
6679 String8 result;
6680
6681 ALOGV(" - sampling rates: ");
6682 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6683 ALOGV(" %d", mSamplingRates[i]);
6684 }
6685
6686 ALOGV(" - channel masks: ");
6687 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6688 ALOGV(" 0x%04x", mChannelMasks[i]);
6689 }
6690
6691 ALOGV(" - formats: ");
6692 for (size_t i = 0; i < mFormats.size(); i++) {
6693 ALOGV(" 0x%08x", mFormats[i]);
6694 }
6695
6696 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6697 ALOGV(" - flags: 0x%04x\n", mFlags);
6698}
6699
6700
Eric Laurent3a4311c2014-03-17 12:00:47 -07006701// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006702
Eric Laurent1f2f2232014-06-02 12:01:23 -07006703
6704AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6705 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6706 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6707 AUDIO_PORT_ROLE_SOURCE,
6708 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006709 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006710{
Eric Laurenta121f902014-06-03 13:32:54 -07006711 if (mGains.size() > 0) {
6712 mGains[0]->getDefaultConfig(&mGain);
6713 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006714}
6715
Eric Laurent3a4311c2014-03-17 12:00:47 -07006716bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006717{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006718 // Devices are considered equal if they:
6719 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6720 // - have the same address or one device does not specify the address
6721 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006722 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006723 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006724 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006725 mChannelMask == other->mChannelMask);
6726}
6727
6728void AudioPolicyManager::DeviceVector::refreshTypes()
6729{
Eric Laurent1c333e22014-05-20 10:48:17 -07006730 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006731 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006732 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006733 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006734 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006735}
6736
6737ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6738{
6739 for(size_t i = 0; i < size(); i++) {
6740 if (item->equals(itemAt(i))) {
6741 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006742 }
6743 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006744 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006745}
6746
Eric Laurent3a4311c2014-03-17 12:00:47 -07006747ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006748{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006749 ssize_t ret = indexOf(item);
6750
6751 if (ret < 0) {
6752 ret = SortedVector::add(item);
6753 if (ret >= 0) {
6754 refreshTypes();
6755 }
6756 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006757 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006758 ret = -1;
6759 }
6760 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006761}
6762
Eric Laurent3a4311c2014-03-17 12:00:47 -07006763ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6764{
6765 size_t i;
6766 ssize_t ret = indexOf(item);
6767
6768 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006769 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006770 } else {
6771 ret = SortedVector::removeAt(ret);
6772 if (ret >= 0) {
6773 refreshTypes();
6774 }
6775 }
6776 return ret;
6777}
6778
6779void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6780{
6781 DeviceVector deviceList;
6782
6783 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6784 types &= ~role_bit;
6785
6786 while (types) {
6787 uint32_t i = 31 - __builtin_clz(types);
6788 uint32_t type = 1 << i;
6789 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006790 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006791 }
6792}
6793
Eric Laurent1afeecb2014-05-14 08:52:28 -07006794void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6795 const DeviceVector& declaredDevices)
6796{
6797 char *devName = strtok(name, "|");
6798 while (devName != NULL) {
6799 if (strlen(devName) != 0) {
6800 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6801 ARRAY_SIZE(sDeviceNameToEnumTable),
6802 devName);
6803 if (type != AUDIO_DEVICE_NONE) {
6804 add(new DeviceDescriptor(String8(""), type));
6805 } else {
6806 sp<DeviceDescriptor> deviceDesc =
6807 declaredDevices.getDeviceFromName(String8(devName));
6808 if (deviceDesc != 0) {
6809 add(deviceDesc);
6810 }
6811 }
6812 }
6813 devName = strtok(NULL, "|");
6814 }
6815}
6816
Eric Laurent1c333e22014-05-20 10:48:17 -07006817sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6818 audio_devices_t type, String8 address) const
6819{
6820 sp<DeviceDescriptor> device;
6821 for (size_t i = 0; i < size(); i++) {
6822 if (itemAt(i)->mDeviceType == type) {
6823 device = itemAt(i);
6824 if (itemAt(i)->mAddress = address) {
6825 break;
6826 }
6827 }
6828 }
6829 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6830 type, address.string(), device.get());
6831 return device;
6832}
6833
Eric Laurent6a94d692014-05-20 11:18:06 -07006834sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6835 audio_port_handle_t id) const
6836{
6837 sp<DeviceDescriptor> device;
6838 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006839 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006840 if (itemAt(i)->mId == id) {
6841 device = itemAt(i);
6842 break;
6843 }
6844 }
6845 return device;
6846}
6847
Eric Laurent1c333e22014-05-20 10:48:17 -07006848AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6849 audio_devices_t type) const
6850{
6851 DeviceVector devices;
6852 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6853 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6854 devices.add(itemAt(i));
6855 type &= ~itemAt(i)->mDeviceType;
6856 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6857 itemAt(i)->mDeviceType, itemAt(i).get());
6858 }
6859 }
6860 return devices;
6861}
6862
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006863AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6864 audio_devices_t type, String8 address) const
6865{
6866 DeviceVector devices;
6867 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6868 for (size_t i = 0; i < size(); i++) {
6869 //ALOGV(" at i=%d: device=%x, addr=%s",
6870 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6871 if (itemAt(i)->mDeviceType == type) {
6872 if (itemAt(i)->mAddress == address) {
6873 //ALOGV(" found matching address %s", address.string());
6874 devices.add(itemAt(i));
6875 }
6876 }
6877 }
6878 return devices;
6879}
6880
Eric Laurent1afeecb2014-05-14 08:52:28 -07006881sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6882 const String8& name) const
6883{
6884 sp<DeviceDescriptor> device;
6885 for (size_t i = 0; i < size(); i++) {
6886 if (itemAt(i)->mName == name) {
6887 device = itemAt(i);
6888 break;
6889 }
6890 }
6891 return device;
6892}
6893
Eric Laurent6a94d692014-05-20 11:18:06 -07006894void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6895 struct audio_port_config *dstConfig,
6896 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006897{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006898 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6899 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006900 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006901 }
6902
6903 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6904
Eric Laurent6a94d692014-05-20 11:18:06 -07006905 dstConfig->id = mId;
6906 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006907 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006908 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006909 dstConfig->ext.device.type = mDeviceType;
6910 dstConfig->ext.device.hw_module = mModule->mHandle;
6911 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006912}
6913
6914void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6915{
Eric Laurent83b88082014-06-20 18:31:16 -07006916 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006917 AudioPort::toAudioPort(port);
6918 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006919 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006920 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006921 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006922 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6923}
6924
Eric Laurent1afeecb2014-05-14 08:52:28 -07006925status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006926{
6927 const size_t SIZE = 256;
6928 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006929 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006930
Eric Laurent1afeecb2014-05-14 08:52:28 -07006931 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6932 result.append(buffer);
6933 if (mId != 0) {
6934 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6935 result.append(buffer);
6936 }
6937 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6938 enumToString(sDeviceNameToEnumTable,
6939 ARRAY_SIZE(sDeviceNameToEnumTable),
6940 mDeviceType));
6941 result.append(buffer);
6942 if (mAddress.size() != 0) {
6943 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6944 result.append(buffer);
6945 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006946 write(fd, result.string(), result.size());
6947 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006948
6949 return NO_ERROR;
6950}
6951
Eric Laurent4d416952014-08-10 14:07:09 -07006952status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6953{
6954 const size_t SIZE = 256;
6955 char buffer[SIZE];
6956 String8 result;
6957
6958
6959 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6960 result.append(buffer);
6961 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6962 result.append(buffer);
6963 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6964 result.append(buffer);
6965 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6966 result.append(buffer);
6967 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6968 result.append(buffer);
6969 for (size_t i = 0; i < mPatch.num_sources; i++) {
6970 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6971 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6972 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6973 ARRAY_SIZE(sDeviceNameToEnumTable),
6974 mPatch.sources[i].ext.device.type));
6975 } else {
6976 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6977 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6978 }
6979 result.append(buffer);
6980 }
6981 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6982 result.append(buffer);
6983 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6984 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
6985 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6986 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
6987 ARRAY_SIZE(sDeviceNameToEnumTable),
6988 mPatch.sinks[i].ext.device.type));
6989 } else {
6990 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6991 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
6992 }
6993 result.append(buffer);
6994 }
6995
6996 write(fd, result.string(), result.size());
6997 return NO_ERROR;
6998}
Eric Laurent3a4311c2014-03-17 12:00:47 -07006999
7000// --- audio_policy.conf file parsing
7001
Eric Laurent5dbe4712014-09-19 19:04:57 -07007002uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007003{
7004 uint32_t flag = 0;
7005
7006 // it is OK to cast name to non const here as we are not going to use it after
7007 // strtok() modifies it
7008 char *flagName = strtok(name, "|");
7009 while (flagName != NULL) {
7010 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007011 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7012 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007013 flagName);
7014 }
7015 flagName = strtok(NULL, "|");
7016 }
7017 //force direct flag if offload flag is set: offloading implies a direct output stream
7018 // and all common behaviors are driven by checking only the direct flag
7019 // this should normally be set appropriately in the policy configuration file
7020 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7021 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7022 }
7023
Eric Laurent5dbe4712014-09-19 19:04:57 -07007024 return flag;
7025}
7026
7027uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7028{
7029 uint32_t flag = 0;
7030
7031 // it is OK to cast name to non const here as we are not going to use it after
7032 // strtok() modifies it
7033 char *flagName = strtok(name, "|");
7034 while (flagName != NULL) {
7035 if (strlen(flagName) != 0) {
7036 flag |= stringToEnum(sInputFlagNameToEnumTable,
7037 ARRAY_SIZE(sInputFlagNameToEnumTable),
7038 flagName);
7039 }
7040 flagName = strtok(NULL, "|");
7041 }
7042 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007043}
7044
Eric Laurente0720872014-03-11 09:30:41 -07007045audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007046{
7047 uint32_t device = 0;
7048
7049 char *devName = strtok(name, "|");
7050 while (devName != NULL) {
7051 if (strlen(devName) != 0) {
7052 device |= stringToEnum(sDeviceNameToEnumTable,
7053 ARRAY_SIZE(sDeviceNameToEnumTable),
7054 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007055 }
Eric Laurente552edb2014-03-10 17:42:56 -07007056 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007057 }
Eric Laurente552edb2014-03-10 17:42:56 -07007058 return device;
7059}
7060
Eric Laurente0720872014-03-11 09:30:41 -07007061void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007062{
Eric Laurente552edb2014-03-10 17:42:56 -07007063 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007064 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007065 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007066
Eric Laurent1afeecb2014-05-14 08:52:28 -07007067 node = config_find(root, DEVICES_TAG);
7068 if (node != NULL) {
7069 node = node->first_child;
7070 while (node) {
7071 ALOGV("loadHwModule() loading device %s", node->name);
7072 status_t tmpStatus = module->loadDevice(node);
7073 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7074 status = tmpStatus;
7075 }
7076 node = node->next;
7077 }
7078 }
7079 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007080 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007081 node = node->first_child;
7082 while (node) {
7083 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007084 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007085 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7086 status = tmpStatus;
7087 }
7088 node = node->next;
7089 }
7090 }
7091 node = config_find(root, INPUTS_TAG);
7092 if (node != NULL) {
7093 node = node->first_child;
7094 while (node) {
7095 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007096 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007097 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7098 status = tmpStatus;
7099 }
7100 node = node->next;
7101 }
7102 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007103 loadGlobalConfig(root, module);
7104
Eric Laurente552edb2014-03-10 17:42:56 -07007105 if (status == NO_ERROR) {
7106 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007107 }
7108}
7109
Eric Laurente0720872014-03-11 09:30:41 -07007110void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007111{
7112 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7113 if (node == NULL) {
7114 return;
7115 }
7116
7117 node = node->first_child;
7118 while (node) {
7119 ALOGV("loadHwModules() loading module %s", node->name);
7120 loadHwModule(node);
7121 node = node->next;
7122 }
7123}
7124
Eric Laurent1f2f2232014-06-02 12:01:23 -07007125void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007126{
7127 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007128
Eric Laurente552edb2014-03-10 17:42:56 -07007129 if (node == NULL) {
7130 return;
7131 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007132 DeviceVector declaredDevices;
7133 if (module != NULL) {
7134 declaredDevices = module->mDeclaredDevices;
7135 }
7136
Eric Laurente552edb2014-03-10 17:42:56 -07007137 node = node->first_child;
7138 while (node) {
7139 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007140 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7141 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007142 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7143 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007144 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007145 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007146 ARRAY_SIZE(sDeviceNameToEnumTable),
7147 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007148 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007149 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007150 } else {
7151 ALOGW("loadGlobalConfig() default device not specified");
7152 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007153 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007154 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007155 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7156 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007157 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007158 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7159 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7160 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007161 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7162 uint32_t major, minor;
7163 sscanf((char *)node->value, "%u.%u", &major, &minor);
7164 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7165 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7166 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007167 }
7168 node = node->next;
7169 }
7170}
7171
Eric Laurente0720872014-03-11 09:30:41 -07007172status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007173{
7174 cnode *root;
7175 char *data;
7176
7177 data = (char *)load_file(path, NULL);
7178 if (data == NULL) {
7179 return -ENODEV;
7180 }
7181 root = config_node("", "");
7182 config_load(root, data);
7183
Eric Laurente552edb2014-03-10 17:42:56 -07007184 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007185 // legacy audio_policy.conf files have one global_configuration section
7186 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007187 config_free(root);
7188 free(root);
7189 free(data);
7190
7191 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7192
7193 return NO_ERROR;
7194}
7195
Eric Laurente0720872014-03-11 09:30:41 -07007196void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007197{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007198 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007199 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007200 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7201 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007202 mAvailableOutputDevices.add(mDefaultOutputDevice);
7203 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007204
7205 module = new HwModule("primary");
7206
Eric Laurent1afeecb2014-05-14 08:52:28 -07007207 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007208 profile->mSamplingRates.add(44100);
7209 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7210 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007211 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007212 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7213 module->mOutputProfiles.add(profile);
7214
Eric Laurent1afeecb2014-05-14 08:52:28 -07007215 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007216 profile->mSamplingRates.add(8000);
7217 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7218 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007219 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007220 module->mInputProfiles.add(profile);
7221
7222 mHwModules.add(module);
7223}
7224
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007225audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7226{
7227 // flags to stream type mapping
7228 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7229 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7230 }
7231 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7232 return AUDIO_STREAM_BLUETOOTH_SCO;
7233 }
7234
7235 // usage to stream type mapping
7236 switch (attr->usage) {
7237 case AUDIO_USAGE_MEDIA:
7238 case AUDIO_USAGE_GAME:
7239 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7240 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7241 return AUDIO_STREAM_MUSIC;
7242 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7243 return AUDIO_STREAM_SYSTEM;
7244 case AUDIO_USAGE_VOICE_COMMUNICATION:
7245 return AUDIO_STREAM_VOICE_CALL;
7246
7247 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7248 return AUDIO_STREAM_DTMF;
7249
7250 case AUDIO_USAGE_ALARM:
7251 return AUDIO_STREAM_ALARM;
7252 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7253 return AUDIO_STREAM_RING;
7254
7255 case AUDIO_USAGE_NOTIFICATION:
7256 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7257 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7258 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7259 case AUDIO_USAGE_NOTIFICATION_EVENT:
7260 return AUDIO_STREAM_NOTIFICATION;
7261
7262 case AUDIO_USAGE_UNKNOWN:
7263 default:
7264 return AUDIO_STREAM_MUSIC;
7265 }
7266}
Eric Laurente552edb2014-03-10 17:42:56 -07007267}; // namespace android