blob: 535e825e8337c5f59d7a029dc2c9e9884b13a116 [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()
Hochi Huang327cb702014-09-21 09:47:31 +080029#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
Eric Laurente552edb2014-03-10 17:42:56 -070030// 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 &&
Hochi Huang327cb702014-09-21 09:47:31 +0800710 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700711 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
712 return;
713 }
714 mForceUse[usage] = config;
715 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700716 case AUDIO_POLICY_FORCE_FOR_RECORD:
717 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
718 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700719 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
720 return;
721 }
722 mForceUse[usage] = config;
723 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700724 case AUDIO_POLICY_FORCE_FOR_DOCK:
725 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
726 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
727 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
728 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
729 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700730 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
731 }
732 forceVolumeReeval = true;
733 mForceUse[usage] = config;
734 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700735 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
736 if (config != AUDIO_POLICY_FORCE_NONE &&
737 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700738 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
739 }
740 forceVolumeReeval = true;
741 mForceUse[usage] = config;
742 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900743 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
744 if (config != AUDIO_POLICY_FORCE_NONE &&
745 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
746 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
747 }
748 mForceUse[usage] = config;
749 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700750 default:
751 ALOGW("setForceUse() invalid usage %d", usage);
752 break;
753 }
754
755 // check for device and output changes triggered by new force usage
756 checkA2dpSuspend();
757 checkOutputForAllStrategies();
758 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700759 if (mPhoneState == AUDIO_MODE_IN_CALL) {
760 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
761 updateCallRouting(newDevice);
762 }
Eric Laurente552edb2014-03-10 17:42:56 -0700763 for (size_t i = 0; i < mOutputs.size(); i++) {
764 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700765 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700766 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
767 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
768 }
Eric Laurente552edb2014-03-10 17:42:56 -0700769 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
770 applyStreamVolumes(output, newDevice, 0, true);
771 }
772 }
773
774 audio_io_handle_t activeInput = getActiveInput();
775 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700776 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700777 }
778
779}
780
Eric Laurente0720872014-03-11 09:30:41 -0700781audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700782{
783 return mForceUse[usage];
784}
785
Eric Laurente0720872014-03-11 09:30:41 -0700786void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700787{
788 ALOGV("setSystemProperty() property %s, value %s", property, value);
789}
790
791// Find a direct output profile compatible with the parameters passed, even if the input flags do
792// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700793sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700794 audio_devices_t device,
795 uint32_t samplingRate,
796 audio_format_t format,
797 audio_channel_mask_t channelMask,
798 audio_output_flags_t flags)
799{
800 for (size_t i = 0; i < mHwModules.size(); i++) {
801 if (mHwModules[i]->mHandle == 0) {
802 continue;
803 }
804 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700805 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700806 bool found = profile->isCompatibleProfile(device, samplingRate,
807 NULL /*updatedSamplingRate*/, format, channelMask,
808 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
809 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700810 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
811 return profile;
812 }
Eric Laurente552edb2014-03-10 17:42:56 -0700813 }
814 }
815 return 0;
816}
817
Eric Laurente0720872014-03-11 09:30:41 -0700818audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700819 uint32_t samplingRate,
820 audio_format_t format,
821 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700822 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700823 const audio_offload_info_t *offloadInfo)
824{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700825
Eric Laurent3b73df72014-03-11 09:06:29 -0700826 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700827 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
828 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
829 device, stream, samplingRate, format, channelMask, flags);
830
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700831 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
832 offloadInfo);
833}
834
835audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
836 uint32_t samplingRate,
837 audio_format_t format,
838 audio_channel_mask_t channelMask,
839 audio_output_flags_t flags,
840 const audio_offload_info_t *offloadInfo)
841{
842 if (attr == NULL) {
843 ALOGE("getOutputForAttr() called with NULL audio attributes");
844 return 0;
845 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700846 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
847 attr->usage, attr->content_type, attr->tags, attr->flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848
849 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
850 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
851 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700852
853 if ((attr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
854 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
855 }
856
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700857 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
858 device, samplingRate, format, channelMask, flags);
859
860 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
861 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
862 offloadInfo);
863}
864
865audio_io_handle_t AudioPolicyManager::getOutputForDevice(
866 audio_devices_t device,
867 audio_stream_type_t stream,
868 uint32_t samplingRate,
869 audio_format_t format,
870 audio_channel_mask_t channelMask,
871 audio_output_flags_t flags,
872 const audio_offload_info_t *offloadInfo)
873{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700874 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700875 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700876 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700877
Eric Laurente552edb2014-03-10 17:42:56 -0700878#ifdef AUDIO_POLICY_TEST
879 if (mCurOutput != 0) {
880 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
881 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
882
883 if (mTestOutputs[mCurOutput] == 0) {
884 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700885 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700886 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700887 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700888 outputDesc->mFlags =
889 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700890 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700891 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
892 config.sample_rate = mTestSamplingRate;
893 config.channel_mask = mTestChannels;
894 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700895 if (offloadInfo != NULL) {
896 config.offload_info = *offloadInfo;
897 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700898 status = mpClientInterface->openOutput(0,
899 &mTestOutputs[mCurOutput],
900 &config,
901 &outputDesc->mDevice,
902 String8(""),
903 &outputDesc->mLatency,
904 outputDesc->mFlags);
905 if (status == NO_ERROR) {
906 outputDesc->mSamplingRate = config.sample_rate;
907 outputDesc->mFormat = config.format;
908 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700909 AudioParameter outputCmd = AudioParameter();
910 outputCmd.addInt(String8("set_id"),mCurOutput);
911 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
912 addOutput(mTestOutputs[mCurOutput], outputDesc);
913 }
914 }
915 return mTestOutputs[mCurOutput];
916 }
917#endif //AUDIO_POLICY_TEST
918
919 // open a direct output if required by specified parameters
920 //force direct flag if offload flag is set: offloading implies a direct output stream
921 // and all common behaviors are driven by checking only the direct flag
922 // this should normally be set appropriately in the policy configuration file
923 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700924 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700925 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700926 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
927 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
928 }
Eric Laurente552edb2014-03-10 17:42:56 -0700929
Eric Laurentb732cf52014-09-24 19:08:21 -0700930 sp<IOProfile> profile;
931
932 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700933 // and not explicitly requested
934 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
935 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700936 audio_channel_count_from_out_mask(channelMask) <= 2) {
937 goto non_direct_output;
938 }
939
Eric Laurente552edb2014-03-10 17:42:56 -0700940 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
941 // creating an offloaded track and tearing it down immediately after start when audioflinger
942 // detects there is an active non offloadable effect.
943 // FIXME: We should check the audio session here but we do not have it in this context.
944 // This may prevent offloading in rare situations where effects are left active by apps
945 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700946
Eric Laurente552edb2014-03-10 17:42:56 -0700947 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
948 !isNonOffloadableEffectEnabled()) {
949 profile = getProfileForDirectOutput(device,
950 samplingRate,
951 format,
952 channelMask,
953 (audio_output_flags_t)flags);
954 }
955
Eric Laurent1c333e22014-05-20 10:48:17 -0700956 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700957 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700958
959 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700960 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700961 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
962 outputDesc = desc;
963 // reuse direct output if currently open and configured with same parameters
964 if ((samplingRate == outputDesc->mSamplingRate) &&
965 (format == outputDesc->mFormat) &&
966 (channelMask == outputDesc->mChannelMask)) {
967 outputDesc->mDirectOpenCount++;
968 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
969 return mOutputs.keyAt(i);
970 }
971 }
972 }
973 // close direct output if currently open and configured with different parameters
974 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700975 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700976 }
977 outputDesc = new AudioOutputDescriptor(profile);
978 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700979 outputDesc->mLatency = 0;
980 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700981 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
982 config.sample_rate = samplingRate;
983 config.channel_mask = channelMask;
984 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700985 if (offloadInfo != NULL) {
986 config.offload_info = *offloadInfo;
987 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700988 status = mpClientInterface->openOutput(profile->mModule->mHandle,
989 &output,
990 &config,
991 &outputDesc->mDevice,
992 String8(""),
993 &outputDesc->mLatency,
994 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700995
996 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700997 if (status != NO_ERROR ||
998 (samplingRate != 0 && samplingRate != config.sample_rate) ||
999 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1000 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001001 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1002 "format %d %d, channelMask %04x %04x", output, samplingRate,
1003 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1004 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001005 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001006 mpClientInterface->closeOutput(output);
1007 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001008 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001009 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001010 outputDesc->mSamplingRate = config.sample_rate;
1011 outputDesc->mChannelMask = config.channel_mask;
1012 outputDesc->mFormat = config.format;
1013 outputDesc->mRefCount[stream] = 0;
1014 outputDesc->mStopTime[stream] = 0;
1015 outputDesc->mDirectOpenCount = 1;
1016
Eric Laurente552edb2014-03-10 17:42:56 -07001017 audio_io_handle_t srcOutput = getOutputForEffect();
1018 addOutput(output, outputDesc);
1019 audio_io_handle_t dstOutput = getOutputForEffect();
1020 if (dstOutput == output) {
1021 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1022 }
1023 mPreviousOutputs = mOutputs;
1024 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001025 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001026 return output;
1027 }
1028
Eric Laurentb732cf52014-09-24 19:08:21 -07001029non_direct_output:
1030
Eric Laurente552edb2014-03-10 17:42:56 -07001031 // ignoring channel mask due to downmix capability in mixer
1032
1033 // open a non direct output
1034
1035 // for non direct outputs, only PCM is supported
1036 if (audio_is_linear_pcm(format)) {
1037 // get which output is suitable for the specified stream. The actual
1038 // routing change will happen when startOutput() will be called
1039 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1040
Eric Laurent8838a382014-09-08 16:44:28 -07001041 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1042 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1043 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001044 }
1045 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1046 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1047
1048 ALOGV("getOutput() returns output %d", output);
1049
1050 return output;
1051}
1052
Eric Laurente0720872014-03-11 09:30:41 -07001053audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001054 audio_output_flags_t flags,
1055 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001056{
1057 // select one output among several that provide a path to a particular device or set of
1058 // devices (the list was previously build by getOutputsForDevice()).
1059 // The priority is as follows:
1060 // 1: the output with the highest number of requested policy flags
1061 // 2: the primary output
1062 // 3: the first output in the list
1063
1064 if (outputs.size() == 0) {
1065 return 0;
1066 }
1067 if (outputs.size() == 1) {
1068 return outputs[0];
1069 }
1070
1071 int maxCommonFlags = 0;
1072 audio_io_handle_t outputFlags = 0;
1073 audio_io_handle_t outputPrimary = 0;
1074
1075 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001076 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001077 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001078 // if a valid format is specified, skip output if not compatible
1079 if (format != AUDIO_FORMAT_INVALID) {
1080 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1081 if (format != outputDesc->mFormat) {
1082 continue;
1083 }
1084 } else if (!audio_is_linear_pcm(format)) {
1085 continue;
1086 }
1087 }
1088
Eric Laurent3b73df72014-03-11 09:06:29 -07001089 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001090 if (commonFlags > maxCommonFlags) {
1091 outputFlags = outputs[i];
1092 maxCommonFlags = commonFlags;
1093 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1094 }
1095 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1096 outputPrimary = outputs[i];
1097 }
1098 }
1099 }
1100
1101 if (outputFlags != 0) {
1102 return outputFlags;
1103 }
1104 if (outputPrimary != 0) {
1105 return outputPrimary;
1106 }
1107
1108 return outputs[0];
1109}
1110
Eric Laurente0720872014-03-11 09:30:41 -07001111status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001112 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001113 int session)
1114{
1115 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1116 ssize_t index = mOutputs.indexOfKey(output);
1117 if (index < 0) {
1118 ALOGW("startOutput() unknown output %d", output);
1119 return BAD_VALUE;
1120 }
1121
Eric Laurent1f2f2232014-06-02 12:01:23 -07001122 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001123
1124 // increment usage count for this stream on the requested output:
1125 // NOTE that the usage count is the same for duplicated output and hardware output which is
1126 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1127 outputDesc->changeRefCount(stream, 1);
1128
1129 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001130 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001131 routing_strategy strategy = getStrategy(stream);
1132 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1133 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1134 uint32_t waitMs = 0;
1135 bool force = false;
1136 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001137 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001138 if (desc != outputDesc) {
1139 // force a device change if any other output is managed by the same hw
1140 // module and has a current device selection that differs from selected device.
1141 // In this case, the audio HAL must receive the new device selection so that it can
1142 // change the device currently selected by the other active output.
1143 if (outputDesc->sharesHwModuleWith(desc) &&
1144 desc->device() != newDevice) {
1145 force = true;
1146 }
1147 // wait for audio on other active outputs to be presented when starting
1148 // a notification so that audio focus effect can propagate.
1149 uint32_t latency = desc->latency();
1150 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1151 waitMs = latency;
1152 }
1153 }
1154 }
1155 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1156
1157 // handle special case for sonification while in call
1158 if (isInCall()) {
1159 handleIncallSonification(stream, true, false);
1160 }
1161
1162 // apply volume rules for current stream and device if necessary
1163 checkAndSetVolume(stream,
1164 mStreams[stream].getVolumeIndex(newDevice),
1165 output,
1166 newDevice);
1167
1168 // update the outputs if starting an output with a stream that can affect notification
1169 // routing
1170 handleNotificationRoutingForStream(stream);
1171 if (waitMs > muteWaitMs) {
1172 usleep((waitMs - muteWaitMs) * 2 * 1000);
1173 }
1174 }
1175 return NO_ERROR;
1176}
1177
1178
Eric Laurente0720872014-03-11 09:30:41 -07001179status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001180 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001181 int session)
1182{
1183 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1184 ssize_t index = mOutputs.indexOfKey(output);
1185 if (index < 0) {
1186 ALOGW("stopOutput() unknown output %d", output);
1187 return BAD_VALUE;
1188 }
1189
Eric Laurent1f2f2232014-06-02 12:01:23 -07001190 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001191
1192 // handle special case for sonification while in call
1193 if (isInCall()) {
1194 handleIncallSonification(stream, false, false);
1195 }
1196
1197 if (outputDesc->mRefCount[stream] > 0) {
1198 // decrement usage count of this stream on the output
1199 outputDesc->changeRefCount(stream, -1);
1200 // store time at which the stream was stopped - see isStreamActive()
1201 if (outputDesc->mRefCount[stream] == 0) {
1202 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001203 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001204 // delay the device switch by twice the latency because stopOutput() is executed when
1205 // the track stop() command is received and at that time the audio track buffer can
1206 // still contain data that needs to be drained. The latency only covers the audio HAL
1207 // and kernel buffers. Also the latency does not always include additional delay in the
1208 // audio path (audio DSP, CODEC ...)
1209 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1210
1211 // force restoring the device selection on other active outputs if it differs from the
1212 // one being selected for this output
1213 for (size_t i = 0; i < mOutputs.size(); i++) {
1214 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001215 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001216 if (curOutput != output &&
1217 desc->isActive() &&
1218 outputDesc->sharesHwModuleWith(desc) &&
1219 (newDevice != desc->device())) {
1220 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001221 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001222 true,
1223 outputDesc->mLatency*2);
1224 }
1225 }
1226 // update the outputs if stopping one with a stream that can affect notification routing
1227 handleNotificationRoutingForStream(stream);
1228 }
1229 return NO_ERROR;
1230 } else {
1231 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1232 return INVALID_OPERATION;
1233 }
1234}
1235
Eric Laurente0720872014-03-11 09:30:41 -07001236void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001237{
1238 ALOGV("releaseOutput() %d", output);
1239 ssize_t index = mOutputs.indexOfKey(output);
1240 if (index < 0) {
1241 ALOGW("releaseOutput() releasing unknown output %d", output);
1242 return;
1243 }
1244
1245#ifdef AUDIO_POLICY_TEST
1246 int testIndex = testOutputIndex(output);
1247 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001248 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001249 if (outputDesc->isActive()) {
1250 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001251 mOutputs.removeItem(output);
1252 mTestOutputs[testIndex] = 0;
1253 }
1254 return;
1255 }
1256#endif //AUDIO_POLICY_TEST
1257
Eric Laurent1f2f2232014-06-02 12:01:23 -07001258 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001259 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001260 if (desc->mDirectOpenCount <= 0) {
1261 ALOGW("releaseOutput() invalid open count %d for output %d",
1262 desc->mDirectOpenCount, output);
1263 return;
1264 }
1265 if (--desc->mDirectOpenCount == 0) {
1266 closeOutput(output);
1267 // If effects where present on the output, audioflinger moved them to the primary
1268 // output by default: move them back to the appropriate output.
1269 audio_io_handle_t dstOutput = getOutputForEffect();
1270 if (dstOutput != mPrimaryOutput) {
1271 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1272 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001273 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001274 }
1275 }
1276}
1277
1278
Eric Laurente0720872014-03-11 09:30:41 -07001279audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001280 uint32_t samplingRate,
1281 audio_format_t format,
1282 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001283 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001284 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001285{
Eric Laurent4dc68062014-07-28 17:26:49 -07001286 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001287 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001288 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001289
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001290 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001291
1292 if (device == AUDIO_DEVICE_NONE) {
1293 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001294 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001295 }
1296
1297 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001298 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001299 case AUDIO_SOURCE_VOICE_UPLINK:
1300 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1301 break;
1302 case AUDIO_SOURCE_VOICE_DOWNLINK:
1303 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1304 break;
1305 case AUDIO_SOURCE_VOICE_CALL:
1306 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1307 break;
1308 default:
1309 break;
1310 }
1311
Eric Laurent5dbe4712014-09-19 19:04:57 -07001312 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1313 bool isSoundTrigger = false;
1314 audio_source_t halInputSource = inputSource;
1315 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1316 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1317 if (index >= 0) {
1318 input = mSoundTriggerSessions.valueFor(session);
1319 isSoundTrigger = true;
1320 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1321 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1322 } else {
1323 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1324 }
1325 }
1326
Eric Laurent1c333e22014-05-20 10:48:17 -07001327 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001328 samplingRate,
1329 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001330 channelMask,
1331 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001332 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001333 //retry without flags
1334 audio_input_flags_t log_flags = flags;
1335 flags = AUDIO_INPUT_FLAG_NONE;
1336 profile = getInputProfile(device,
1337 samplingRate,
1338 format,
1339 channelMask,
1340 flags);
1341 if (profile == 0) {
1342 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1343 "channelMask 0x%X, flags %#x",
1344 device, samplingRate, format, channelMask, log_flags);
1345 return AUDIO_IO_HANDLE_NONE;
1346 }
Eric Laurente552edb2014-03-10 17:42:56 -07001347 }
1348
1349 if (profile->mModule->mHandle == 0) {
1350 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001351 return AUDIO_IO_HANDLE_NONE;
1352 }
1353
1354 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1355 config.sample_rate = samplingRate;
1356 config.channel_mask = channelMask;
1357 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001358
Eric Laurentcf2c0212014-07-25 16:20:43 -07001359 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1360 &input,
1361 &config,
1362 &device,
1363 String8(""),
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001364 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001365 flags);
1366
1367 // only accept input with the exact requested set of parameters
1368 if (status != NO_ERROR ||
1369 (samplingRate != config.sample_rate) ||
1370 (format != config.format) ||
1371 (channelMask != config.channel_mask)) {
1372 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1373 samplingRate, format, channelMask);
1374 if (input != AUDIO_IO_HANDLE_NONE) {
1375 mpClientInterface->closeInput(input);
1376 }
1377 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001378 }
1379
Eric Laurent1f2f2232014-06-02 12:01:23 -07001380 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001381 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001382 inputDesc->mRefCount = 0;
1383 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001384 inputDesc->mSamplingRate = samplingRate;
1385 inputDesc->mFormat = format;
1386 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001387 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001388 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001389 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001390
Eric Laurentd4692962014-05-05 18:13:44 -07001391 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001392 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001393 return input;
1394}
1395
Eric Laurent4dc68062014-07-28 17:26:49 -07001396status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1397 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001398{
1399 ALOGV("startInput() input %d", input);
1400 ssize_t index = mInputs.indexOfKey(input);
1401 if (index < 0) {
1402 ALOGW("startInput() unknown input %d", input);
1403 return BAD_VALUE;
1404 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001405 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001406
Eric Laurent4dc68062014-07-28 17:26:49 -07001407 index = inputDesc->mSessions.indexOf(session);
1408 if (index < 0) {
1409 ALOGW("startInput() unknown session %d on input %d", session, input);
1410 return BAD_VALUE;
1411 }
1412
Glenn Kasten74a8e252014-07-24 14:09:55 -07001413 // virtual input devices are compatible with other input devices
1414 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1415
1416 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001417 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001418 if (activeInput != 0 && activeInput != input) {
1419
1420 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1421 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001422 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001423 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001424 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001425 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1426 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001427 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001428 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001429 return INVALID_OPERATION;
1430 }
1431 }
1432 }
1433
Glenn Kasten74a8e252014-07-24 14:09:55 -07001434 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001435 if (activeInputsCount() == 0) {
1436 SoundTrigger::setCaptureState(true);
1437 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001438 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001439
Glenn Kasten74a8e252014-07-24 14:09:55 -07001440 // Automatically enable the remote submix output when input is started.
1441 // For remote submix (a virtual device), we open only one input per capture request.
1442 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1443 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1444 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1445 }
Eric Laurente552edb2014-03-10 17:42:56 -07001446 }
1447
Eric Laurente552edb2014-03-10 17:42:56 -07001448 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1449
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001450 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001451 return NO_ERROR;
1452}
1453
Eric Laurent4dc68062014-07-28 17:26:49 -07001454status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1455 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001456{
1457 ALOGV("stopInput() input %d", input);
1458 ssize_t index = mInputs.indexOfKey(input);
1459 if (index < 0) {
1460 ALOGW("stopInput() unknown input %d", input);
1461 return BAD_VALUE;
1462 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001463 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001464
Eric Laurent4dc68062014-07-28 17:26:49 -07001465 index = inputDesc->mSessions.indexOf(session);
1466 if (index < 0) {
1467 ALOGW("stopInput() unknown session %d on input %d", session, input);
1468 return BAD_VALUE;
1469 }
1470
Eric Laurente552edb2014-03-10 17:42:56 -07001471 if (inputDesc->mRefCount == 0) {
1472 ALOGW("stopInput() input %d already stopped", input);
1473 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001474 }
1475
1476 inputDesc->mRefCount--;
1477 if (inputDesc->mRefCount == 0) {
1478
Eric Laurente552edb2014-03-10 17:42:56 -07001479 // automatically disable the remote submix output when input is stopped
1480 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1481 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001482 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001483 }
1484
Eric Laurent1c333e22014-05-20 10:48:17 -07001485 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001486
1487 if (activeInputsCount() == 0) {
1488 SoundTrigger::setCaptureState(false);
1489 }
Eric Laurente552edb2014-03-10 17:42:56 -07001490 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001491 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001492}
1493
Eric Laurent4dc68062014-07-28 17:26:49 -07001494void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1495 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001496{
1497 ALOGV("releaseInput() %d", input);
1498 ssize_t index = mInputs.indexOfKey(input);
1499 if (index < 0) {
1500 ALOGW("releaseInput() releasing unknown input %d", input);
1501 return;
1502 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001503 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1504 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001505
1506 index = inputDesc->mSessions.indexOf(session);
1507 if (index < 0) {
1508 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1509 return;
1510 }
1511 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001512 if (inputDesc->mOpenRefCount == 0) {
1513 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1514 return;
1515 }
1516 inputDesc->mOpenRefCount--;
1517 if (inputDesc->mOpenRefCount > 0) {
1518 ALOGV("releaseInput() exit > 0");
1519 return;
1520 }
1521
Eric Laurent05b90f82014-08-27 15:32:29 -07001522 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001523 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001524 ALOGV("releaseInput() exit");
1525}
1526
Eric Laurentd4692962014-05-05 18:13:44 -07001527void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001528 bool patchRemoved = false;
1529
Eric Laurentd4692962014-05-05 18:13:44 -07001530 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001531 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1532 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1533 if (patch_index >= 0) {
1534 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1535 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1536 mAudioPatches.removeItemsAt(patch_index);
1537 patchRemoved = true;
1538 }
Eric Laurentd4692962014-05-05 18:13:44 -07001539 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1540 }
1541 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001542 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001543
1544 if (patchRemoved) {
1545 mpClientInterface->onAudioPatchListUpdate();
1546 }
Eric Laurentd4692962014-05-05 18:13:44 -07001547}
1548
Eric Laurente0720872014-03-11 09:30:41 -07001549void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001550 int indexMin,
1551 int indexMax)
1552{
1553 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1554 if (indexMin < 0 || indexMin >= indexMax) {
1555 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1556 return;
1557 }
1558 mStreams[stream].mIndexMin = indexMin;
1559 mStreams[stream].mIndexMax = indexMax;
1560}
1561
Eric Laurente0720872014-03-11 09:30:41 -07001562status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001563 int index,
1564 audio_devices_t device)
1565{
1566
1567 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1568 return BAD_VALUE;
1569 }
1570 if (!audio_is_output_device(device)) {
1571 return BAD_VALUE;
1572 }
1573
1574 // Force max volume if stream cannot be muted
1575 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1576
1577 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1578 stream, device, index);
1579
1580 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1581 // clear all device specific values
1582 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1583 mStreams[stream].mIndexCur.clear();
1584 }
1585 mStreams[stream].mIndexCur.add(device, index);
1586
Eric Laurent31551f82014-10-10 18:21:56 -07001587 // update volume on all outputs whose current device is also selected by the same
1588 // strategy as the device specified by the caller
1589 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1590 if ((device != AUDIO_DEVICE_OUT_DEFAULT) && (device & strategyDevice) == 0) {
1591 return NO_ERROR;
1592 }
Eric Laurente552edb2014-03-10 17:42:56 -07001593 status_t status = NO_ERROR;
1594 for (size_t i = 0; i < mOutputs.size(); i++) {
1595 audio_devices_t curDevice =
1596 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001597 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001598 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1599 if (volStatus != NO_ERROR) {
1600 status = volStatus;
1601 }
1602 }
1603 }
1604 return status;
1605}
1606
Eric Laurente0720872014-03-11 09:30:41 -07001607status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001608 int *index,
1609 audio_devices_t device)
1610{
1611 if (index == NULL) {
1612 return BAD_VALUE;
1613 }
1614 if (!audio_is_output_device(device)) {
1615 return BAD_VALUE;
1616 }
1617 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1618 // the strategy the stream belongs to.
1619 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1620 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1621 }
1622 device = getDeviceForVolume(device);
1623
1624 *index = mStreams[stream].getVolumeIndex(device);
1625 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1626 return NO_ERROR;
1627}
1628
Eric Laurente0720872014-03-11 09:30:41 -07001629audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001630 const SortedVector<audio_io_handle_t>& outputs)
1631{
1632 // select one output among several suitable for global effects.
1633 // The priority is as follows:
1634 // 1: An offloaded output. If the effect ends up not being offloadable,
1635 // AudioFlinger will invalidate the track and the offloaded output
1636 // will be closed causing the effect to be moved to a PCM output.
1637 // 2: A deep buffer output
1638 // 3: the first output in the list
1639
1640 if (outputs.size() == 0) {
1641 return 0;
1642 }
1643
1644 audio_io_handle_t outputOffloaded = 0;
1645 audio_io_handle_t outputDeepBuffer = 0;
1646
1647 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001648 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001649 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001650 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1651 outputOffloaded = outputs[i];
1652 }
1653 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1654 outputDeepBuffer = outputs[i];
1655 }
1656 }
1657
1658 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1659 outputOffloaded, outputDeepBuffer);
1660 if (outputOffloaded != 0) {
1661 return outputOffloaded;
1662 }
1663 if (outputDeepBuffer != 0) {
1664 return outputDeepBuffer;
1665 }
1666
1667 return outputs[0];
1668}
1669
Eric Laurente0720872014-03-11 09:30:41 -07001670audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001671{
1672 // apply simple rule where global effects are attached to the same output as MUSIC streams
1673
Eric Laurent3b73df72014-03-11 09:06:29 -07001674 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001675 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1676 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1677
1678 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1679 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1680 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1681
1682 return output;
1683}
1684
Eric Laurente0720872014-03-11 09:30:41 -07001685status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001686 audio_io_handle_t io,
1687 uint32_t strategy,
1688 int session,
1689 int id)
1690{
1691 ssize_t index = mOutputs.indexOfKey(io);
1692 if (index < 0) {
1693 index = mInputs.indexOfKey(io);
1694 if (index < 0) {
1695 ALOGW("registerEffect() unknown io %d", io);
1696 return INVALID_OPERATION;
1697 }
1698 }
1699
1700 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1701 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1702 desc->name, desc->memoryUsage);
1703 return INVALID_OPERATION;
1704 }
1705 mTotalEffectsMemory += desc->memoryUsage;
1706 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1707 desc->name, io, strategy, session, id);
1708 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1709
Eric Laurent1f2f2232014-06-02 12:01:23 -07001710 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1711 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1712 effectDesc->mIo = io;
1713 effectDesc->mStrategy = (routing_strategy)strategy;
1714 effectDesc->mSession = session;
1715 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001716
Eric Laurent1f2f2232014-06-02 12:01:23 -07001717 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001718
1719 return NO_ERROR;
1720}
1721
Eric Laurente0720872014-03-11 09:30:41 -07001722status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001723{
1724 ssize_t index = mEffects.indexOfKey(id);
1725 if (index < 0) {
1726 ALOGW("unregisterEffect() unknown effect ID %d", id);
1727 return INVALID_OPERATION;
1728 }
1729
Eric Laurent1f2f2232014-06-02 12:01:23 -07001730 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001731
Eric Laurent1f2f2232014-06-02 12:01:23 -07001732 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001733
Eric Laurent1f2f2232014-06-02 12:01:23 -07001734 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001735 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001736 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1737 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001738 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001739 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001740 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001741 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001742
1743 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001744
1745 return NO_ERROR;
1746}
1747
Eric Laurente0720872014-03-11 09:30:41 -07001748status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001749{
1750 ssize_t index = mEffects.indexOfKey(id);
1751 if (index < 0) {
1752 ALOGW("unregisterEffect() unknown effect ID %d", id);
1753 return INVALID_OPERATION;
1754 }
1755
1756 return setEffectEnabled(mEffects.valueAt(index), enabled);
1757}
1758
Eric Laurent1f2f2232014-06-02 12:01:23 -07001759status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001760{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001761 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001762 ALOGV("setEffectEnabled(%s) effect already %s",
1763 enabled?"true":"false", enabled?"enabled":"disabled");
1764 return INVALID_OPERATION;
1765 }
1766
1767 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001768 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001769 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001770 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001771 return INVALID_OPERATION;
1772 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001773 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001774 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1775 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001776 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001777 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001778 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1779 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001780 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001781 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001782 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1783 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001784 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001785 return NO_ERROR;
1786}
1787
Eric Laurente0720872014-03-11 09:30:41 -07001788bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001789{
1790 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001791 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1792 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1793 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001794 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001795 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001796 return true;
1797 }
1798 }
1799 return false;
1800}
1801
Eric Laurente0720872014-03-11 09:30:41 -07001802bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001803{
1804 nsecs_t sysTime = systemTime();
1805 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001806 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001807 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001808 return true;
1809 }
1810 }
1811 return false;
1812}
1813
Eric Laurente0720872014-03-11 09:30:41 -07001814bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001815 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001816{
1817 nsecs_t sysTime = systemTime();
1818 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001819 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001820 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001821 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001822 return true;
1823 }
1824 }
1825 return false;
1826}
1827
Eric Laurente0720872014-03-11 09:30:41 -07001828bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001829{
1830 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001831 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001832 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001833 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001834 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1835 && (inputDescriptor->mRefCount > 0)) {
1836 return true;
1837 }
1838 }
1839 return false;
1840}
1841
1842
Eric Laurente0720872014-03-11 09:30:41 -07001843status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001844{
1845 const size_t SIZE = 256;
1846 char buffer[SIZE];
1847 String8 result;
1848
1849 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1850 result.append(buffer);
1851
1852 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1853 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001854 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1855 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001856 snprintf(buffer, SIZE, " Force use for communications %d\n",
1857 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001858 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001859 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001860 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001861 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001862 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001863 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001864 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001865 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001866 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001867 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1868 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1869 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001870
Eric Laurent3a4311c2014-03-17 12:00:47 -07001871 snprintf(buffer, SIZE, " Available output devices:\n");
1872 result.append(buffer);
1873 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001874 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001875 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001876 }
1877 snprintf(buffer, SIZE, "\n Available input devices:\n");
1878 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001879 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001880 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001881 }
Eric Laurente552edb2014-03-10 17:42:56 -07001882
1883 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1884 write(fd, buffer, strlen(buffer));
1885 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001886 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001887 write(fd, buffer, strlen(buffer));
1888 mHwModules[i]->dump(fd);
1889 }
1890
1891 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1892 write(fd, buffer, strlen(buffer));
1893 for (size_t i = 0; i < mOutputs.size(); i++) {
1894 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1895 write(fd, buffer, strlen(buffer));
1896 mOutputs.valueAt(i)->dump(fd);
1897 }
1898
1899 snprintf(buffer, SIZE, "\nInputs dump:\n");
1900 write(fd, buffer, strlen(buffer));
1901 for (size_t i = 0; i < mInputs.size(); i++) {
1902 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1903 write(fd, buffer, strlen(buffer));
1904 mInputs.valueAt(i)->dump(fd);
1905 }
1906
1907 snprintf(buffer, SIZE, "\nStreams dump:\n");
1908 write(fd, buffer, strlen(buffer));
1909 snprintf(buffer, SIZE,
1910 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1911 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001912 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001913 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001914 write(fd, buffer, strlen(buffer));
1915 mStreams[i].dump(fd);
1916 }
1917
1918 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1919 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1920 write(fd, buffer, strlen(buffer));
1921
1922 snprintf(buffer, SIZE, "Registered effects:\n");
1923 write(fd, buffer, strlen(buffer));
1924 for (size_t i = 0; i < mEffects.size(); i++) {
1925 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1926 write(fd, buffer, strlen(buffer));
1927 mEffects.valueAt(i)->dump(fd);
1928 }
1929
Eric Laurent4d416952014-08-10 14:07:09 -07001930 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1931 write(fd, buffer, strlen(buffer));
1932 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1933 mAudioPatches[i]->dump(fd, 2, i);
1934 }
Eric Laurente552edb2014-03-10 17:42:56 -07001935
1936 return NO_ERROR;
1937}
1938
1939// This function checks for the parameters which can be offloaded.
1940// This can be enhanced depending on the capability of the DSP and policy
1941// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001942bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001943{
1944 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001945 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001946 offloadInfo.sample_rate, offloadInfo.channel_mask,
1947 offloadInfo.format,
1948 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1949 offloadInfo.has_video);
1950
1951 // Check if offload has been disabled
1952 char propValue[PROPERTY_VALUE_MAX];
1953 if (property_get("audio.offload.disable", propValue, "0")) {
1954 if (atoi(propValue) != 0) {
1955 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1956 return false;
1957 }
1958 }
1959
1960 // Check if stream type is music, then only allow offload as of now.
1961 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1962 {
1963 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1964 return false;
1965 }
1966
1967 //TODO: enable audio offloading with video when ready
1968 if (offloadInfo.has_video)
1969 {
1970 ALOGV("isOffloadSupported: has_video == true, returning false");
1971 return false;
1972 }
1973
1974 //If duration is less than minimum value defined in property, return false
1975 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1976 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1977 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1978 return false;
1979 }
1980 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1981 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1982 return false;
1983 }
1984
1985 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1986 // creating an offloaded track and tearing it down immediately after start when audioflinger
1987 // detects there is an active non offloadable effect.
1988 // FIXME: We should check the audio session here but we do not have it in this context.
1989 // This may prevent offloading in rare situations where effects are left active by apps
1990 // in the background.
1991 if (isNonOffloadableEffectEnabled()) {
1992 return false;
1993 }
1994
1995 // See if there is a profile to support this.
1996 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001997 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001998 offloadInfo.sample_rate,
1999 offloadInfo.format,
2000 offloadInfo.channel_mask,
2001 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002002 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2003 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002004}
2005
Eric Laurent6a94d692014-05-20 11:18:06 -07002006status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2007 audio_port_type_t type,
2008 unsigned int *num_ports,
2009 struct audio_port *ports,
2010 unsigned int *generation)
2011{
2012 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2013 generation == NULL) {
2014 return BAD_VALUE;
2015 }
2016 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2017 if (ports == NULL) {
2018 *num_ports = 0;
2019 }
2020
2021 size_t portsWritten = 0;
2022 size_t portsMax = *num_ports;
2023 *num_ports = 0;
2024 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2025 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2026 for (size_t i = 0;
2027 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2028 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2029 }
2030 *num_ports += mAvailableOutputDevices.size();
2031 }
2032 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2033 for (size_t i = 0;
2034 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2035 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2036 }
2037 *num_ports += mAvailableInputDevices.size();
2038 }
2039 }
2040 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2041 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2042 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2043 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2044 }
2045 *num_ports += mInputs.size();
2046 }
2047 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002048 size_t numOutputs = 0;
2049 for (size_t i = 0; i < mOutputs.size(); i++) {
2050 if (!mOutputs[i]->isDuplicated()) {
2051 numOutputs++;
2052 if (portsWritten < portsMax) {
2053 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2054 }
2055 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002056 }
Eric Laurent84c70242014-06-23 08:46:27 -07002057 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002058 }
2059 }
2060 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002061 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002062 return NO_ERROR;
2063}
2064
2065status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2066{
2067 return NO_ERROR;
2068}
2069
Eric Laurent1f2f2232014-06-02 12:01:23 -07002070sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002071 audio_port_handle_t id) const
2072{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002073 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002074 for (size_t i = 0; i < mOutputs.size(); i++) {
2075 outputDesc = mOutputs.valueAt(i);
2076 if (outputDesc->mId == id) {
2077 break;
2078 }
2079 }
2080 return outputDesc;
2081}
2082
Eric Laurent1f2f2232014-06-02 12:01:23 -07002083sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002084 audio_port_handle_t id) const
2085{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002086 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002087 for (size_t i = 0; i < mInputs.size(); i++) {
2088 inputDesc = mInputs.valueAt(i);
2089 if (inputDesc->mId == id) {
2090 break;
2091 }
2092 }
2093 return inputDesc;
2094}
2095
Eric Laurent1f2f2232014-06-02 12:01:23 -07002096sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2097 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002098{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002099 sp <HwModule> module;
2100
Eric Laurent6a94d692014-05-20 11:18:06 -07002101 for (size_t i = 0; i < mHwModules.size(); i++) {
2102 if (mHwModules[i]->mHandle == 0) {
2103 continue;
2104 }
2105 if (audio_is_output_device(device)) {
2106 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2107 {
2108 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2109 return mHwModules[i];
2110 }
2111 }
2112 } else {
2113 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2114 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2115 device & ~AUDIO_DEVICE_BIT_IN) {
2116 return mHwModules[i];
2117 }
2118 }
2119 }
2120 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002121 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002122}
2123
Eric Laurent1f2f2232014-06-02 12:01:23 -07002124sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002125{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002126 sp <HwModule> module;
2127
Eric Laurent1afeecb2014-05-14 08:52:28 -07002128 for (size_t i = 0; i < mHwModules.size(); i++)
2129 {
2130 if (strcmp(mHwModules[i]->mName, name) == 0) {
2131 return mHwModules[i];
2132 }
2133 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002134 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002135}
2136
Eric Laurentc2730ba2014-07-20 15:47:07 -07002137audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2138{
2139 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2140 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2141 return devices & mAvailableOutputDevices.types();
2142}
2143
2144audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2145{
2146 audio_module_handle_t primaryHandle =
2147 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2148 audio_devices_t devices = AUDIO_DEVICE_NONE;
2149 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2150 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2151 devices |= mAvailableInputDevices[i]->mDeviceType;
2152 }
2153 }
2154 return devices;
2155}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002156
Eric Laurent6a94d692014-05-20 11:18:06 -07002157status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2158 audio_patch_handle_t *handle,
2159 uid_t uid)
2160{
2161 ALOGV("createAudioPatch()");
2162
2163 if (handle == NULL || patch == NULL) {
2164 return BAD_VALUE;
2165 }
2166 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2167
Eric Laurent874c42872014-08-08 15:13:39 -07002168 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2169 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2170 return BAD_VALUE;
2171 }
2172 // only one source per audio patch supported for now
2173 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002174 return INVALID_OPERATION;
2175 }
Eric Laurent874c42872014-08-08 15:13:39 -07002176
2177 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002178 return INVALID_OPERATION;
2179 }
Eric Laurent874c42872014-08-08 15:13:39 -07002180 for (size_t i = 0; i < patch->num_sinks; i++) {
2181 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2182 return INVALID_OPERATION;
2183 }
2184 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002185
2186 sp<AudioPatch> patchDesc;
2187 ssize_t index = mAudioPatches.indexOfKey(*handle);
2188
Eric Laurent6a94d692014-05-20 11:18:06 -07002189 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2190 patch->sources[0].role,
2191 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002192#if LOG_NDEBUG == 0
2193 for (size_t i = 0; i < patch->num_sinks; i++) {
2194 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2195 patch->sinks[i].role,
2196 patch->sinks[i].type);
2197 }
2198#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002199
2200 if (index >= 0) {
2201 patchDesc = mAudioPatches.valueAt(index);
2202 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2203 mUidCached, patchDesc->mUid, uid);
2204 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2205 return INVALID_OPERATION;
2206 }
2207 } else {
2208 *handle = 0;
2209 }
2210
2211 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002212 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002213 if (outputDesc == NULL) {
2214 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2215 return BAD_VALUE;
2216 }
Eric Laurent84c70242014-06-23 08:46:27 -07002217 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2218 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002219 if (patchDesc != 0) {
2220 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2221 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2222 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2223 return BAD_VALUE;
2224 }
2225 }
Eric Laurent874c42872014-08-08 15:13:39 -07002226 DeviceVector devices;
2227 for (size_t i = 0; i < patch->num_sinks; i++) {
2228 // Only support mix to devices connection
2229 // TODO add support for mix to mix connection
2230 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2231 ALOGV("createAudioPatch() source mix but sink is not a device");
2232 return INVALID_OPERATION;
2233 }
2234 sp<DeviceDescriptor> devDesc =
2235 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2236 if (devDesc == 0) {
2237 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2238 return BAD_VALUE;
2239 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002240
Eric Laurent874c42872014-08-08 15:13:39 -07002241 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2242 patch->sources[0].sample_rate,
2243 NULL, // updatedSamplingRate
2244 patch->sources[0].format,
2245 patch->sources[0].channel_mask,
2246 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2247 ALOGV("createAudioPatch() profile not supported for device %08x",
2248 devDesc->mDeviceType);
2249 return INVALID_OPERATION;
2250 }
2251 devices.add(devDesc);
2252 }
2253 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002254 return INVALID_OPERATION;
2255 }
Eric Laurent874c42872014-08-08 15:13:39 -07002256
Eric Laurent6a94d692014-05-20 11:18:06 -07002257 // TODO: reconfigure output format and channels here
2258 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002259 devices.types(), outputDesc->mIoHandle);
2260 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002261 index = mAudioPatches.indexOfKey(*handle);
2262 if (index >= 0) {
2263 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2264 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2265 }
2266 patchDesc = mAudioPatches.valueAt(index);
2267 patchDesc->mUid = uid;
2268 ALOGV("createAudioPatch() success");
2269 } else {
2270 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2271 return INVALID_OPERATION;
2272 }
2273 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2274 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2275 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002276 // only one sink supported when connecting an input device to a mix
2277 if (patch->num_sinks > 1) {
2278 return INVALID_OPERATION;
2279 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002280 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002281 if (inputDesc == NULL) {
2282 return BAD_VALUE;
2283 }
2284 if (patchDesc != 0) {
2285 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2286 return BAD_VALUE;
2287 }
2288 }
2289 sp<DeviceDescriptor> devDesc =
2290 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2291 if (devDesc == 0) {
2292 return BAD_VALUE;
2293 }
2294
Eric Laurent84c70242014-06-23 08:46:27 -07002295 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002296 patch->sinks[0].sample_rate,
2297 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002298 patch->sinks[0].format,
2299 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002300 // FIXME for the parameter type,
2301 // and the NONE
2302 (audio_output_flags_t)
2303 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002304 return INVALID_OPERATION;
2305 }
2306 // TODO: reconfigure output format and channels here
2307 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002308 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002309 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002310 index = mAudioPatches.indexOfKey(*handle);
2311 if (index >= 0) {
2312 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2313 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2314 }
2315 patchDesc = mAudioPatches.valueAt(index);
2316 patchDesc->mUid = uid;
2317 ALOGV("createAudioPatch() success");
2318 } else {
2319 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2320 return INVALID_OPERATION;
2321 }
2322 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2323 // device to device connection
2324 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002325 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002326 return BAD_VALUE;
2327 }
2328 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002329 sp<DeviceDescriptor> srcDeviceDesc =
2330 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002331 if (srcDeviceDesc == 0) {
2332 return BAD_VALUE;
2333 }
Eric Laurent874c42872014-08-08 15:13:39 -07002334
Eric Laurent6a94d692014-05-20 11:18:06 -07002335 //update source and sink with our own data as the data passed in the patch may
2336 // be incomplete.
2337 struct audio_patch newPatch = *patch;
2338 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002339
Eric Laurent874c42872014-08-08 15:13:39 -07002340 for (size_t i = 0; i < patch->num_sinks; i++) {
2341 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2342 ALOGV("createAudioPatch() source device but one sink is not a device");
2343 return INVALID_OPERATION;
2344 }
2345
2346 sp<DeviceDescriptor> sinkDeviceDesc =
2347 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2348 if (sinkDeviceDesc == 0) {
2349 return BAD_VALUE;
2350 }
2351 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2352
2353 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2354 // only one sink supported when connected devices across HW modules
2355 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002356 return INVALID_OPERATION;
2357 }
Eric Laurent874c42872014-08-08 15:13:39 -07002358 SortedVector<audio_io_handle_t> outputs =
2359 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2360 mOutputs);
2361 // if the sink device is reachable via an opened output stream, request to go via
2362 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002363 audio_io_handle_t output = selectOutput(outputs,
2364 AUDIO_OUTPUT_FLAG_NONE,
2365 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002366 if (output != AUDIO_IO_HANDLE_NONE) {
2367 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2368 if (outputDesc->isDuplicated()) {
2369 return INVALID_OPERATION;
2370 }
2371 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2372 newPatch.num_sources = 2;
2373 }
Eric Laurent83b88082014-06-20 18:31:16 -07002374 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002375 }
2376 // TODO: check from routing capabilities in config file and other conflicting patches
2377
2378 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2379 if (index >= 0) {
2380 afPatchHandle = patchDesc->mAfPatchHandle;
2381 }
2382
2383 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2384 &afPatchHandle,
2385 0);
2386 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2387 status, afPatchHandle);
2388 if (status == NO_ERROR) {
2389 if (index < 0) {
2390 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2391 &newPatch, uid);
2392 addAudioPatch(patchDesc->mHandle, patchDesc);
2393 } else {
2394 patchDesc->mPatch = newPatch;
2395 }
2396 patchDesc->mAfPatchHandle = afPatchHandle;
2397 *handle = patchDesc->mHandle;
2398 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002399 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002400 } else {
2401 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2402 status);
2403 return INVALID_OPERATION;
2404 }
2405 } else {
2406 return BAD_VALUE;
2407 }
2408 } else {
2409 return BAD_VALUE;
2410 }
2411 return NO_ERROR;
2412}
2413
2414status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2415 uid_t uid)
2416{
2417 ALOGV("releaseAudioPatch() patch %d", handle);
2418
2419 ssize_t index = mAudioPatches.indexOfKey(handle);
2420
2421 if (index < 0) {
2422 return BAD_VALUE;
2423 }
2424 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2425 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2426 mUidCached, patchDesc->mUid, uid);
2427 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2428 return INVALID_OPERATION;
2429 }
2430
2431 struct audio_patch *patch = &patchDesc->mPatch;
2432 patchDesc->mUid = mUidCached;
2433 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002434 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002435 if (outputDesc == NULL) {
2436 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2437 return BAD_VALUE;
2438 }
2439
2440 setOutputDevice(outputDesc->mIoHandle,
2441 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2442 true,
2443 0,
2444 NULL);
2445 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2446 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002447 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002448 if (inputDesc == NULL) {
2449 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2450 return BAD_VALUE;
2451 }
2452 setInputDevice(inputDesc->mIoHandle,
2453 getNewInputDevice(inputDesc->mIoHandle),
2454 true,
2455 NULL);
2456 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2457 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2458 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2459 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2460 status, patchDesc->mAfPatchHandle);
2461 removeAudioPatch(patchDesc->mHandle);
2462 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002463 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002464 } else {
2465 return BAD_VALUE;
2466 }
2467 } else {
2468 return BAD_VALUE;
2469 }
2470 return NO_ERROR;
2471}
2472
2473status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2474 struct audio_patch *patches,
2475 unsigned int *generation)
2476{
2477 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2478 generation == NULL) {
2479 return BAD_VALUE;
2480 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002481 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002482 *num_patches, patches, mAudioPatches.size());
2483 if (patches == NULL) {
2484 *num_patches = 0;
2485 }
2486
2487 size_t patchesWritten = 0;
2488 size_t patchesMax = *num_patches;
2489 for (size_t i = 0;
2490 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2491 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2492 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002493 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002494 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2495 }
2496 *num_patches = mAudioPatches.size();
2497
2498 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002499 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002500 return NO_ERROR;
2501}
2502
Eric Laurente1715a42014-05-20 11:30:42 -07002503status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002504{
Eric Laurente1715a42014-05-20 11:30:42 -07002505 ALOGV("setAudioPortConfig()");
2506
2507 if (config == NULL) {
2508 return BAD_VALUE;
2509 }
2510 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2511 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002512 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2513 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002514 }
2515
Eric Laurenta121f902014-06-03 13:32:54 -07002516 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002517 if (config->type == AUDIO_PORT_TYPE_MIX) {
2518 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002519 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002520 if (outputDesc == NULL) {
2521 return BAD_VALUE;
2522 }
Eric Laurent84c70242014-06-23 08:46:27 -07002523 ALOG_ASSERT(!outputDesc->isDuplicated(),
2524 "setAudioPortConfig() called on duplicated output %d",
2525 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002526 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002527 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002528 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002529 if (inputDesc == NULL) {
2530 return BAD_VALUE;
2531 }
Eric Laurenta121f902014-06-03 13:32:54 -07002532 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002533 } else {
2534 return BAD_VALUE;
2535 }
2536 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2537 sp<DeviceDescriptor> deviceDesc;
2538 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2539 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2540 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2541 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2542 } else {
2543 return BAD_VALUE;
2544 }
2545 if (deviceDesc == NULL) {
2546 return BAD_VALUE;
2547 }
Eric Laurenta121f902014-06-03 13:32:54 -07002548 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002549 } else {
2550 return BAD_VALUE;
2551 }
2552
Eric Laurenta121f902014-06-03 13:32:54 -07002553 struct audio_port_config backupConfig;
2554 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2555 if (status == NO_ERROR) {
2556 struct audio_port_config newConfig;
2557 audioPortConfig->toAudioPortConfig(&newConfig, config);
2558 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002559 }
Eric Laurenta121f902014-06-03 13:32:54 -07002560 if (status != NO_ERROR) {
2561 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002562 }
Eric Laurente1715a42014-05-20 11:30:42 -07002563
2564 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002565}
2566
2567void AudioPolicyManager::clearAudioPatches(uid_t uid)
2568{
2569 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2570 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2571 if (patchDesc->mUid == uid) {
2572 // releaseAudioPatch() removes the patch from mAudioPatches
2573 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2574 i--;
2575 }
2576 }
2577 }
2578}
2579
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002580status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2581 audio_io_handle_t *ioHandle,
2582 audio_devices_t *device)
2583{
2584 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2585 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2586 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2587
2588 mSoundTriggerSessions.add(*session, *ioHandle);
2589
2590 return NO_ERROR;
2591}
2592
2593status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2594{
2595 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2596 if (index < 0) {
2597 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2598 return BAD_VALUE;
2599 }
2600
2601 mSoundTriggerSessions.removeItem(session);
2602 return NO_ERROR;
2603}
2604
Eric Laurent6a94d692014-05-20 11:18:06 -07002605status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2606 const sp<AudioPatch>& patch)
2607{
2608 ssize_t index = mAudioPatches.indexOfKey(handle);
2609
2610 if (index >= 0) {
2611 ALOGW("addAudioPatch() patch %d already in", handle);
2612 return ALREADY_EXISTS;
2613 }
2614 mAudioPatches.add(handle, patch);
2615 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2616 "sink handle %d",
2617 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2618 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2619 return NO_ERROR;
2620}
2621
2622status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2623{
2624 ssize_t index = mAudioPatches.indexOfKey(handle);
2625
2626 if (index < 0) {
2627 ALOGW("removeAudioPatch() patch %d not in", handle);
2628 return ALREADY_EXISTS;
2629 }
2630 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2631 mAudioPatches.valueAt(index)->mAfPatchHandle);
2632 mAudioPatches.removeItemsAt(index);
2633 return NO_ERROR;
2634}
2635
Eric Laurente552edb2014-03-10 17:42:56 -07002636// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002637// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002638// ----------------------------------------------------------------------------
2639
Eric Laurent3a4311c2014-03-17 12:00:47 -07002640uint32_t AudioPolicyManager::nextUniqueId()
2641{
2642 return android_atomic_inc(&mNextUniqueId);
2643}
2644
Eric Laurent6a94d692014-05-20 11:18:06 -07002645uint32_t AudioPolicyManager::nextAudioPortGeneration()
2646{
2647 return android_atomic_inc(&mAudioPortGeneration);
2648}
2649
Eric Laurente0720872014-03-11 09:30:41 -07002650AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002651 :
2652#ifdef AUDIO_POLICY_TEST
2653 Thread(false),
2654#endif //AUDIO_POLICY_TEST
2655 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002656 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002657 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2658 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002659 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002660 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Vineeta Srivastavaf2ab2192014-10-11 21:59:36 +00002661 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002662{
Eric Laurent6a94d692014-05-20 11:18:06 -07002663 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002664 mpClientInterface = clientInterface;
2665
Eric Laurent3b73df72014-03-11 09:06:29 -07002666 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2667 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002668 }
2669
Eric Laurent1afeecb2014-05-14 08:52:28 -07002670 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002671 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2672 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2673 ALOGE("could not load audio policy configuration file, setting defaults");
2674 defaultAudioPolicyConfig();
2675 }
2676 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002677 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002678
2679 // must be done after reading the policy
2680 initializeVolumeCurves();
2681
2682 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002683 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2684 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002685 for (size_t i = 0; i < mHwModules.size(); i++) {
2686 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2687 if (mHwModules[i]->mHandle == 0) {
2688 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2689 continue;
2690 }
2691 // open all output streams needed to access attached devices
2692 // except for direct output streams that are only opened when they are actually
2693 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002694 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002695 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2696 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002697 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002698
Eric Laurent3a4311c2014-03-17 12:00:47 -07002699 if (outProfile->mSupportedDevices.isEmpty()) {
2700 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2701 continue;
2702 }
2703
Eric Laurentd78f1532014-09-16 16:38:20 -07002704 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2705 continue;
2706 }
Eric Laurent83b88082014-06-20 18:31:16 -07002707 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2708 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2709 profileType = mDefaultOutputDevice->mDeviceType;
2710 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002711 // chose first device present in mSupportedDevices also part of
2712 // outputDeviceTypes
2713 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2714 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2715 if ((profileType & outputDeviceTypes) != 0) {
2716 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002717 }
Eric Laurente552edb2014-03-10 17:42:56 -07002718 }
2719 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002720 if ((profileType & outputDeviceTypes) == 0) {
2721 continue;
2722 }
2723 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2724
2725 outputDesc->mDevice = profileType;
2726 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2727 config.sample_rate = outputDesc->mSamplingRate;
2728 config.channel_mask = outputDesc->mChannelMask;
2729 config.format = outputDesc->mFormat;
2730 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2731 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2732 &output,
2733 &config,
2734 &outputDesc->mDevice,
2735 String8(""),
2736 &outputDesc->mLatency,
2737 outputDesc->mFlags);
2738
2739 if (status != NO_ERROR) {
2740 ALOGW("Cannot open output stream for device %08x on hw module %s",
2741 outputDesc->mDevice,
2742 mHwModules[i]->mName);
2743 } else {
2744 outputDesc->mSamplingRate = config.sample_rate;
2745 outputDesc->mChannelMask = config.channel_mask;
2746 outputDesc->mFormat = config.format;
2747
2748 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2749 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2750 ssize_t index =
2751 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2752 // give a valid ID to an attached device once confirmed it is reachable
2753 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2754 mAvailableOutputDevices[index]->mId = nextUniqueId();
2755 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2756 }
2757 }
2758 if (mPrimaryOutput == 0 &&
2759 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2760 mPrimaryOutput = output;
2761 }
2762 addOutput(output, outputDesc);
2763 setOutputDevice(output,
2764 outputDesc->mDevice,
2765 true);
2766 }
Eric Laurente552edb2014-03-10 17:42:56 -07002767 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002768 // open input streams needed to access attached devices to validate
2769 // mAvailableInputDevices list
2770 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2771 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002772 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002773
Eric Laurent3a4311c2014-03-17 12:00:47 -07002774 if (inProfile->mSupportedDevices.isEmpty()) {
2775 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2776 continue;
2777 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002778 // chose first device present in mSupportedDevices also part of
2779 // inputDeviceTypes
2780 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2781 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2782 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2783 if (profileType & inputDeviceTypes) {
2784 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002785 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002786 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002787 if ((profileType & inputDeviceTypes) == 0) {
2788 continue;
2789 }
2790 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2791
2792 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2793 inputDesc->mDevice = profileType;
2794
2795 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2796 config.sample_rate = inputDesc->mSamplingRate;
2797 config.channel_mask = inputDesc->mChannelMask;
2798 config.format = inputDesc->mFormat;
2799 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2800 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2801 &input,
2802 &config,
2803 &inputDesc->mDevice,
2804 String8(""),
2805 AUDIO_SOURCE_MIC,
2806 AUDIO_INPUT_FLAG_NONE);
2807
2808 if (status == NO_ERROR) {
2809 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2810 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2811 ssize_t index =
2812 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2813 // give a valid ID to an attached device once confirmed it is reachable
2814 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2815 mAvailableInputDevices[index]->mId = nextUniqueId();
2816 mAvailableInputDevices[index]->mModule = mHwModules[i];
2817 }
2818 }
2819 mpClientInterface->closeInput(input);
2820 } else {
2821 ALOGW("Cannot open input stream for device %08x on hw module %s",
2822 inputDesc->mDevice,
2823 mHwModules[i]->mName);
2824 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002825 }
2826 }
2827 // make sure all attached devices have been allocated a unique ID
2828 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2829 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002830 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002831 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2832 continue;
2833 }
2834 i++;
2835 }
2836 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2837 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002838 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002839 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2840 continue;
2841 }
2842 i++;
2843 }
2844 // make sure default device is reachable
2845 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002846 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002847 }
Eric Laurente552edb2014-03-10 17:42:56 -07002848
2849 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2850
2851 updateDevicesAndOutputs();
2852
2853#ifdef AUDIO_POLICY_TEST
2854 if (mPrimaryOutput != 0) {
2855 AudioParameter outputCmd = AudioParameter();
2856 outputCmd.addInt(String8("set_id"), 0);
2857 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2858
2859 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2860 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002861 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2862 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002863 mTestLatencyMs = 0;
2864 mCurOutput = 0;
2865 mDirectOutput = false;
2866 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2867 mTestOutputs[i] = 0;
2868 }
2869
2870 const size_t SIZE = 256;
2871 char buffer[SIZE];
2872 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2873 run(buffer, ANDROID_PRIORITY_AUDIO);
2874 }
2875#endif //AUDIO_POLICY_TEST
2876}
2877
Eric Laurente0720872014-03-11 09:30:41 -07002878AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002879{
2880#ifdef AUDIO_POLICY_TEST
2881 exit();
2882#endif //AUDIO_POLICY_TEST
2883 for (size_t i = 0; i < mOutputs.size(); i++) {
2884 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002885 }
2886 for (size_t i = 0; i < mInputs.size(); i++) {
2887 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002888 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002889 mAvailableOutputDevices.clear();
2890 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002891 mOutputs.clear();
2892 mInputs.clear();
2893 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002894}
2895
Eric Laurente0720872014-03-11 09:30:41 -07002896status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002897{
2898 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2899}
2900
2901#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002902bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002903{
2904 ALOGV("entering threadLoop()");
2905 while (!exitPending())
2906 {
2907 String8 command;
2908 int valueInt;
2909 String8 value;
2910
2911 Mutex::Autolock _l(mLock);
2912 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2913
2914 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2915 AudioParameter param = AudioParameter(command);
2916
2917 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2918 valueInt != 0) {
2919 ALOGV("Test command %s received", command.string());
2920 String8 target;
2921 if (param.get(String8("target"), target) != NO_ERROR) {
2922 target = "Manager";
2923 }
2924 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2925 param.remove(String8("test_cmd_policy_output"));
2926 mCurOutput = valueInt;
2927 }
2928 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2929 param.remove(String8("test_cmd_policy_direct"));
2930 if (value == "false") {
2931 mDirectOutput = false;
2932 } else if (value == "true") {
2933 mDirectOutput = true;
2934 }
2935 }
2936 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2937 param.remove(String8("test_cmd_policy_input"));
2938 mTestInput = valueInt;
2939 }
2940
2941 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2942 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002943 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002944 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002945 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002946 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002947 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002948 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002949 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002950 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002951 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002952 if (target == "Manager") {
2953 mTestFormat = format;
2954 } else if (mTestOutputs[mCurOutput] != 0) {
2955 AudioParameter outputParam = AudioParameter();
2956 outputParam.addInt(String8("format"), format);
2957 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2958 }
2959 }
2960 }
2961 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2962 param.remove(String8("test_cmd_policy_channels"));
2963 int channels = 0;
2964
2965 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002966 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002967 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002968 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002969 }
2970 if (channels != 0) {
2971 if (target == "Manager") {
2972 mTestChannels = channels;
2973 } else if (mTestOutputs[mCurOutput] != 0) {
2974 AudioParameter outputParam = AudioParameter();
2975 outputParam.addInt(String8("channels"), channels);
2976 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2977 }
2978 }
2979 }
2980 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2981 param.remove(String8("test_cmd_policy_sampleRate"));
2982 if (valueInt >= 0 && valueInt <= 96000) {
2983 int samplingRate = valueInt;
2984 if (target == "Manager") {
2985 mTestSamplingRate = samplingRate;
2986 } else if (mTestOutputs[mCurOutput] != 0) {
2987 AudioParameter outputParam = AudioParameter();
2988 outputParam.addInt(String8("sampling_rate"), samplingRate);
2989 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2990 }
2991 }
2992 }
2993
2994 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2995 param.remove(String8("test_cmd_policy_reopen"));
2996
Eric Laurent1f2f2232014-06-02 12:01:23 -07002997 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002998 mpClientInterface->closeOutput(mPrimaryOutput);
2999
3000 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3001
Eric Laurente552edb2014-03-10 17:42:56 -07003002 mOutputs.removeItem(mPrimaryOutput);
3003
Eric Laurent1f2f2232014-06-02 12:01:23 -07003004 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003005 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003006 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3007 config.sample_rate = outputDesc->mSamplingRate;
3008 config.channel_mask = outputDesc->mChannelMask;
3009 config.format = outputDesc->mFormat;
3010 status_t status = mpClientInterface->openOutput(moduleHandle,
3011 &mPrimaryOutput,
3012 &config,
3013 &outputDesc->mDevice,
3014 String8(""),
3015 &outputDesc->mLatency,
3016 outputDesc->mFlags);
3017 if (status != NO_ERROR) {
3018 ALOGE("Failed to reopen hardware output stream, "
3019 "samplingRate: %d, format %d, channels %d",
3020 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003021 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003022 outputDesc->mSamplingRate = config.sample_rate;
3023 outputDesc->mChannelMask = config.channel_mask;
3024 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003025 AudioParameter outputCmd = AudioParameter();
3026 outputCmd.addInt(String8("set_id"), 0);
3027 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3028 addOutput(mPrimaryOutput, outputDesc);
3029 }
3030 }
3031
3032
3033 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3034 }
3035 }
3036 return false;
3037}
3038
Eric Laurente0720872014-03-11 09:30:41 -07003039void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003040{
3041 {
3042 AutoMutex _l(mLock);
3043 requestExit();
3044 mWaitWorkCV.signal();
3045 }
3046 requestExitAndWait();
3047}
3048
Eric Laurente0720872014-03-11 09:30:41 -07003049int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003050{
3051 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3052 if (output == mTestOutputs[i]) return i;
3053 }
3054 return 0;
3055}
3056#endif //AUDIO_POLICY_TEST
3057
3058// ---
3059
Eric Laurent1f2f2232014-06-02 12:01:23 -07003060void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003061{
Eric Laurent1c333e22014-05-20 10:48:17 -07003062 outputDesc->mIoHandle = output;
3063 outputDesc->mId = nextUniqueId();
3064 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003065 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003066}
3067
Eric Laurent1f2f2232014-06-02 12:01:23 -07003068void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003069{
Eric Laurent1c333e22014-05-20 10:48:17 -07003070 inputDesc->mIoHandle = input;
3071 inputDesc->mId = nextUniqueId();
3072 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003073 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003074}
Eric Laurente552edb2014-03-10 17:42:56 -07003075
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003076void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3077 const String8 address /*in*/,
3078 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3079 // look for a match on the given address on the addresses of the outputs:
3080 // find the address by finding the patch that maps to this output
3081 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3082 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3083 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3084 if (patchIdx >= 0) {
3085 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3086 const int numSinks = patchDesc->mPatch.num_sinks;
3087 for (ssize_t j=0; j < numSinks; j++) {
3088 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3089 const char* patchAddr =
3090 patchDesc->mPatch.sinks[j].ext.device.address;
3091 if (strncmp(patchAddr,
3092 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003093 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003094 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3095 outputs.add(desc->mIoHandle);
3096 break;
3097 }
3098 }
3099 }
3100 }
3101}
3102
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003103status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003104 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003105 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003106 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003107{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003108 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003109 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003110 // erase all current sample rates, formats and channel masks
3111 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003112
Eric Laurent3b73df72014-03-11 09:06:29 -07003113 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003114 // first list already open outputs that can be routed to this device
3115 for (size_t i = 0; i < mOutputs.size(); i++) {
3116 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003117 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003118 if (!deviceDistinguishesOnAddress(device)) {
3119 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3120 outputs.add(mOutputs.keyAt(i));
3121 } else {
3122 ALOGV(" checking address match due to device 0x%x", device);
3123 findIoHandlesByAddress(desc, address, outputs);
3124 }
Eric Laurente552edb2014-03-10 17:42:56 -07003125 }
3126 }
3127 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003128 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003129 for (size_t i = 0; i < mHwModules.size(); i++)
3130 {
3131 if (mHwModules[i]->mHandle == 0) {
3132 continue;
3133 }
3134 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3135 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003136 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003137 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003138 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3139 }
3140 }
3141 }
3142
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003143 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3144
Eric Laurente552edb2014-03-10 17:42:56 -07003145 if (profiles.isEmpty() && outputs.isEmpty()) {
3146 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3147 return BAD_VALUE;
3148 }
3149
3150 // open outputs for matching profiles if needed. Direct outputs are also opened to
3151 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3152 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003153 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003154
3155 // nothing to do if one output is already opened for this profile
3156 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003157 for (j = 0; j < outputs.size(); j++) {
3158 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003159 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003160 // matching profile: save the sample rates, format and channel masks supported
3161 // by the profile in our device descriptor
3162 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003163 break;
3164 }
3165 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003166 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003167 continue;
3168 }
3169
Eric Laurent83b88082014-06-20 18:31:16 -07003170 ALOGV("opening output for device %08x with params %s profile %p",
3171 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003172 desc = new AudioOutputDescriptor(profile);
3173 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003174 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3175 config.sample_rate = desc->mSamplingRate;
3176 config.channel_mask = desc->mChannelMask;
3177 config.format = desc->mFormat;
3178 config.offload_info.sample_rate = desc->mSamplingRate;
3179 config.offload_info.channel_mask = desc->mChannelMask;
3180 config.offload_info.format = desc->mFormat;
3181 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3182 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3183 &output,
3184 &config,
3185 &desc->mDevice,
3186 address,
3187 &desc->mLatency,
3188 desc->mFlags);
3189 if (status == NO_ERROR) {
3190 desc->mSamplingRate = config.sample_rate;
3191 desc->mChannelMask = config.channel_mask;
3192 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003193
Eric Laurentd4692962014-05-05 18:13:44 -07003194 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003195 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003196 char *param = audio_device_address_to_parameter(device, address);
3197 mpClientInterface->setParameters(output, String8(param));
3198 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003199 }
3200
Eric Laurentd4692962014-05-05 18:13:44 -07003201 // Here is where we step through and resolve any "dynamic" fields
3202 String8 reply;
3203 char *value;
3204 if (profile->mSamplingRates[0] == 0) {
3205 reply = mpClientInterface->getParameters(output,
3206 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003207 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003208 reply.string());
3209 value = strpbrk((char *)reply.string(), "=");
3210 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003211 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003212 }
Eric Laurentd4692962014-05-05 18:13:44 -07003213 }
3214 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3215 reply = mpClientInterface->getParameters(output,
3216 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003217 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003218 reply.string());
3219 value = strpbrk((char *)reply.string(), "=");
3220 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003221 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003222 }
Eric Laurentd4692962014-05-05 18:13:44 -07003223 }
3224 if (profile->mChannelMasks[0] == 0) {
3225 reply = mpClientInterface->getParameters(output,
3226 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003227 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003228 reply.string());
3229 value = strpbrk((char *)reply.string(), "=");
3230 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003231 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003232 }
Eric Laurentd4692962014-05-05 18:13:44 -07003233 }
3234 if (((profile->mSamplingRates[0] == 0) &&
3235 (profile->mSamplingRates.size() < 2)) ||
3236 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3237 (profile->mFormats.size() < 2)) ||
3238 ((profile->mChannelMasks[0] == 0) &&
3239 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003240 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003241 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003242 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003243 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3244 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003245 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003246 config.sample_rate = profile->pickSamplingRate();
3247 config.channel_mask = profile->pickChannelMask();
3248 config.format = profile->pickFormat();
3249 config.offload_info.sample_rate = config.sample_rate;
3250 config.offload_info.channel_mask = config.channel_mask;
3251 config.offload_info.format = config.format;
3252 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3253 &output,
3254 &config,
3255 &desc->mDevice,
3256 address,
3257 &desc->mLatency,
3258 desc->mFlags);
3259 if (status == NO_ERROR) {
3260 desc->mSamplingRate = config.sample_rate;
3261 desc->mChannelMask = config.channel_mask;
3262 desc->mFormat = config.format;
3263 } else {
3264 output = AUDIO_IO_HANDLE_NONE;
3265 }
Eric Laurentd4692962014-05-05 18:13:44 -07003266 }
3267
Eric Laurentcf2c0212014-07-25 16:20:43 -07003268 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003269 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003270 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003271 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003272
Eric Laurentd4692962014-05-05 18:13:44 -07003273 // set initial stream volume for device
3274 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003275
Eric Laurentd4692962014-05-05 18:13:44 -07003276 //TODO: configure audio effect output stage here
3277
3278 // open a duplicating output thread for the new output and the primary output
3279 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3280 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003281 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003282 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003283 sp<AudioOutputDescriptor> dupOutputDesc =
3284 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003285 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3286 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3287 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3288 dupOutputDesc->mFormat = desc->mFormat;
3289 dupOutputDesc->mChannelMask = desc->mChannelMask;
3290 dupOutputDesc->mLatency = desc->mLatency;
3291 addOutput(duplicatedOutput, dupOutputDesc);
3292 applyStreamVolumes(duplicatedOutput, device, 0, true);
3293 } else {
3294 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3295 mPrimaryOutput, output);
3296 mpClientInterface->closeOutput(output);
3297 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003298 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003299 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003300 }
Eric Laurente552edb2014-03-10 17:42:56 -07003301 }
3302 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003303 } else {
3304 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003305 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003306 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003307 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003308 profiles.removeAt(profile_index);
3309 profile_index--;
3310 } else {
3311 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003312 devDesc->importAudioPort(profile);
3313
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003314 if (deviceDistinguishesOnAddress(device)) {
3315 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3316 device, address.string());
3317 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3318 NULL/*patch handle*/, address.string());
3319 }
Eric Laurente552edb2014-03-10 17:42:56 -07003320 ALOGV("checkOutputsForDevice(): adding output %d", output);
3321 }
3322 }
3323
3324 if (profiles.isEmpty()) {
3325 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3326 return BAD_VALUE;
3327 }
Eric Laurentd4692962014-05-05 18:13:44 -07003328 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003329 // check if one opened output is not needed any more after disconnecting one device
3330 for (size_t i = 0; i < mOutputs.size(); i++) {
3331 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003332 if (!desc->isDuplicated()) {
3333 if (!(desc->mProfile->mSupportedDevices.types()
3334 & mAvailableOutputDevices.types())) {
3335 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3336 mOutputs.keyAt(i));
3337 outputs.add(mOutputs.keyAt(i));
3338 } else if (deviceDistinguishesOnAddress(device) &&
3339 // exact match on device
3340 (desc->mProfile->mSupportedDevices.types() == device)) {
3341 findIoHandlesByAddress(desc, address, outputs);
3342 }
Eric Laurente552edb2014-03-10 17:42:56 -07003343 }
3344 }
Eric Laurentd4692962014-05-05 18:13:44 -07003345 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003346 for (size_t i = 0; i < mHwModules.size(); i++)
3347 {
3348 if (mHwModules[i]->mHandle == 0) {
3349 continue;
3350 }
3351 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3352 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003353 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003354 if (profile->mSupportedDevices.types() & device) {
3355 ALOGV("checkOutputsForDevice(): "
3356 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003357 if (profile->mSamplingRates[0] == 0) {
3358 profile->mSamplingRates.clear();
3359 profile->mSamplingRates.add(0);
3360 }
3361 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3362 profile->mFormats.clear();
3363 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3364 }
3365 if (profile->mChannelMasks[0] == 0) {
3366 profile->mChannelMasks.clear();
3367 profile->mChannelMasks.add(0);
3368 }
3369 }
3370 }
3371 }
3372 }
3373 return NO_ERROR;
3374}
3375
Eric Laurentd4692962014-05-05 18:13:44 -07003376status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3377 audio_policy_dev_state_t state,
3378 SortedVector<audio_io_handle_t>& inputs,
3379 const String8 address)
3380{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003381 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003382 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3383 // first list already open inputs that can be routed to this device
3384 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3385 desc = mInputs.valueAt(input_index);
3386 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3387 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3388 inputs.add(mInputs.keyAt(input_index));
3389 }
3390 }
3391
3392 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003393 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003394 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3395 {
3396 if (mHwModules[module_idx]->mHandle == 0) {
3397 continue;
3398 }
3399 for (size_t profile_index = 0;
3400 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3401 profile_index++)
3402 {
3403 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3404 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003405 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003406 profile_index, module_idx);
3407 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3408 }
3409 }
3410 }
3411
3412 if (profiles.isEmpty() && inputs.isEmpty()) {
3413 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3414 return BAD_VALUE;
3415 }
3416
3417 // open inputs for matching profiles if needed. Direct inputs are also opened to
3418 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3419 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3420
Eric Laurent1c333e22014-05-20 10:48:17 -07003421 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003422 // nothing to do if one input is already opened for this profile
3423 size_t input_index;
3424 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3425 desc = mInputs.valueAt(input_index);
3426 if (desc->mProfile == profile) {
3427 break;
3428 }
3429 }
3430 if (input_index != mInputs.size()) {
3431 continue;
3432 }
3433
3434 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3435 desc = new AudioInputDescriptor(profile);
3436 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003437 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3438 config.sample_rate = desc->mSamplingRate;
3439 config.channel_mask = desc->mChannelMask;
3440 config.format = desc->mFormat;
3441 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3442 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3443 &input,
3444 &config,
3445 &desc->mDevice,
3446 address,
3447 AUDIO_SOURCE_MIC,
3448 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003449
Eric Laurentcf2c0212014-07-25 16:20:43 -07003450 if (status == NO_ERROR) {
3451 desc->mSamplingRate = config.sample_rate;
3452 desc->mChannelMask = config.channel_mask;
3453 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003454
Eric Laurentd4692962014-05-05 18:13:44 -07003455 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003456 char *param = audio_device_address_to_parameter(device, address);
3457 mpClientInterface->setParameters(input, String8(param));
3458 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003459 }
3460
3461 // Here is where we step through and resolve any "dynamic" fields
3462 String8 reply;
3463 char *value;
3464 if (profile->mSamplingRates[0] == 0) {
3465 reply = mpClientInterface->getParameters(input,
3466 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3467 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3468 reply.string());
3469 value = strpbrk((char *)reply.string(), "=");
3470 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003471 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003472 }
3473 }
3474 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3475 reply = mpClientInterface->getParameters(input,
3476 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3477 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3478 value = strpbrk((char *)reply.string(), "=");
3479 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003480 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003481 }
3482 }
3483 if (profile->mChannelMasks[0] == 0) {
3484 reply = mpClientInterface->getParameters(input,
3485 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3486 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3487 reply.string());
3488 value = strpbrk((char *)reply.string(), "=");
3489 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003490 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003491 }
3492 }
3493 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3494 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3495 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3496 ALOGW("checkInputsForDevice() direct input missing param");
3497 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003498 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003499 }
3500
3501 if (input != 0) {
3502 addInput(input, desc);
3503 }
3504 } // endif input != 0
3505
Eric Laurentcf2c0212014-07-25 16:20:43 -07003506 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003507 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003508 profiles.removeAt(profile_index);
3509 profile_index--;
3510 } else {
3511 inputs.add(input);
3512 ALOGV("checkInputsForDevice(): adding input %d", input);
3513 }
3514 } // end scan profiles
3515
3516 if (profiles.isEmpty()) {
3517 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3518 return BAD_VALUE;
3519 }
3520 } else {
3521 // Disconnect
3522 // check if one opened input is not needed any more after disconnecting one device
3523 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3524 desc = mInputs.valueAt(input_index);
3525 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3526 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3527 mInputs.keyAt(input_index));
3528 inputs.add(mInputs.keyAt(input_index));
3529 }
3530 }
3531 // Clear any profiles associated with the disconnected device.
3532 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3533 if (mHwModules[module_index]->mHandle == 0) {
3534 continue;
3535 }
3536 for (size_t profile_index = 0;
3537 profile_index < mHwModules[module_index]->mInputProfiles.size();
3538 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003539 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003540 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003541 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003542 profile_index, module_index);
3543 if (profile->mSamplingRates[0] == 0) {
3544 profile->mSamplingRates.clear();
3545 profile->mSamplingRates.add(0);
3546 }
3547 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3548 profile->mFormats.clear();
3549 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3550 }
3551 if (profile->mChannelMasks[0] == 0) {
3552 profile->mChannelMasks.clear();
3553 profile->mChannelMasks.add(0);
3554 }
3555 }
3556 }
3557 }
3558 } // end disconnect
3559
3560 return NO_ERROR;
3561}
3562
3563
Eric Laurente0720872014-03-11 09:30:41 -07003564void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003565{
3566 ALOGV("closeOutput(%d)", output);
3567
Eric Laurent1f2f2232014-06-02 12:01:23 -07003568 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003569 if (outputDesc == NULL) {
3570 ALOGW("closeOutput() unknown output %d", output);
3571 return;
3572 }
3573
3574 // look for duplicated outputs connected to the output being removed.
3575 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003576 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003577 if (dupOutputDesc->isDuplicated() &&
3578 (dupOutputDesc->mOutput1 == outputDesc ||
3579 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003580 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003581 if (dupOutputDesc->mOutput1 == outputDesc) {
3582 outputDesc2 = dupOutputDesc->mOutput2;
3583 } else {
3584 outputDesc2 = dupOutputDesc->mOutput1;
3585 }
3586 // As all active tracks on duplicated output will be deleted,
3587 // and as they were also referenced on the other output, the reference
3588 // count for their stream type must be adjusted accordingly on
3589 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003590 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003591 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003592 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003593 }
3594 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3595 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3596
3597 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003598 mOutputs.removeItem(duplicatedOutput);
3599 }
3600 }
3601
Eric Laurent05b90f82014-08-27 15:32:29 -07003602 nextAudioPortGeneration();
3603
3604 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3605 if (index >= 0) {
3606 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3607 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3608 mAudioPatches.removeItemsAt(index);
3609 mpClientInterface->onAudioPatchListUpdate();
3610 }
3611
Eric Laurente552edb2014-03-10 17:42:56 -07003612 AudioParameter param;
3613 param.add(String8("closing"), String8("true"));
3614 mpClientInterface->setParameters(output, param.toString());
3615
3616 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003617 mOutputs.removeItem(output);
3618 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003619}
3620
3621void AudioPolicyManager::closeInput(audio_io_handle_t input)
3622{
3623 ALOGV("closeInput(%d)", input);
3624
3625 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3626 if (inputDesc == NULL) {
3627 ALOGW("closeInput() unknown input %d", input);
3628 return;
3629 }
3630
Eric Laurent6a94d692014-05-20 11:18:06 -07003631 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003632
3633 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3634 if (index >= 0) {
3635 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3636 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3637 mAudioPatches.removeItemsAt(index);
3638 mpClientInterface->onAudioPatchListUpdate();
3639 }
3640
3641 mpClientInterface->closeInput(input);
3642 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003643}
3644
Eric Laurente0720872014-03-11 09:30:41 -07003645SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003646 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003647{
3648 SortedVector<audio_io_handle_t> outputs;
3649
3650 ALOGVV("getOutputsForDevice() device %04x", device);
3651 for (size_t i = 0; i < openOutputs.size(); i++) {
3652 ALOGVV("output %d isDuplicated=%d device=%04x",
3653 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3654 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3655 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3656 outputs.add(openOutputs.keyAt(i));
3657 }
3658 }
3659 return outputs;
3660}
3661
Eric Laurente0720872014-03-11 09:30:41 -07003662bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003663 SortedVector<audio_io_handle_t>& outputs2)
3664{
3665 if (outputs1.size() != outputs2.size()) {
3666 return false;
3667 }
3668 for (size_t i = 0; i < outputs1.size(); i++) {
3669 if (outputs1[i] != outputs2[i]) {
3670 return false;
3671 }
3672 }
3673 return true;
3674}
3675
Eric Laurente0720872014-03-11 09:30:41 -07003676void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003677{
3678 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3679 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3680 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3681 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3682
3683 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3684 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3685 strategy, srcOutputs[0], dstOutputs[0]);
3686 // mute strategy while moving tracks from one output to another
3687 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003688 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003689 if (desc->isStrategyActive(strategy)) {
3690 setStrategyMute(strategy, true, srcOutputs[i]);
3691 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3692 }
3693 }
3694
3695 // Move effects associated to this strategy from previous output to new output
3696 if (strategy == STRATEGY_MEDIA) {
3697 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3698 SortedVector<audio_io_handle_t> moved;
3699 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003700 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3701 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3702 effectDesc->mIo != fxOutput) {
3703 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003704 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3705 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003706 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003707 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003708 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003709 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003710 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003711 }
3712 }
3713 }
3714 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003715 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3716 if (getStrategy((audio_stream_type_t)i) == strategy) {
3717 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003718 }
3719 }
3720 }
3721}
3722
Eric Laurente0720872014-03-11 09:30:41 -07003723void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003724{
Jon Eklund966095e2014-09-09 15:39:49 -05003725 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3726 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003727 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003728 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3729 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003730 checkOutputForStrategy(STRATEGY_SONIFICATION);
3731 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3732 checkOutputForStrategy(STRATEGY_MEDIA);
3733 checkOutputForStrategy(STRATEGY_DTMF);
3734}
3735
Eric Laurente0720872014-03-11 09:30:41 -07003736audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003737{
Eric Laurente552edb2014-03-10 17:42:56 -07003738 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003739 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003740 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3741 return mOutputs.keyAt(i);
3742 }
3743 }
3744
3745 return 0;
3746}
3747
Eric Laurente0720872014-03-11 09:30:41 -07003748void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003749{
Eric Laurente552edb2014-03-10 17:42:56 -07003750 audio_io_handle_t a2dpOutput = getA2dpOutput();
3751 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003752 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003753 return;
3754 }
3755
Eric Laurent3a4311c2014-03-17 12:00:47 -07003756 bool isScoConnected =
3757 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003758 // suspend A2DP output if:
3759 // (NOT already suspended) &&
3760 // ((SCO device is connected &&
3761 // (forced usage for communication || for record is SCO))) ||
3762 // (phone state is ringing || in call)
3763 //
3764 // restore A2DP output if:
3765 // (Already suspended) &&
3766 // ((SCO device is NOT connected ||
3767 // (forced usage NOT for communication && NOT for record is SCO))) &&
3768 // (phone state is NOT ringing && NOT in call)
3769 //
3770 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003771 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003772 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3773 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3774 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3775 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003776
3777 mpClientInterface->restoreOutput(a2dpOutput);
3778 mA2dpSuspended = false;
3779 }
3780 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003781 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003782 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3783 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3784 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3785 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003786
3787 mpClientInterface->suspendOutput(a2dpOutput);
3788 mA2dpSuspended = true;
3789 }
3790 }
3791}
3792
Eric Laurent1c333e22014-05-20 10:48:17 -07003793audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003794{
3795 audio_devices_t device = AUDIO_DEVICE_NONE;
3796
Eric Laurent1f2f2232014-06-02 12:01:23 -07003797 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003798
3799 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3800 if (index >= 0) {
3801 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3802 if (patchDesc->mUid != mUidCached) {
3803 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3804 outputDesc->device(), outputDesc->mPatchHandle);
3805 return outputDesc->device();
3806 }
3807 }
3808
Eric Laurente552edb2014-03-10 17:42:56 -07003809 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003810 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003811 // use device for strategy enforced audible
3812 // 2: we are in call or the strategy phone is active on the output:
3813 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003814 // 3: the strategy for enforced audible is active but not enforced on the output:
3815 // use the device for strategy enforced audible
3816 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003817 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003818 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003819 // use device for strategy "respectful" sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003820 // 6: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003821 // use device for strategy media
Jon Eklund966095e2014-09-09 15:39:49 -05003822 // 7: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003823 // use device for strategy DTMF
Jon Eklund966095e2014-09-09 15:39:49 -05003824 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3825 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003826 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3827 } else if (isInCall() ||
3828 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3829 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003830 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3831 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003832 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3833 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3834 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3835 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3836 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3837 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3838 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3839 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3840 }
3841
Eric Laurent1c333e22014-05-20 10:48:17 -07003842 ALOGV("getNewOutputDevice() selected device %x", device);
3843 return device;
3844}
3845
3846audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3847{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003848 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003849
3850 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3851 if (index >= 0) {
3852 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3853 if (patchDesc->mUid != mUidCached) {
3854 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3855 inputDesc->mDevice, inputDesc->mPatchHandle);
3856 return inputDesc->mDevice;
3857 }
3858 }
3859
Eric Laurent1c333e22014-05-20 10:48:17 -07003860 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3861
3862 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003863 return device;
3864}
3865
Eric Laurente0720872014-03-11 09:30:41 -07003866uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003867 return (uint32_t)getStrategy(stream);
3868}
3869
Eric Laurente0720872014-03-11 09:30:41 -07003870audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003871 // By checking the range of stream before calling getStrategy, we avoid
3872 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3873 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003874 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003875 return AUDIO_DEVICE_NONE;
3876 }
3877 audio_devices_t devices;
3878 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3879 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3880 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3881 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003882 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003883 if (outputDesc->isStrategyActive(strategy)) {
3884 devices = outputDesc->device();
3885 break;
3886 }
Eric Laurente552edb2014-03-10 17:42:56 -07003887 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003888
3889 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
3890 and doesn't really need to.*/
3891 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
3892 devices |= AUDIO_DEVICE_OUT_SPEAKER;
3893 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3894 }
3895
Eric Laurente552edb2014-03-10 17:42:56 -07003896 return devices;
3897}
3898
Eric Laurente0720872014-03-11 09:30:41 -07003899AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003900 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003901 // stream to strategy mapping
3902 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003903 case AUDIO_STREAM_VOICE_CALL:
3904 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003905 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003906 case AUDIO_STREAM_RING:
3907 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003908 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003909 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003910 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003911 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003912 return STRATEGY_DTMF;
3913 default:
3914 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003915 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003916 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3917 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003918 case AUDIO_STREAM_TTS:
3919 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003920 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003921 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003922 return STRATEGY_ENFORCED_AUDIBLE;
3923 }
3924}
3925
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003926uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3927 // flags to strategy mapping
3928 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3929 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3930 }
3931
3932 // usage to strategy mapping
3933 switch (attr->usage) {
3934 case AUDIO_USAGE_MEDIA:
3935 case AUDIO_USAGE_GAME:
3936 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3937 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3938 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3939 return (uint32_t) STRATEGY_MEDIA;
3940
3941 case AUDIO_USAGE_VOICE_COMMUNICATION:
3942 return (uint32_t) STRATEGY_PHONE;
3943
3944 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3945 return (uint32_t) STRATEGY_DTMF;
3946
3947 case AUDIO_USAGE_ALARM:
3948 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3949 return (uint32_t) STRATEGY_SONIFICATION;
3950
3951 case AUDIO_USAGE_NOTIFICATION:
3952 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3953 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3954 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3955 case AUDIO_USAGE_NOTIFICATION_EVENT:
3956 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3957
3958 case AUDIO_USAGE_UNKNOWN:
3959 default:
3960 return (uint32_t) STRATEGY_MEDIA;
3961 }
3962}
3963
Eric Laurente0720872014-03-11 09:30:41 -07003964void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003965 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003966 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003967 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3968 updateDevicesAndOutputs();
3969 break;
3970 default:
3971 break;
3972 }
3973}
3974
Eric Laurente0720872014-03-11 09:30:41 -07003975audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003976 bool fromCache)
3977{
3978 uint32_t device = AUDIO_DEVICE_NONE;
3979
3980 if (fromCache) {
3981 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3982 strategy, mDeviceForStrategy[strategy]);
3983 return mDeviceForStrategy[strategy];
3984 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003985 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003986 switch (strategy) {
3987
3988 case STRATEGY_SONIFICATION_RESPECTFUL:
3989 if (isInCall()) {
3990 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003991 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003992 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3993 // while media is playing on a remote device, use the the sonification behavior.
3994 // Note that we test this usecase before testing if media is playing because
3995 // the isStreamActive() method only informs about the activity of a stream, not
3996 // if it's for local playback. Note also that we use the same delay between both tests
3997 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05003998 //user "safe" speaker if available instead of normal speaker to avoid triggering
3999 //other acoustic safety mechanisms for notification
4000 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4001 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004002 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004003 // while media is playing (or has recently played), use the same device
4004 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4005 } else {
4006 // when media is not playing anymore, fall back on the sonification behavior
4007 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004008 //user "safe" speaker if available instead of normal speaker to avoid triggering
4009 //other acoustic safety mechanisms for notification
4010 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4011 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004012 }
4013
4014 break;
4015
4016 case STRATEGY_DTMF:
4017 if (!isInCall()) {
4018 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4019 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4020 break;
4021 }
4022 // when in call, DTMF and PHONE strategies follow the same rules
4023 // FALL THROUGH
4024
4025 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004026 // Force use of only devices on primary output if:
4027 // - in call AND
4028 // - cannot route from voice call RX OR
4029 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4030 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4031 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4032 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4033 if (((mAvailableInputDevices.types() &
4034 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4035 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004036 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004037 AUDIO_DEVICE_API_VERSION_3_0))) {
4038 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4039 }
4040 }
Eric Laurente552edb2014-03-10 17:42:56 -07004041 // for phone strategy, we first consider the forced use and then the available devices by order
4042 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004043 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4044 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004045 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004046 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004047 if (device) break;
4048 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004049 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004050 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004051 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004052 if (device) break;
4053 // if SCO device is requested but no SCO device is available, fall back to default case
4054 // FALL THROUGH
4055
4056 default: // FORCE_NONE
4057 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004058 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004059 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004060 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004061 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004062 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004063 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004064 if (device) break;
4065 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004066 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004067 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004069 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004070 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4071 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004072 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004073 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004074 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004075 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004076 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004077 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004078 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004079 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004080 if (device) break;
4081 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004082 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004083 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004084 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004085 if (device == AUDIO_DEVICE_NONE) {
4086 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4087 }
4088 break;
4089
Eric Laurent3b73df72014-03-11 09:06:29 -07004090 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004091 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4092 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004093 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004094 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004095 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004096 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004097 if (device) break;
4098 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004099 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004100 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004101 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004102 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004103 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004104 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004105 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004106 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004107 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004108 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004109 if (device) break;
4110 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004111 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4112 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004113 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004114 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004115 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004116 if (device == AUDIO_DEVICE_NONE) {
4117 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4118 }
4119 break;
4120 }
4121 break;
4122
4123 case STRATEGY_SONIFICATION:
4124
4125 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4126 // handleIncallSonification().
4127 if (isInCall()) {
4128 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4129 break;
4130 }
4131 // FALL THROUGH
4132
4133 case STRATEGY_ENFORCED_AUDIBLE:
4134 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4135 // except:
4136 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4137 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4138
4139 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004140 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004141 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004142 if (device == AUDIO_DEVICE_NONE) {
4143 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4144 }
4145 }
4146 // The second device used for sonification is the same as the device used by media strategy
4147 // FALL THROUGH
4148
4149 case STRATEGY_MEDIA: {
4150 uint32_t device2 = AUDIO_DEVICE_NONE;
4151 if (strategy != STRATEGY_SONIFICATION) {
4152 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004153 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004154 }
4155 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004156 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004157 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004158 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004159 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004160 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004161 }
4162 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004163 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004164 }
4165 }
Hochi Huang327cb702014-09-21 09:47:31 +08004166 if ((device2 == AUDIO_DEVICE_NONE) &&
4167 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4168 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4169 }
Eric Laurente552edb2014-03-10 17:42:56 -07004170 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004171 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004172 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004173 if ((device2 == AUDIO_DEVICE_NONE)) {
4174 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4175 }
Eric Laurente552edb2014-03-10 17:42:56 -07004176 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004177 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004178 }
4179 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004180 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004181 }
4182 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004183 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004184 }
4185 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004186 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004187 }
4188 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4189 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004190 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004191 }
4192 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004193 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004194 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004195 }
4196 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004197 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004198 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004199 int device3 = AUDIO_DEVICE_NONE;
4200 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004201 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004202 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4203 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004204 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004205 }
Eric Laurente552edb2014-03-10 17:42:56 -07004206
Jungshik Jang839e4f32014-06-26 17:23:40 +09004207 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004208 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4209 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4210 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004211
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004212 // If hdmi system audio mode is on, remove speaker out of output list.
4213 if ((strategy == STRATEGY_MEDIA) &&
4214 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4215 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4216 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4217 }
4218
Eric Laurente552edb2014-03-10 17:42:56 -07004219 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004220 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004221 if (device == AUDIO_DEVICE_NONE) {
4222 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4223 }
4224 } break;
4225
4226 default:
4227 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4228 break;
4229 }
4230
4231 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4232 return device;
4233}
4234
Eric Laurente0720872014-03-11 09:30:41 -07004235void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004236{
4237 for (int i = 0; i < NUM_STRATEGIES; i++) {
4238 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4239 }
4240 mPreviousOutputs = mOutputs;
4241}
4242
Eric Laurent1f2f2232014-06-02 12:01:23 -07004243uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004244 audio_devices_t prevDevice,
4245 uint32_t delayMs)
4246{
4247 // mute/unmute strategies using an incompatible device combination
4248 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4249 // if unmuting, unmute only after the specified delay
4250 if (outputDesc->isDuplicated()) {
4251 return 0;
4252 }
4253
4254 uint32_t muteWaitMs = 0;
4255 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004256 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004257
4258 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4259 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004260 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004261 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;
Hochi Huang327cb702014-09-21 09:47:31 +08004680 case AUDIO_SOURCE_FM_TUNER:
4681 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
4682 device = AUDIO_DEVICE_IN_FM_TUNER;
4683 }
4684 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004685 default:
4686 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4687 break;
4688 }
4689 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4690 return device;
4691}
4692
Eric Laurente0720872014-03-11 09:30:41 -07004693bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004694{
4695 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4696 device &= ~AUDIO_DEVICE_BIT_IN;
4697 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4698 return true;
4699 }
4700 return false;
4701}
4702
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004703bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4704 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4705}
4706
Eric Laurente0720872014-03-11 09:30:41 -07004707audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004708{
4709 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004710 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004711 if ((input_descriptor->mRefCount > 0)
4712 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4713 return mInputs.keyAt(i);
4714 }
4715 }
4716 return 0;
4717}
4718
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004719uint32_t AudioPolicyManager::activeInputsCount() const
4720{
4721 uint32_t count = 0;
4722 for (size_t i = 0; i < mInputs.size(); i++) {
4723 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4724 if (desc->mRefCount > 0) {
4725 return count++;
4726 }
4727 }
4728 return count;
4729}
4730
Eric Laurente552edb2014-03-10 17:42:56 -07004731
Eric Laurente0720872014-03-11 09:30:41 -07004732audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004733{
4734 if (device == AUDIO_DEVICE_NONE) {
4735 // this happens when forcing a route update and no track is active on an output.
4736 // In this case the returned category is not important.
4737 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004738 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004739 // Multiple device selection is either:
4740 // - speaker + one other device: give priority to speaker in this case.
4741 // - one A2DP device + another device: happens with duplicated output. In this case
4742 // retain the device on the A2DP output as the other must not correspond to an active
4743 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004744 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004745 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4746 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004747 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4748 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4749 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4750 device = AUDIO_DEVICE_OUT_AUX_LINE;
4751 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4752 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004753 } else {
4754 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4755 }
4756 }
4757
Jon Eklund11c9fb12014-06-23 14:47:03 -05004758 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4759 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4760 device = AUDIO_DEVICE_OUT_SPEAKER;
4761
Eric Laurent3b73df72014-03-11 09:06:29 -07004762 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004763 "getDeviceForVolume() invalid device combination: %08x",
4764 device);
4765
4766 return device;
4767}
4768
Eric Laurente0720872014-03-11 09:30:41 -07004769AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004770{
4771 switch(getDeviceForVolume(device)) {
4772 case AUDIO_DEVICE_OUT_EARPIECE:
4773 return DEVICE_CATEGORY_EARPIECE;
4774 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4775 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4776 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4777 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4778 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4779 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4780 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004781 case AUDIO_DEVICE_OUT_LINE:
4782 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4783 /*USB? Remote submix?*/
4784 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004785 case AUDIO_DEVICE_OUT_SPEAKER:
4786 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4787 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004788 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4789 case AUDIO_DEVICE_OUT_USB_DEVICE:
4790 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4791 default:
4792 return DEVICE_CATEGORY_SPEAKER;
4793 }
4794}
4795
Eric Laurente0720872014-03-11 09:30:41 -07004796float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004797 int indexInUi)
4798{
4799 device_category deviceCategory = getDeviceCategory(device);
4800 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4801
4802 // the volume index in the UI is relative to the min and max volume indices for this stream type
4803 int nbSteps = 1 + curve[VOLMAX].mIndex -
4804 curve[VOLMIN].mIndex;
4805 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4806 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4807
4808 // find what part of the curve this index volume belongs to, or if it's out of bounds
4809 int segment = 0;
4810 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4811 return 0.0f;
4812 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4813 segment = 0;
4814 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4815 segment = 1;
4816 } else if (volIdx <= curve[VOLMAX].mIndex) {
4817 segment = 2;
4818 } else { // out of bounds
4819 return 1.0f;
4820 }
4821
4822 // linear interpolation in the attenuation table in dB
4823 float decibels = curve[segment].mDBAttenuation +
4824 ((float)(volIdx - curve[segment].mIndex)) *
4825 ( (curve[segment+1].mDBAttenuation -
4826 curve[segment].mDBAttenuation) /
4827 ((float)(curve[segment+1].mIndex -
4828 curve[segment].mIndex)) );
4829
4830 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4831
4832 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4833 curve[segment].mIndex, volIdx,
4834 curve[segment+1].mIndex,
4835 curve[segment].mDBAttenuation,
4836 decibels,
4837 curve[segment+1].mDBAttenuation,
4838 amplification);
4839
4840 return amplification;
4841}
4842
Eric Laurente0720872014-03-11 09:30:41 -07004843const AudioPolicyManager::VolumeCurvePoint
4844 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004845 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4846};
4847
Eric Laurente0720872014-03-11 09:30:41 -07004848const AudioPolicyManager::VolumeCurvePoint
4849 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004850 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4851};
4852
Eric Laurente0720872014-03-11 09:30:41 -07004853const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004854 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4855 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4856};
4857
4858const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004859 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004860 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4861};
4862
Eric Laurente0720872014-03-11 09:30:41 -07004863const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004864 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004865 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004866};
4867
4868const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004869 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004870 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4871};
4872
Eric Laurente0720872014-03-11 09:30:41 -07004873const AudioPolicyManager::VolumeCurvePoint
4874 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004875 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4876};
4877
4878// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4879// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4880// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4881// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4882
Eric Laurente0720872014-03-11 09:30:41 -07004883const AudioPolicyManager::VolumeCurvePoint
4884 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004885 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4886};
4887
Eric Laurente0720872014-03-11 09:30:41 -07004888const AudioPolicyManager::VolumeCurvePoint
4889 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004890 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4891};
4892
Eric Laurente0720872014-03-11 09:30:41 -07004893const AudioPolicyManager::VolumeCurvePoint
4894 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004895 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4896};
4897
Eric Laurente0720872014-03-11 09:30:41 -07004898const AudioPolicyManager::VolumeCurvePoint
4899 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004900 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4901};
4902
Eric Laurente0720872014-03-11 09:30:41 -07004903const AudioPolicyManager::VolumeCurvePoint
4904 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004905 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4906};
4907
Eric Laurente0720872014-03-11 09:30:41 -07004908const AudioPolicyManager::VolumeCurvePoint
4909 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4910 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004911 { // AUDIO_STREAM_VOICE_CALL
4912 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4913 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004914 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4915 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004916 },
4917 { // AUDIO_STREAM_SYSTEM
4918 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4919 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004920 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4921 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004922 },
4923 { // AUDIO_STREAM_RING
4924 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4925 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004926 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4927 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004928 },
4929 { // AUDIO_STREAM_MUSIC
4930 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4931 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004932 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4933 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004934 },
4935 { // AUDIO_STREAM_ALARM
4936 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4937 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004938 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4939 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004940 },
4941 { // AUDIO_STREAM_NOTIFICATION
4942 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4943 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004944 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4945 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004946 },
4947 { // AUDIO_STREAM_BLUETOOTH_SCO
4948 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4949 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004950 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4951 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004952 },
4953 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4954 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4955 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004956 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4957 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004958 },
4959 { // AUDIO_STREAM_DTMF
4960 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4961 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004962 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4963 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004964 },
4965 { // AUDIO_STREAM_TTS
4966 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4967 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004968 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4969 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004970 },
4971};
4972
Eric Laurente0720872014-03-11 09:30:41 -07004973void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004974{
4975 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4976 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4977 mStreams[i].mVolumeCurve[j] =
4978 sVolumeProfiles[i][j];
4979 }
4980 }
4981
4982 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4983 if (mSpeakerDrcEnabled) {
4984 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4985 sDefaultSystemVolumeCurveDrc;
4986 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4987 sSpeakerSonificationVolumeCurveDrc;
4988 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4989 sSpeakerSonificationVolumeCurveDrc;
4990 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4991 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004992 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4993 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004994 }
4995}
4996
Eric Laurente0720872014-03-11 09:30:41 -07004997float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004998 int index,
4999 audio_io_handle_t output,
5000 audio_devices_t device)
5001{
5002 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005003 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005004 StreamDescriptor &streamDesc = mStreams[stream];
5005
5006 if (device == AUDIO_DEVICE_NONE) {
5007 device = outputDesc->device();
5008 }
5009
Eric Laurente552edb2014-03-10 17:42:56 -07005010 volume = volIndexToAmpl(device, streamDesc, index);
5011
5012 // if a headset is connected, apply the following rules to ring tones and notifications
5013 // to avoid sound level bursts in user's ears:
5014 // - always attenuate ring tones and notifications volume by 6dB
5015 // - if music is playing, always limit the volume to current music volume,
5016 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005017 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005018 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5019 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5020 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5021 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5022 ((stream_strategy == STRATEGY_SONIFICATION)
5023 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005024 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005025 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005026 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005027 streamDesc.mCanBeMuted) {
5028 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5029 // when the phone is ringing we must consider that music could have been paused just before
5030 // by the music application and behave as if music was active if the last music track was
5031 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005032 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005033 mLimitRingtoneVolume) {
5034 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005035 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5036 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005037 output,
5038 musicDevice);
5039 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5040 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5041 if (volume > minVol) {
5042 volume = minVol;
5043 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5044 }
5045 }
5046 }
5047
5048 return volume;
5049}
5050
Eric Laurente0720872014-03-11 09:30:41 -07005051status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005052 int index,
5053 audio_io_handle_t output,
5054 audio_devices_t device,
5055 int delayMs,
5056 bool force)
5057{
5058
5059 // do not change actual stream volume if the stream is muted
5060 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5061 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5062 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5063 return NO_ERROR;
5064 }
5065
5066 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005067 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5068 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5069 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5070 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005071 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005072 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005073 return INVALID_OPERATION;
5074 }
5075
5076 float volume = computeVolume(stream, index, output, device);
5077 // We actually change the volume if:
5078 // - the float value returned by computeVolume() changed
5079 // - the force flag is set
5080 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5081 force) {
5082 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5083 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5084 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5085 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005086 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5087 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005088 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005089 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005090 }
5091
Eric Laurent3b73df72014-03-11 09:06:29 -07005092 if (stream == AUDIO_STREAM_VOICE_CALL ||
5093 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005094 float voiceVolume;
5095 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005096 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005097 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5098 } else {
5099 voiceVolume = 1.0;
5100 }
5101
5102 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5103 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5104 mLastVoiceVolume = voiceVolume;
5105 }
5106 }
5107
5108 return NO_ERROR;
5109}
5110
Eric Laurente0720872014-03-11 09:30:41 -07005111void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005112 audio_devices_t device,
5113 int delayMs,
5114 bool force)
5115{
5116 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5117
Eric Laurent3b73df72014-03-11 09:06:29 -07005118 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5119 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005120 mStreams[stream].getVolumeIndex(device),
5121 output,
5122 device,
5123 delayMs,
5124 force);
5125 }
5126}
5127
Eric Laurente0720872014-03-11 09:30:41 -07005128void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005129 bool on,
5130 audio_io_handle_t output,
5131 int delayMs,
5132 audio_devices_t device)
5133{
5134 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005135 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5136 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5137 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005138 }
5139 }
5140}
5141
Eric Laurente0720872014-03-11 09:30:41 -07005142void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005143 bool on,
5144 audio_io_handle_t output,
5145 int delayMs,
5146 audio_devices_t device)
5147{
5148 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005149 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005150 if (device == AUDIO_DEVICE_NONE) {
5151 device = outputDesc->device();
5152 }
5153
5154 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5155 stream, on, output, outputDesc->mMuteCount[stream], device);
5156
5157 if (on) {
5158 if (outputDesc->mMuteCount[stream] == 0) {
5159 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005160 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5161 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005162 checkAndSetVolume(stream, 0, output, device, delayMs);
5163 }
5164 }
5165 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5166 outputDesc->mMuteCount[stream]++;
5167 } else {
5168 if (outputDesc->mMuteCount[stream] == 0) {
5169 ALOGV("setStreamMute() unmuting non muted stream!");
5170 return;
5171 }
5172 if (--outputDesc->mMuteCount[stream] == 0) {
5173 checkAndSetVolume(stream,
5174 streamDesc.getVolumeIndex(device),
5175 output,
5176 device,
5177 delayMs);
5178 }
5179 }
5180}
5181
Eric Laurente0720872014-03-11 09:30:41 -07005182void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005183 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005184{
5185 // if the stream pertains to sonification strategy and we are in call we must
5186 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5187 // in the device used for phone strategy and play the tone if the selected device does not
5188 // interfere with the device used for phone strategy
5189 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5190 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005191 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005192 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5193 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005194 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005195 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5196 stream, starting, outputDesc->mDevice, stateChange);
5197 if (outputDesc->mRefCount[stream]) {
5198 int muteCount = 1;
5199 if (stateChange) {
5200 muteCount = outputDesc->mRefCount[stream];
5201 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005202 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005203 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5204 for (int i = 0; i < muteCount; i++) {
5205 setStreamMute(stream, starting, mPrimaryOutput);
5206 }
5207 } else {
5208 ALOGV("handleIncallSonification() high visibility");
5209 if (outputDesc->device() &
5210 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5211 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5212 for (int i = 0; i < muteCount; i++) {
5213 setStreamMute(stream, starting, mPrimaryOutput);
5214 }
5215 }
5216 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005217 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5218 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005219 } else {
5220 mpClientInterface->stopTone();
5221 }
5222 }
5223 }
5224 }
5225}
5226
Eric Laurente0720872014-03-11 09:30:41 -07005227bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005228{
5229 return isStateInCall(mPhoneState);
5230}
5231
Eric Laurente0720872014-03-11 09:30:41 -07005232bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005233 return ((state == AUDIO_MODE_IN_CALL) ||
5234 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005235}
5236
Eric Laurente0720872014-03-11 09:30:41 -07005237uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005238{
5239 return MAX_EFFECTS_CPU_LOAD;
5240}
5241
Eric Laurente0720872014-03-11 09:30:41 -07005242uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005243{
5244 return MAX_EFFECTS_MEMORY;
5245}
5246
Eric Laurent6a94d692014-05-20 11:18:06 -07005247
Eric Laurente552edb2014-03-10 17:42:56 -07005248// --- AudioOutputDescriptor class implementation
5249
Eric Laurente0720872014-03-11 09:30:41 -07005250AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005251 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005252 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005253 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005254 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5255{
5256 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005257 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005258 mRefCount[i] = 0;
5259 mCurVolume[i] = -1.0;
5260 mMuteCount[i] = 0;
5261 mStopTime[i] = 0;
5262 }
5263 for (int i = 0; i < NUM_STRATEGIES; i++) {
5264 mStrategyMutedByDevice[i] = false;
5265 }
5266 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005267 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005268 mSamplingRate = profile->pickSamplingRate();
5269 mFormat = profile->pickFormat();
5270 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005271 if (profile->mGains.size() > 0) {
5272 profile->mGains[0]->getDefaultConfig(&mGain);
5273 }
Eric Laurente552edb2014-03-10 17:42:56 -07005274 }
5275}
5276
Eric Laurente0720872014-03-11 09:30:41 -07005277audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005278{
5279 if (isDuplicated()) {
5280 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5281 } else {
5282 return mDevice;
5283 }
5284}
5285
Eric Laurente0720872014-03-11 09:30:41 -07005286uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005287{
5288 if (isDuplicated()) {
5289 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5290 } else {
5291 return mLatency;
5292 }
5293}
5294
Eric Laurente0720872014-03-11 09:30:41 -07005295bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005296 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005297{
5298 if (isDuplicated()) {
5299 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5300 } else if (outputDesc->isDuplicated()){
5301 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5302 } else {
5303 return (mProfile->mModule == outputDesc->mProfile->mModule);
5304 }
5305}
5306
Eric Laurente0720872014-03-11 09:30:41 -07005307void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005308 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005309{
5310 // forward usage count change to attached outputs
5311 if (isDuplicated()) {
5312 mOutput1->changeRefCount(stream, delta);
5313 mOutput2->changeRefCount(stream, delta);
5314 }
5315 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005316 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5317 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005318 mRefCount[stream] = 0;
5319 return;
5320 }
5321 mRefCount[stream] += delta;
5322 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5323}
5324
Eric Laurente0720872014-03-11 09:30:41 -07005325audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005326{
5327 if (isDuplicated()) {
5328 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5329 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005330 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005331 }
5332}
5333
Eric Laurente0720872014-03-11 09:30:41 -07005334bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005335{
5336 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5337}
5338
Eric Laurente0720872014-03-11 09:30:41 -07005339bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005340 uint32_t inPastMs,
5341 nsecs_t sysTime) const
5342{
5343 if ((sysTime == 0) && (inPastMs != 0)) {
5344 sysTime = systemTime();
5345 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005346 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5347 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005348 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005349 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005350 return true;
5351 }
5352 }
5353 return false;
5354}
5355
Eric Laurente0720872014-03-11 09:30:41 -07005356bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005357 uint32_t inPastMs,
5358 nsecs_t sysTime) const
5359{
5360 if (mRefCount[stream] != 0) {
5361 return true;
5362 }
5363 if (inPastMs == 0) {
5364 return false;
5365 }
5366 if (sysTime == 0) {
5367 sysTime = systemTime();
5368 }
5369 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5370 return true;
5371 }
5372 return false;
5373}
5374
Eric Laurent1c333e22014-05-20 10:48:17 -07005375void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005376 struct audio_port_config *dstConfig,
5377 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005378{
Eric Laurent84c70242014-06-23 08:46:27 -07005379 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5380
Eric Laurent1f2f2232014-06-02 12:01:23 -07005381 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5382 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5383 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005384 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005385 }
5386 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5387
Eric Laurent6a94d692014-05-20 11:18:06 -07005388 dstConfig->id = mId;
5389 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5390 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005391 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5392 dstConfig->ext.mix.handle = mIoHandle;
5393 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005394}
5395
5396void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5397 struct audio_port *port) const
5398{
Eric Laurent84c70242014-06-23 08:46:27 -07005399 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005400 mProfile->toAudioPort(port);
5401 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005402 toAudioPortConfig(&port->active_config);
5403 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005404 port->ext.mix.handle = mIoHandle;
5405 port->ext.mix.latency_class =
5406 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5407}
Eric Laurente552edb2014-03-10 17:42:56 -07005408
Eric Laurente0720872014-03-11 09:30:41 -07005409status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005410{
5411 const size_t SIZE = 256;
5412 char buffer[SIZE];
5413 String8 result;
5414
Eric Laurent4d416952014-08-10 14:07:09 -07005415 snprintf(buffer, SIZE, " ID: %d\n", mId);
5416 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005417 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5418 result.append(buffer);
5419 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5420 result.append(buffer);
5421 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5422 result.append(buffer);
5423 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5424 result.append(buffer);
5425 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5426 result.append(buffer);
5427 snprintf(buffer, SIZE, " Devices %08x\n", device());
5428 result.append(buffer);
5429 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5430 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005431 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5432 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5433 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005434 result.append(buffer);
5435 }
5436 write(fd, result.string(), result.size());
5437
5438 return NO_ERROR;
5439}
5440
5441// --- AudioInputDescriptor class implementation
5442
Eric Laurent1c333e22014-05-20 10:48:17 -07005443AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005444 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005445 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005446 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005447{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005448 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005449 mSamplingRate = profile->pickSamplingRate();
5450 mFormat = profile->pickFormat();
5451 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005452 if (profile->mGains.size() > 0) {
5453 profile->mGains[0]->getDefaultConfig(&mGain);
5454 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005455 }
Eric Laurente552edb2014-03-10 17:42:56 -07005456}
5457
Eric Laurent1c333e22014-05-20 10:48:17 -07005458void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005459 struct audio_port_config *dstConfig,
5460 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005461{
Eric Laurent84c70242014-06-23 08:46:27 -07005462 ALOG_ASSERT(mProfile != 0,
5463 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005464 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5465 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5466 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005467 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005468 }
5469
5470 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5471
Eric Laurent6a94d692014-05-20 11:18:06 -07005472 dstConfig->id = mId;
5473 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5474 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005475 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5476 dstConfig->ext.mix.handle = mIoHandle;
5477 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005478}
5479
5480void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5481 struct audio_port *port) const
5482{
Eric Laurent84c70242014-06-23 08:46:27 -07005483 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5484
Eric Laurent1c333e22014-05-20 10:48:17 -07005485 mProfile->toAudioPort(port);
5486 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005487 toAudioPortConfig(&port->active_config);
5488 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005489 port->ext.mix.handle = mIoHandle;
5490 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5491}
5492
Eric Laurente0720872014-03-11 09:30:41 -07005493status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005494{
5495 const size_t SIZE = 256;
5496 char buffer[SIZE];
5497 String8 result;
5498
Eric Laurent4d416952014-08-10 14:07:09 -07005499 snprintf(buffer, SIZE, " ID: %d\n", mId);
5500 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005501 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5502 result.append(buffer);
5503 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5504 result.append(buffer);
5505 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5506 result.append(buffer);
5507 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5508 result.append(buffer);
5509 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5510 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005511 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5512 result.append(buffer);
5513
Eric Laurente552edb2014-03-10 17:42:56 -07005514 write(fd, result.string(), result.size());
5515
5516 return NO_ERROR;
5517}
5518
5519// --- StreamDescriptor class implementation
5520
Eric Laurente0720872014-03-11 09:30:41 -07005521AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005522 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5523{
5524 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5525}
5526
Eric Laurente0720872014-03-11 09:30:41 -07005527int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005528{
Eric Laurente0720872014-03-11 09:30:41 -07005529 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005530 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5531 if (mIndexCur.indexOfKey(device) < 0) {
5532 device = AUDIO_DEVICE_OUT_DEFAULT;
5533 }
5534 return mIndexCur.valueFor(device);
5535}
5536
Eric Laurente0720872014-03-11 09:30:41 -07005537void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005538{
5539 const size_t SIZE = 256;
5540 char buffer[SIZE];
5541 String8 result;
5542
5543 snprintf(buffer, SIZE, "%s %02d %02d ",
5544 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5545 result.append(buffer);
5546 for (size_t i = 0; i < mIndexCur.size(); i++) {
5547 snprintf(buffer, SIZE, "%04x : %02d, ",
5548 mIndexCur.keyAt(i),
5549 mIndexCur.valueAt(i));
5550 result.append(buffer);
5551 }
5552 result.append("\n");
5553
5554 write(fd, result.string(), result.size());
5555}
5556
5557// --- EffectDescriptor class implementation
5558
Eric Laurente0720872014-03-11 09:30:41 -07005559status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005560{
5561 const size_t SIZE = 256;
5562 char buffer[SIZE];
5563 String8 result;
5564
5565 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5566 result.append(buffer);
5567 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5568 result.append(buffer);
5569 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5570 result.append(buffer);
5571 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5572 result.append(buffer);
5573 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5574 result.append(buffer);
5575 write(fd, result.string(), result.size());
5576
5577 return NO_ERROR;
5578}
5579
Eric Laurent1c333e22014-05-20 10:48:17 -07005580// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005581
Eric Laurente0720872014-03-11 09:30:41 -07005582AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005583 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5584 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005585{
5586}
5587
Eric Laurente0720872014-03-11 09:30:41 -07005588AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005589{
5590 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005591 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005592 }
5593 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005594 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005595 }
5596 free((void *)mName);
5597}
5598
Eric Laurent1afeecb2014-05-14 08:52:28 -07005599status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5600{
5601 cnode *node = root->first_child;
5602
5603 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5604
5605 while (node) {
5606 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5607 profile->loadSamplingRates((char *)node->value);
5608 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5609 profile->loadFormats((char *)node->value);
5610 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5611 profile->loadInChannels((char *)node->value);
5612 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5613 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5614 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005615 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5616 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005617 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5618 profile->loadGains(node);
5619 }
5620 node = node->next;
5621 }
5622 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5623 "loadInput() invalid supported devices");
5624 ALOGW_IF(profile->mChannelMasks.size() == 0,
5625 "loadInput() invalid supported channel masks");
5626 ALOGW_IF(profile->mSamplingRates.size() == 0,
5627 "loadInput() invalid supported sampling rates");
5628 ALOGW_IF(profile->mFormats.size() == 0,
5629 "loadInput() invalid supported formats");
5630 if (!profile->mSupportedDevices.isEmpty() &&
5631 (profile->mChannelMasks.size() != 0) &&
5632 (profile->mSamplingRates.size() != 0) &&
5633 (profile->mFormats.size() != 0)) {
5634
5635 ALOGV("loadInput() adding input Supported Devices %04x",
5636 profile->mSupportedDevices.types());
5637
5638 mInputProfiles.add(profile);
5639 return NO_ERROR;
5640 } else {
5641 return BAD_VALUE;
5642 }
5643}
5644
5645status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5646{
5647 cnode *node = root->first_child;
5648
5649 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5650
5651 while (node) {
5652 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5653 profile->loadSamplingRates((char *)node->value);
5654 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5655 profile->loadFormats((char *)node->value);
5656 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5657 profile->loadOutChannels((char *)node->value);
5658 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5659 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5660 mDeclaredDevices);
5661 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005662 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005663 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5664 profile->loadGains(node);
5665 }
5666 node = node->next;
5667 }
5668 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5669 "loadOutput() invalid supported devices");
5670 ALOGW_IF(profile->mChannelMasks.size() == 0,
5671 "loadOutput() invalid supported channel masks");
5672 ALOGW_IF(profile->mSamplingRates.size() == 0,
5673 "loadOutput() invalid supported sampling rates");
5674 ALOGW_IF(profile->mFormats.size() == 0,
5675 "loadOutput() invalid supported formats");
5676 if (!profile->mSupportedDevices.isEmpty() &&
5677 (profile->mChannelMasks.size() != 0) &&
5678 (profile->mSamplingRates.size() != 0) &&
5679 (profile->mFormats.size() != 0)) {
5680
5681 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5682 profile->mSupportedDevices.types(), profile->mFlags);
5683
5684 mOutputProfiles.add(profile);
5685 return NO_ERROR;
5686 } else {
5687 return BAD_VALUE;
5688 }
5689}
5690
5691status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5692{
5693 cnode *node = root->first_child;
5694
5695 audio_devices_t type = AUDIO_DEVICE_NONE;
5696 while (node) {
5697 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5698 type = parseDeviceNames((char *)node->value);
5699 break;
5700 }
5701 node = node->next;
5702 }
5703 if (type == AUDIO_DEVICE_NONE ||
5704 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5705 ALOGW("loadDevice() bad type %08x", type);
5706 return BAD_VALUE;
5707 }
5708 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5709 deviceDesc->mModule = this;
5710
5711 node = root->first_child;
5712 while (node) {
5713 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5714 deviceDesc->mAddress = String8((char *)node->value);
5715 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5716 if (audio_is_input_device(type)) {
5717 deviceDesc->loadInChannels((char *)node->value);
5718 } else {
5719 deviceDesc->loadOutChannels((char *)node->value);
5720 }
5721 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5722 deviceDesc->loadGains(node);
5723 }
5724 node = node->next;
5725 }
5726
5727 ALOGV("loadDevice() adding device name %s type %08x address %s",
5728 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5729
5730 mDeclaredDevices.add(deviceDesc);
5731
5732 return NO_ERROR;
5733}
5734
Eric Laurente0720872014-03-11 09:30:41 -07005735void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005736{
5737 const size_t SIZE = 256;
5738 char buffer[SIZE];
5739 String8 result;
5740
5741 snprintf(buffer, SIZE, " - name: %s\n", mName);
5742 result.append(buffer);
5743 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5744 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005745 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5746 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005747 write(fd, result.string(), result.size());
5748 if (mOutputProfiles.size()) {
5749 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5750 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005751 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005752 write(fd, buffer, strlen(buffer));
5753 mOutputProfiles[i]->dump(fd);
5754 }
5755 }
5756 if (mInputProfiles.size()) {
5757 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5758 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005759 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005760 write(fd, buffer, strlen(buffer));
5761 mInputProfiles[i]->dump(fd);
5762 }
5763 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005764 if (mDeclaredDevices.size()) {
5765 write(fd, " - devices:\n", strlen(" - devices:\n"));
5766 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5767 mDeclaredDevices[i]->dump(fd, 4, i);
5768 }
5769 }
Eric Laurente552edb2014-03-10 17:42:56 -07005770}
5771
Eric Laurent1c333e22014-05-20 10:48:17 -07005772// --- AudioPort class implementation
5773
Eric Laurenta121f902014-06-03 13:32:54 -07005774
5775AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5776 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07005777 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07005778{
5779 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5780 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5781}
5782
Eric Laurent1c333e22014-05-20 10:48:17 -07005783void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5784{
5785 port->role = mRole;
5786 port->type = mType;
5787 unsigned int i;
5788 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005789 if (mSamplingRates[i] != 0) {
5790 port->sample_rates[i] = mSamplingRates[i];
5791 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005792 }
5793 port->num_sample_rates = i;
5794 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005795 if (mChannelMasks[i] != 0) {
5796 port->channel_masks[i] = mChannelMasks[i];
5797 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005798 }
5799 port->num_channel_masks = i;
5800 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005801 if (mFormats[i] != 0) {
5802 port->formats[i] = mFormats[i];
5803 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005804 }
5805 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005806
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005807 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005808
5809 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5810 port->gains[i] = mGains[i]->mGain;
5811 }
5812 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005813}
5814
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005815void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5816 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5817 const uint32_t rate = port->mSamplingRates.itemAt(k);
5818 if (rate != 0) { // skip "dynamic" rates
5819 bool hasRate = false;
5820 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5821 if (rate == mSamplingRates.itemAt(l)) {
5822 hasRate = true;
5823 break;
5824 }
5825 }
5826 if (!hasRate) { // never import a sampling rate twice
5827 mSamplingRates.add(rate);
5828 }
5829 }
5830 }
5831 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5832 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5833 if (mask != 0) { // skip "dynamic" masks
5834 bool hasMask = false;
5835 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5836 if (mask == mChannelMasks.itemAt(l)) {
5837 hasMask = true;
5838 break;
5839 }
5840 }
5841 if (!hasMask) { // never import a channel mask twice
5842 mChannelMasks.add(mask);
5843 }
5844 }
5845 }
5846 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5847 const audio_format_t format = port->mFormats.itemAt(k);
5848 if (format != 0) { // skip "dynamic" formats
5849 bool hasFormat = false;
5850 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5851 if (format == mFormats.itemAt(l)) {
5852 hasFormat = true;
5853 break;
5854 }
5855 }
5856 if (!hasFormat) { // never import a channel mask twice
5857 mFormats.add(format);
5858 }
5859 }
5860 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08005861 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
5862 sp<AudioGain> gain = port->mGains.itemAt(k);
5863 if (gain != 0) {
5864 bool hasGain = false;
5865 for (size_t l = 0 ; l < mGains.size() ; l++) {
5866 if (gain == mGains.itemAt(l)) {
5867 hasGain = true;
5868 break;
5869 }
5870 }
5871 if (!hasGain) { // never import a gain twice
5872 mGains.add(gain);
5873 }
5874 }
5875 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005876}
5877
5878void AudioPolicyManager::AudioPort::clearCapabilities() {
5879 mChannelMasks.clear();
5880 mFormats.clear();
5881 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08005882 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005883}
Eric Laurent1c333e22014-05-20 10:48:17 -07005884
5885void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5886{
5887 char *str = strtok(name, "|");
5888
5889 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5890 // rates 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 mSamplingRates.add(0);
5893 return;
5894 }
5895
5896 while (str != NULL) {
5897 uint32_t rate = atoi(str);
5898 if (rate != 0) {
5899 ALOGV("loadSamplingRates() adding rate %d", rate);
5900 mSamplingRates.add(rate);
5901 }
5902 str = strtok(NULL, "|");
5903 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005904}
5905
5906void AudioPolicyManager::AudioPort::loadFormats(char *name)
5907{
5908 char *str = strtok(name, "|");
5909
5910 // by convention, "0' in the first entry in mFormats indicates the supported formats
5911 // should be read from the output stream after it is opened for the first time
5912 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5913 mFormats.add(AUDIO_FORMAT_DEFAULT);
5914 return;
5915 }
5916
5917 while (str != NULL) {
5918 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5919 ARRAY_SIZE(sFormatNameToEnumTable),
5920 str);
5921 if (format != AUDIO_FORMAT_DEFAULT) {
5922 mFormats.add(format);
5923 }
5924 str = strtok(NULL, "|");
5925 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005926}
5927
5928void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5929{
5930 const char *str = strtok(name, "|");
5931
5932 ALOGV("loadInChannels() %s", name);
5933
5934 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5935 mChannelMasks.add(0);
5936 return;
5937 }
5938
5939 while (str != NULL) {
5940 audio_channel_mask_t channelMask =
5941 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5942 ARRAY_SIZE(sInChannelsNameToEnumTable),
5943 str);
5944 if (channelMask != 0) {
5945 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5946 mChannelMasks.add(channelMask);
5947 }
5948 str = strtok(NULL, "|");
5949 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005950}
5951
5952void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5953{
5954 const char *str = strtok(name, "|");
5955
5956 ALOGV("loadOutChannels() %s", name);
5957
5958 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5959 // masks should be read from the output stream after it is opened for the first time
5960 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5961 mChannelMasks.add(0);
5962 return;
5963 }
5964
5965 while (str != NULL) {
5966 audio_channel_mask_t channelMask =
5967 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5968 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5969 str);
5970 if (channelMask != 0) {
5971 mChannelMasks.add(channelMask);
5972 }
5973 str = strtok(NULL, "|");
5974 }
5975 return;
5976}
5977
Eric Laurent1afeecb2014-05-14 08:52:28 -07005978audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5979{
5980 const char *str = strtok(name, "|");
5981
5982 ALOGV("loadGainMode() %s", name);
5983 audio_gain_mode_t mode = 0;
5984 while (str != NULL) {
5985 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5986 ARRAY_SIZE(sGainModeNameToEnumTable),
5987 str);
5988 str = strtok(NULL, "|");
5989 }
5990 return mode;
5991}
5992
Eric Laurenta121f902014-06-03 13:32:54 -07005993void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005994{
5995 cnode *node = root->first_child;
5996
Eric Laurenta121f902014-06-03 13:32:54 -07005997 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005998
5999 while (node) {
6000 if (strcmp(node->name, GAIN_MODE) == 0) {
6001 gain->mGain.mode = loadGainMode((char *)node->value);
6002 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006003 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006004 gain->mGain.channel_mask =
6005 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6006 ARRAY_SIZE(sInChannelsNameToEnumTable),
6007 (char *)node->value);
6008 } else {
6009 gain->mGain.channel_mask =
6010 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6011 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6012 (char *)node->value);
6013 }
6014 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6015 gain->mGain.min_value = atoi((char *)node->value);
6016 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6017 gain->mGain.max_value = atoi((char *)node->value);
6018 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6019 gain->mGain.default_value = atoi((char *)node->value);
6020 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6021 gain->mGain.step_value = atoi((char *)node->value);
6022 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6023 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6024 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6025 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6026 }
6027 node = node->next;
6028 }
6029
6030 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6031 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6032
6033 if (gain->mGain.mode == 0) {
6034 return;
6035 }
6036 mGains.add(gain);
6037}
6038
6039void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6040{
6041 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006042 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006043 while (node) {
6044 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006045 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006046 node = node->next;
6047 }
6048}
6049
Glenn Kastencbd48022014-07-24 13:46:44 -07006050status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006051{
6052 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6053 if (mSamplingRates[i] == samplingRate) {
6054 return NO_ERROR;
6055 }
6056 }
6057 return BAD_VALUE;
6058}
6059
Glenn Kastencbd48022014-07-24 13:46:44 -07006060status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6061 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006062{
Glenn Kastencbd48022014-07-24 13:46:44 -07006063 // Search for the closest supported sampling rate that is above (preferred)
6064 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6065 // The sampling rates do not need to be sorted in ascending order.
6066 ssize_t maxBelow = -1;
6067 ssize_t minAbove = -1;
6068 uint32_t candidate;
6069 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6070 candidate = mSamplingRates[i];
6071 if (candidate == samplingRate) {
6072 if (updatedSamplingRate != NULL) {
6073 *updatedSamplingRate = candidate;
6074 }
6075 return NO_ERROR;
6076 }
6077 // candidate < desired
6078 if (candidate < samplingRate) {
6079 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6080 maxBelow = i;
6081 }
6082 // candidate > desired
6083 } else {
6084 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6085 minAbove = i;
6086 }
6087 }
6088 }
6089 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6090 // TODO Move these assumptions out.
6091 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6092 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6093 // due to approximation by an int32_t of the
6094 // phase increments
6095 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6096 if (minAbove >= 0) {
6097 candidate = mSamplingRates[minAbove];
6098 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6099 if (updatedSamplingRate != NULL) {
6100 *updatedSamplingRate = candidate;
6101 }
6102 return NO_ERROR;
6103 }
6104 }
6105 // But if we have to up-sample from a lower sampling rate, that's OK.
6106 if (maxBelow >= 0) {
6107 candidate = mSamplingRates[maxBelow];
6108 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6109 if (updatedSamplingRate != NULL) {
6110 *updatedSamplingRate = candidate;
6111 }
6112 return NO_ERROR;
6113 }
6114 }
6115 // leave updatedSamplingRate unmodified
6116 return BAD_VALUE;
6117}
6118
6119status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6120{
6121 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006122 if (mChannelMasks[i] == channelMask) {
6123 return NO_ERROR;
6124 }
6125 }
6126 return BAD_VALUE;
6127}
6128
Glenn Kastencbd48022014-07-24 13:46:44 -07006129status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6130 const
6131{
6132 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6133 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6134 // FIXME Does not handle multi-channel automatic conversions yet
6135 audio_channel_mask_t supported = mChannelMasks[i];
6136 if (supported == channelMask) {
6137 return NO_ERROR;
6138 }
6139 if (isRecordThread) {
6140 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6141 // FIXME Abstract this out to a table.
6142 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6143 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6144 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6145 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6146 return NO_ERROR;
6147 }
6148 }
6149 }
6150 return BAD_VALUE;
6151}
6152
Eric Laurenta121f902014-06-03 13:32:54 -07006153status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6154{
6155 for (size_t i = 0; i < mFormats.size(); i ++) {
6156 if (mFormats[i] == format) {
6157 return NO_ERROR;
6158 }
6159 }
6160 return BAD_VALUE;
6161}
6162
Eric Laurent1e693b52014-07-09 15:03:28 -07006163
6164uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6165{
6166 // special case for uninitialized dynamic profile
6167 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6168 return 0;
6169 }
6170
Eric Laurent828bcff2014-09-07 12:26:06 -07006171 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6172 // channel count / sampling rate combination chosen will be supported by the connected
6173 // sink
6174 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6175 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6176 uint32_t samplingRate = UINT_MAX;
6177 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6178 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6179 samplingRate = mSamplingRates[i];
6180 }
6181 }
6182 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6183 }
6184
Eric Laurent1e693b52014-07-09 15:03:28 -07006185 uint32_t samplingRate = 0;
6186 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6187
6188 // For mixed output and inputs, use max mixer sampling rates. Do not
6189 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006190 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006191 maxRate = UINT_MAX;
6192 }
6193 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6194 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6195 samplingRate = mSamplingRates[i];
6196 }
6197 }
6198 return samplingRate;
6199}
6200
6201audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6202{
6203 // special case for uninitialized dynamic profile
6204 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6205 return AUDIO_CHANNEL_NONE;
6206 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006207 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006208
6209 // For direct outputs, pick minimum channel count: this helps ensuring that the
6210 // channel count / sampling rate combination chosen will be supported by the connected
6211 // sink
6212 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6213 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6214 uint32_t channelCount = UINT_MAX;
6215 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6216 uint32_t cnlCount;
6217 if (mUseInChannelMask) {
6218 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6219 } else {
6220 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6221 }
6222 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6223 channelMask = mChannelMasks[i];
6224 channelCount = cnlCount;
6225 }
6226 }
6227 return channelMask;
6228 }
6229
Eric Laurent1e693b52014-07-09 15:03:28 -07006230 uint32_t channelCount = 0;
6231 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6232
6233 // For mixed output and inputs, use max mixer channel count. Do not
6234 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006235 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006236 maxCount = UINT_MAX;
6237 }
6238 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6239 uint32_t cnlCount;
6240 if (mUseInChannelMask) {
6241 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6242 } else {
6243 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6244 }
6245 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6246 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006247 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006248 }
6249 }
6250 return channelMask;
6251}
6252
Andy Hung9a605382014-07-28 16:16:31 -07006253/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006254const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6255 AUDIO_FORMAT_DEFAULT,
6256 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006257 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006258 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006259 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006260 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006261};
6262
6263int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6264 audio_format_t format2)
6265{
6266 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6267 // compressed format and better than any PCM format. This is by design of pickFormat()
6268 if (!audio_is_linear_pcm(format1)) {
6269 if (!audio_is_linear_pcm(format2)) {
6270 return 0;
6271 }
6272 return 1;
6273 }
6274 if (!audio_is_linear_pcm(format2)) {
6275 return -1;
6276 }
6277
6278 int index1 = -1, index2 = -1;
6279 for (size_t i = 0;
6280 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6281 i ++) {
6282 if (sPcmFormatCompareTable[i] == format1) {
6283 index1 = i;
6284 }
6285 if (sPcmFormatCompareTable[i] == format2) {
6286 index2 = i;
6287 }
6288 }
6289 // format1 not found => index1 < 0 => format2 > format1
6290 // format2 not found => index2 < 0 => format2 < format1
6291 return index1 - index2;
6292}
6293
6294audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6295{
6296 // special case for uninitialized dynamic profile
6297 if (mFormats.size() == 1 && mFormats[0] == 0) {
6298 return AUDIO_FORMAT_DEFAULT;
6299 }
6300
6301 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006302 audio_format_t bestFormat =
6303 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6304 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006305 // For mixed output and inputs, use best mixer output format. Do not
6306 // limit format otherwise
6307 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6308 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006309 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006310 bestFormat = AUDIO_FORMAT_INVALID;
6311 }
6312
6313 for (size_t i = 0; i < mFormats.size(); i ++) {
6314 if ((compareFormats(mFormats[i], format) > 0) &&
6315 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6316 format = mFormats[i];
6317 }
6318 }
6319 return format;
6320}
6321
Eric Laurenta121f902014-06-03 13:32:54 -07006322status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6323 int index) const
6324{
6325 if (index < 0 || (size_t)index >= mGains.size()) {
6326 return BAD_VALUE;
6327 }
6328 return mGains[index]->checkConfig(gainConfig);
6329}
6330
Eric Laurent1afeecb2014-05-14 08:52:28 -07006331void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6332{
6333 const size_t SIZE = 256;
6334 char buffer[SIZE];
6335 String8 result;
6336
6337 if (mName.size() != 0) {
6338 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6339 result.append(buffer);
6340 }
6341
6342 if (mSamplingRates.size() != 0) {
6343 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6344 result.append(buffer);
6345 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006346 if (i == 0 && mSamplingRates[i] == 0) {
6347 snprintf(buffer, SIZE, "Dynamic");
6348 } else {
6349 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6350 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006351 result.append(buffer);
6352 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6353 }
6354 result.append("\n");
6355 }
6356
6357 if (mChannelMasks.size() != 0) {
6358 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6359 result.append(buffer);
6360 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006361 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6362
6363 if (i == 0 && mChannelMasks[i] == 0) {
6364 snprintf(buffer, SIZE, "Dynamic");
6365 } else {
6366 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6367 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006368 result.append(buffer);
6369 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6370 }
6371 result.append("\n");
6372 }
6373
6374 if (mFormats.size() != 0) {
6375 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6376 result.append(buffer);
6377 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006378 const char *formatStr = enumToString(sFormatNameToEnumTable,
6379 ARRAY_SIZE(sFormatNameToEnumTable),
6380 mFormats[i]);
6381 if (i == 0 && strcmp(formatStr, "") == 0) {
6382 snprintf(buffer, SIZE, "Dynamic");
6383 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006384 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006385 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006386 result.append(buffer);
6387 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6388 }
6389 result.append("\n");
6390 }
6391 write(fd, result.string(), result.size());
6392 if (mGains.size() != 0) {
6393 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6394 write(fd, buffer, strlen(buffer) + 1);
6395 result.append(buffer);
6396 for (size_t i = 0; i < mGains.size(); i++) {
6397 mGains[i]->dump(fd, spaces + 2, i);
6398 }
6399 }
6400}
6401
6402// --- AudioGain class implementation
6403
Eric Laurenta121f902014-06-03 13:32:54 -07006404AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006405{
Eric Laurenta121f902014-06-03 13:32:54 -07006406 mIndex = index;
6407 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006408 memset(&mGain, 0, sizeof(struct audio_gain));
6409}
6410
Eric Laurenta121f902014-06-03 13:32:54 -07006411void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6412{
6413 config->index = mIndex;
6414 config->mode = mGain.mode;
6415 config->channel_mask = mGain.channel_mask;
6416 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6417 config->values[0] = mGain.default_value;
6418 } else {
6419 uint32_t numValues;
6420 if (mUseInChannelMask) {
6421 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6422 } else {
6423 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6424 }
6425 for (size_t i = 0; i < numValues; i++) {
6426 config->values[i] = mGain.default_value;
6427 }
6428 }
6429 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6430 config->ramp_duration_ms = mGain.min_ramp_ms;
6431 }
6432}
6433
6434status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6435{
6436 if ((config->mode & ~mGain.mode) != 0) {
6437 return BAD_VALUE;
6438 }
6439 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6440 if ((config->values[0] < mGain.min_value) ||
6441 (config->values[0] > mGain.max_value)) {
6442 return BAD_VALUE;
6443 }
6444 } else {
6445 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6446 return BAD_VALUE;
6447 }
6448 uint32_t numValues;
6449 if (mUseInChannelMask) {
6450 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6451 } else {
6452 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6453 }
6454 for (size_t i = 0; i < numValues; i++) {
6455 if ((config->values[i] < mGain.min_value) ||
6456 (config->values[i] > mGain.max_value)) {
6457 return BAD_VALUE;
6458 }
6459 }
6460 }
6461 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6462 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6463 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6464 return BAD_VALUE;
6465 }
6466 }
6467 return NO_ERROR;
6468}
6469
Eric Laurent1afeecb2014-05-14 08:52:28 -07006470void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6471{
6472 const size_t SIZE = 256;
6473 char buffer[SIZE];
6474 String8 result;
6475
6476 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6477 result.append(buffer);
6478 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6479 result.append(buffer);
6480 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6481 result.append(buffer);
6482 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6483 result.append(buffer);
6484 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6485 result.append(buffer);
6486 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6487 result.append(buffer);
6488 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6489 result.append(buffer);
6490 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6491 result.append(buffer);
6492 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6493 result.append(buffer);
6494
6495 write(fd, result.string(), result.size());
6496}
6497
Eric Laurent1f2f2232014-06-02 12:01:23 -07006498// --- AudioPortConfig class implementation
6499
6500AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6501{
6502 mSamplingRate = 0;
6503 mChannelMask = AUDIO_CHANNEL_NONE;
6504 mFormat = AUDIO_FORMAT_INVALID;
6505 mGain.index = -1;
6506}
6507
Eric Laurenta121f902014-06-03 13:32:54 -07006508status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6509 const struct audio_port_config *config,
6510 struct audio_port_config *backupConfig)
6511{
6512 struct audio_port_config localBackupConfig;
6513 status_t status = NO_ERROR;
6514
6515 localBackupConfig.config_mask = config->config_mask;
6516 toAudioPortConfig(&localBackupConfig);
6517
Marco Nelissen961ec212014-08-25 15:58:39 -07006518 sp<AudioPort> audioport = getAudioPort();
6519 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006520 status = NO_INIT;
6521 goto exit;
6522 }
6523 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006524 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006525 if (status != NO_ERROR) {
6526 goto exit;
6527 }
6528 mSamplingRate = config->sample_rate;
6529 }
6530 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006531 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006532 if (status != NO_ERROR) {
6533 goto exit;
6534 }
6535 mChannelMask = config->channel_mask;
6536 }
6537 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006538 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006539 if (status != NO_ERROR) {
6540 goto exit;
6541 }
6542 mFormat = config->format;
6543 }
6544 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006545 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006546 if (status != NO_ERROR) {
6547 goto exit;
6548 }
6549 mGain = config->gain;
6550 }
6551
6552exit:
6553 if (status != NO_ERROR) {
6554 applyAudioPortConfig(&localBackupConfig);
6555 }
6556 if (backupConfig != NULL) {
6557 *backupConfig = localBackupConfig;
6558 }
6559 return status;
6560}
6561
Eric Laurent1f2f2232014-06-02 12:01:23 -07006562void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6563 struct audio_port_config *dstConfig,
6564 const struct audio_port_config *srcConfig) const
6565{
6566 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6567 dstConfig->sample_rate = mSamplingRate;
6568 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6569 dstConfig->sample_rate = srcConfig->sample_rate;
6570 }
6571 } else {
6572 dstConfig->sample_rate = 0;
6573 }
6574 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6575 dstConfig->channel_mask = mChannelMask;
6576 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6577 dstConfig->channel_mask = srcConfig->channel_mask;
6578 }
6579 } else {
6580 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6581 }
6582 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6583 dstConfig->format = mFormat;
6584 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6585 dstConfig->format = srcConfig->format;
6586 }
6587 } else {
6588 dstConfig->format = AUDIO_FORMAT_INVALID;
6589 }
6590 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6591 dstConfig->gain = mGain;
6592 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6593 dstConfig->gain = srcConfig->gain;
6594 }
6595 } else {
6596 dstConfig->gain.index = -1;
6597 }
6598 if (dstConfig->gain.index != -1) {
6599 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6600 } else {
6601 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6602 }
6603}
6604
Eric Laurent1c333e22014-05-20 10:48:17 -07006605// --- IOProfile class implementation
6606
Eric Laurent1afeecb2014-05-14 08:52:28 -07006607AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006608 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006609 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006610{
6611}
6612
Eric Laurente0720872014-03-11 09:30:41 -07006613AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006614{
6615}
6616
6617// checks if the IO profile is compatible with specified parameters.
6618// Sampling rate, format and channel mask must be specified in order to
6619// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006620bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006621 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006622 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006623 audio_format_t format,
6624 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006625 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006626{
Glenn Kastencbd48022014-07-24 13:46:44 -07006627 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6628 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6629 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006630
Glenn Kastencbd48022014-07-24 13:46:44 -07006631 if ((mSupportedDevices.types() & device) != device) {
6632 return false;
6633 }
6634
6635 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006636 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006637 }
6638 uint32_t myUpdatedSamplingRate = samplingRate;
6639 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006640 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006641 }
6642 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6643 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006644 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006645 }
6646
6647 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6648 return false;
6649 }
6650
6651 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6652 checkExactChannelMask(channelMask) != NO_ERROR)) {
6653 return false;
6654 }
6655 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6656 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6657 return false;
6658 }
6659
6660 if (isPlaybackThread && (mFlags & flags) != flags) {
6661 return false;
6662 }
6663 // The only input flag that is allowed to be different is the fast flag.
6664 // An existing fast stream is compatible with a normal track request.
6665 // An existing normal stream is compatible with a fast track request,
6666 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006667 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006668 ~AUDIO_INPUT_FLAG_FAST)) {
6669 return false;
6670 }
6671
6672 if (updatedSamplingRate != NULL) {
6673 *updatedSamplingRate = myUpdatedSamplingRate;
6674 }
6675 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006676}
6677
Eric Laurente0720872014-03-11 09:30:41 -07006678void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006679{
6680 const size_t SIZE = 256;
6681 char buffer[SIZE];
6682 String8 result;
6683
Eric Laurent1afeecb2014-05-14 08:52:28 -07006684 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006685
Eric Laurente552edb2014-03-10 17:42:56 -07006686 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6687 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006688 snprintf(buffer, SIZE, " - devices:\n");
6689 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006690 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006691 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6692 mSupportedDevices[i]->dump(fd, 6, i);
6693 }
Eric Laurente552edb2014-03-10 17:42:56 -07006694}
6695
Eric Laurentd4692962014-05-05 18:13:44 -07006696void AudioPolicyManager::IOProfile::log()
6697{
6698 const size_t SIZE = 256;
6699 char buffer[SIZE];
6700 String8 result;
6701
6702 ALOGV(" - sampling rates: ");
6703 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6704 ALOGV(" %d", mSamplingRates[i]);
6705 }
6706
6707 ALOGV(" - channel masks: ");
6708 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6709 ALOGV(" 0x%04x", mChannelMasks[i]);
6710 }
6711
6712 ALOGV(" - formats: ");
6713 for (size_t i = 0; i < mFormats.size(); i++) {
6714 ALOGV(" 0x%08x", mFormats[i]);
6715 }
6716
6717 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6718 ALOGV(" - flags: 0x%04x\n", mFlags);
6719}
6720
6721
Eric Laurent3a4311c2014-03-17 12:00:47 -07006722// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006723
Eric Laurent1f2f2232014-06-02 12:01:23 -07006724
6725AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6726 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6727 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6728 AUDIO_PORT_ROLE_SOURCE,
6729 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006730 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006731{
Eric Laurenta121f902014-06-03 13:32:54 -07006732 if (mGains.size() > 0) {
6733 mGains[0]->getDefaultConfig(&mGain);
6734 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006735}
6736
Eric Laurent3a4311c2014-03-17 12:00:47 -07006737bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006738{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006739 // Devices are considered equal if they:
6740 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6741 // - have the same address or one device does not specify the address
6742 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006743 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006744 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006745 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006746 mChannelMask == other->mChannelMask);
6747}
6748
6749void AudioPolicyManager::DeviceVector::refreshTypes()
6750{
Eric Laurent1c333e22014-05-20 10:48:17 -07006751 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006752 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006753 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006754 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006755 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006756}
6757
6758ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6759{
6760 for(size_t i = 0; i < size(); i++) {
6761 if (item->equals(itemAt(i))) {
6762 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006763 }
6764 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006765 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006766}
6767
Eric Laurent3a4311c2014-03-17 12:00:47 -07006768ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006769{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006770 ssize_t ret = indexOf(item);
6771
6772 if (ret < 0) {
6773 ret = SortedVector::add(item);
6774 if (ret >= 0) {
6775 refreshTypes();
6776 }
6777 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006778 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006779 ret = -1;
6780 }
6781 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006782}
6783
Eric Laurent3a4311c2014-03-17 12:00:47 -07006784ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6785{
6786 size_t i;
6787 ssize_t ret = indexOf(item);
6788
6789 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006790 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006791 } else {
6792 ret = SortedVector::removeAt(ret);
6793 if (ret >= 0) {
6794 refreshTypes();
6795 }
6796 }
6797 return ret;
6798}
6799
6800void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6801{
6802 DeviceVector deviceList;
6803
6804 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6805 types &= ~role_bit;
6806
6807 while (types) {
6808 uint32_t i = 31 - __builtin_clz(types);
6809 uint32_t type = 1 << i;
6810 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006811 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006812 }
6813}
6814
Eric Laurent1afeecb2014-05-14 08:52:28 -07006815void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6816 const DeviceVector& declaredDevices)
6817{
6818 char *devName = strtok(name, "|");
6819 while (devName != NULL) {
6820 if (strlen(devName) != 0) {
6821 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6822 ARRAY_SIZE(sDeviceNameToEnumTable),
6823 devName);
6824 if (type != AUDIO_DEVICE_NONE) {
6825 add(new DeviceDescriptor(String8(""), type));
6826 } else {
6827 sp<DeviceDescriptor> deviceDesc =
6828 declaredDevices.getDeviceFromName(String8(devName));
6829 if (deviceDesc != 0) {
6830 add(deviceDesc);
6831 }
6832 }
6833 }
6834 devName = strtok(NULL, "|");
6835 }
6836}
6837
Eric Laurent1c333e22014-05-20 10:48:17 -07006838sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6839 audio_devices_t type, String8 address) const
6840{
6841 sp<DeviceDescriptor> device;
6842 for (size_t i = 0; i < size(); i++) {
6843 if (itemAt(i)->mDeviceType == type) {
6844 device = itemAt(i);
6845 if (itemAt(i)->mAddress = address) {
6846 break;
6847 }
6848 }
6849 }
6850 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6851 type, address.string(), device.get());
6852 return device;
6853}
6854
Eric Laurent6a94d692014-05-20 11:18:06 -07006855sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6856 audio_port_handle_t id) const
6857{
6858 sp<DeviceDescriptor> device;
6859 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006860 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006861 if (itemAt(i)->mId == id) {
6862 device = itemAt(i);
6863 break;
6864 }
6865 }
6866 return device;
6867}
6868
Eric Laurent1c333e22014-05-20 10:48:17 -07006869AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6870 audio_devices_t type) const
6871{
6872 DeviceVector devices;
6873 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6874 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6875 devices.add(itemAt(i));
6876 type &= ~itemAt(i)->mDeviceType;
6877 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6878 itemAt(i)->mDeviceType, itemAt(i).get());
6879 }
6880 }
6881 return devices;
6882}
6883
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006884AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6885 audio_devices_t type, String8 address) const
6886{
6887 DeviceVector devices;
6888 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6889 for (size_t i = 0; i < size(); i++) {
6890 //ALOGV(" at i=%d: device=%x, addr=%s",
6891 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6892 if (itemAt(i)->mDeviceType == type) {
6893 if (itemAt(i)->mAddress == address) {
6894 //ALOGV(" found matching address %s", address.string());
6895 devices.add(itemAt(i));
6896 }
6897 }
6898 }
6899 return devices;
6900}
6901
Eric Laurent1afeecb2014-05-14 08:52:28 -07006902sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6903 const String8& name) const
6904{
6905 sp<DeviceDescriptor> device;
6906 for (size_t i = 0; i < size(); i++) {
6907 if (itemAt(i)->mName == name) {
6908 device = itemAt(i);
6909 break;
6910 }
6911 }
6912 return device;
6913}
6914
Eric Laurent6a94d692014-05-20 11:18:06 -07006915void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6916 struct audio_port_config *dstConfig,
6917 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006918{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006919 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6920 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006921 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006922 }
6923
6924 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6925
Eric Laurent6a94d692014-05-20 11:18:06 -07006926 dstConfig->id = mId;
6927 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006928 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006929 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006930 dstConfig->ext.device.type = mDeviceType;
6931 dstConfig->ext.device.hw_module = mModule->mHandle;
6932 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006933}
6934
6935void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6936{
Eric Laurent83b88082014-06-20 18:31:16 -07006937 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006938 AudioPort::toAudioPort(port);
6939 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006940 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006941 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006942 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006943 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6944}
6945
Eric Laurent1afeecb2014-05-14 08:52:28 -07006946status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006947{
6948 const size_t SIZE = 256;
6949 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006950 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006951
Eric Laurent1afeecb2014-05-14 08:52:28 -07006952 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6953 result.append(buffer);
6954 if (mId != 0) {
6955 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6956 result.append(buffer);
6957 }
6958 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6959 enumToString(sDeviceNameToEnumTable,
6960 ARRAY_SIZE(sDeviceNameToEnumTable),
6961 mDeviceType));
6962 result.append(buffer);
6963 if (mAddress.size() != 0) {
6964 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6965 result.append(buffer);
6966 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006967 write(fd, result.string(), result.size());
6968 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006969
6970 return NO_ERROR;
6971}
6972
Eric Laurent4d416952014-08-10 14:07:09 -07006973status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6974{
6975 const size_t SIZE = 256;
6976 char buffer[SIZE];
6977 String8 result;
6978
6979
6980 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6981 result.append(buffer);
6982 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6983 result.append(buffer);
6984 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6985 result.append(buffer);
6986 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6987 result.append(buffer);
6988 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6989 result.append(buffer);
6990 for (size_t i = 0; i < mPatch.num_sources; i++) {
6991 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6992 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6993 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6994 ARRAY_SIZE(sDeviceNameToEnumTable),
6995 mPatch.sources[i].ext.device.type));
6996 } else {
6997 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6998 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6999 }
7000 result.append(buffer);
7001 }
7002 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7003 result.append(buffer);
7004 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7005 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7006 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7007 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7008 ARRAY_SIZE(sDeviceNameToEnumTable),
7009 mPatch.sinks[i].ext.device.type));
7010 } else {
7011 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7012 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7013 }
7014 result.append(buffer);
7015 }
7016
7017 write(fd, result.string(), result.size());
7018 return NO_ERROR;
7019}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007020
7021// --- audio_policy.conf file parsing
7022
Eric Laurent5dbe4712014-09-19 19:04:57 -07007023uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007024{
7025 uint32_t flag = 0;
7026
7027 // it is OK to cast name to non const here as we are not going to use it after
7028 // strtok() modifies it
7029 char *flagName = strtok(name, "|");
7030 while (flagName != NULL) {
7031 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007032 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7033 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007034 flagName);
7035 }
7036 flagName = strtok(NULL, "|");
7037 }
7038 //force direct flag if offload flag is set: offloading implies a direct output stream
7039 // and all common behaviors are driven by checking only the direct flag
7040 // this should normally be set appropriately in the policy configuration file
7041 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7042 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7043 }
7044
Eric Laurent5dbe4712014-09-19 19:04:57 -07007045 return flag;
7046}
7047
7048uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7049{
7050 uint32_t flag = 0;
7051
7052 // it is OK to cast name to non const here as we are not going to use it after
7053 // strtok() modifies it
7054 char *flagName = strtok(name, "|");
7055 while (flagName != NULL) {
7056 if (strlen(flagName) != 0) {
7057 flag |= stringToEnum(sInputFlagNameToEnumTable,
7058 ARRAY_SIZE(sInputFlagNameToEnumTable),
7059 flagName);
7060 }
7061 flagName = strtok(NULL, "|");
7062 }
7063 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007064}
7065
Eric Laurente0720872014-03-11 09:30:41 -07007066audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007067{
7068 uint32_t device = 0;
7069
7070 char *devName = strtok(name, "|");
7071 while (devName != NULL) {
7072 if (strlen(devName) != 0) {
7073 device |= stringToEnum(sDeviceNameToEnumTable,
7074 ARRAY_SIZE(sDeviceNameToEnumTable),
7075 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007076 }
Eric Laurente552edb2014-03-10 17:42:56 -07007077 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007078 }
Eric Laurente552edb2014-03-10 17:42:56 -07007079 return device;
7080}
7081
Eric Laurente0720872014-03-11 09:30:41 -07007082void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007083{
Eric Laurente552edb2014-03-10 17:42:56 -07007084 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007085 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007086 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007087
Eric Laurent1afeecb2014-05-14 08:52:28 -07007088 node = config_find(root, DEVICES_TAG);
7089 if (node != NULL) {
7090 node = node->first_child;
7091 while (node) {
7092 ALOGV("loadHwModule() loading device %s", node->name);
7093 status_t tmpStatus = module->loadDevice(node);
7094 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7095 status = tmpStatus;
7096 }
7097 node = node->next;
7098 }
7099 }
7100 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007101 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007102 node = node->first_child;
7103 while (node) {
7104 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007105 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007106 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7107 status = tmpStatus;
7108 }
7109 node = node->next;
7110 }
7111 }
7112 node = config_find(root, INPUTS_TAG);
7113 if (node != NULL) {
7114 node = node->first_child;
7115 while (node) {
7116 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007117 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007118 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7119 status = tmpStatus;
7120 }
7121 node = node->next;
7122 }
7123 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007124 loadGlobalConfig(root, module);
7125
Eric Laurente552edb2014-03-10 17:42:56 -07007126 if (status == NO_ERROR) {
7127 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007128 }
7129}
7130
Eric Laurente0720872014-03-11 09:30:41 -07007131void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007132{
7133 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7134 if (node == NULL) {
7135 return;
7136 }
7137
7138 node = node->first_child;
7139 while (node) {
7140 ALOGV("loadHwModules() loading module %s", node->name);
7141 loadHwModule(node);
7142 node = node->next;
7143 }
7144}
7145
Eric Laurent1f2f2232014-06-02 12:01:23 -07007146void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007147{
7148 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007149
Eric Laurente552edb2014-03-10 17:42:56 -07007150 if (node == NULL) {
7151 return;
7152 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007153 DeviceVector declaredDevices;
7154 if (module != NULL) {
7155 declaredDevices = module->mDeclaredDevices;
7156 }
7157
Eric Laurente552edb2014-03-10 17:42:56 -07007158 node = node->first_child;
7159 while (node) {
7160 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007161 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7162 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007163 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7164 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007165 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007166 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007167 ARRAY_SIZE(sDeviceNameToEnumTable),
7168 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007169 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007170 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007171 } else {
7172 ALOGW("loadGlobalConfig() default device not specified");
7173 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007174 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007175 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007176 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7177 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007178 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007179 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7180 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7181 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007182 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7183 uint32_t major, minor;
7184 sscanf((char *)node->value, "%u.%u", &major, &minor);
7185 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7186 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7187 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007188 }
7189 node = node->next;
7190 }
7191}
7192
Eric Laurente0720872014-03-11 09:30:41 -07007193status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007194{
7195 cnode *root;
7196 char *data;
7197
7198 data = (char *)load_file(path, NULL);
7199 if (data == NULL) {
7200 return -ENODEV;
7201 }
7202 root = config_node("", "");
7203 config_load(root, data);
7204
Eric Laurente552edb2014-03-10 17:42:56 -07007205 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007206 // legacy audio_policy.conf files have one global_configuration section
7207 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007208 config_free(root);
7209 free(root);
7210 free(data);
7211
7212 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7213
7214 return NO_ERROR;
7215}
7216
Eric Laurente0720872014-03-11 09:30:41 -07007217void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007218{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007219 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007220 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007221 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7222 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007223 mAvailableOutputDevices.add(mDefaultOutputDevice);
7224 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007225
7226 module = new HwModule("primary");
7227
Eric Laurent1afeecb2014-05-14 08:52:28 -07007228 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007229 profile->mSamplingRates.add(44100);
7230 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7231 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007232 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007233 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7234 module->mOutputProfiles.add(profile);
7235
Eric Laurent1afeecb2014-05-14 08:52:28 -07007236 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007237 profile->mSamplingRates.add(8000);
7238 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7239 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007240 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007241 module->mInputProfiles.add(profile);
7242
7243 mHwModules.add(module);
7244}
7245
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007246audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7247{
7248 // flags to stream type mapping
7249 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7250 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7251 }
7252 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7253 return AUDIO_STREAM_BLUETOOTH_SCO;
7254 }
7255
7256 // usage to stream type mapping
7257 switch (attr->usage) {
7258 case AUDIO_USAGE_MEDIA:
7259 case AUDIO_USAGE_GAME:
7260 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7261 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7262 return AUDIO_STREAM_MUSIC;
7263 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7264 return AUDIO_STREAM_SYSTEM;
7265 case AUDIO_USAGE_VOICE_COMMUNICATION:
7266 return AUDIO_STREAM_VOICE_CALL;
7267
7268 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7269 return AUDIO_STREAM_DTMF;
7270
7271 case AUDIO_USAGE_ALARM:
7272 return AUDIO_STREAM_ALARM;
7273 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7274 return AUDIO_STREAM_RING;
7275
7276 case AUDIO_USAGE_NOTIFICATION:
7277 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7278 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7279 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7280 case AUDIO_USAGE_NOTIFICATION_EVENT:
7281 return AUDIO_STREAM_NOTIFICATION;
7282
7283 case AUDIO_USAGE_UNKNOWN:
7284 default:
7285 return AUDIO_STREAM_MUSIC;
7286 }
7287}
Eric Laurente552edb2014-03-10 17:42:56 -07007288}; // namespace android