blob: 01a6c5509b00ca316321b1c2acc2a3948ee23df9 [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:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004361 // the requested device is AUDIO_DEVICE_NONE
4362 // OR the requested device is the same as current device
4363 // AND force is not specified
4364 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004365 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004366 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4367 outputDesc->mPatchHandle != 0) {
4368 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4369 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004370 return muteWaitMs;
4371 }
4372
4373 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004374
Eric Laurente552edb2014-03-10 17:42:56 -07004375 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004376 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004377 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004378 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004379 DeviceVector deviceList = (address == NULL) ?
4380 mAvailableOutputDevices.getDevicesFromType(device)
4381 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004382 if (!deviceList.isEmpty()) {
4383 struct audio_patch patch;
4384 outputDesc->toAudioPortConfig(&patch.sources[0]);
4385 patch.num_sources = 1;
4386 patch.num_sinks = 0;
4387 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4388 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004389 patch.num_sinks++;
4390 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004391 ssize_t index;
4392 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4393 index = mAudioPatches.indexOfKey(*patchHandle);
4394 } else {
4395 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4396 }
4397 sp< AudioPatch> patchDesc;
4398 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4399 if (index >= 0) {
4400 patchDesc = mAudioPatches.valueAt(index);
4401 afPatchHandle = patchDesc->mAfPatchHandle;
4402 }
4403
Eric Laurent1c333e22014-05-20 10:48:17 -07004404 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004405 &afPatchHandle,
4406 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004407 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4408 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004409 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004410 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004411 if (index < 0) {
4412 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4413 &patch, mUidCached);
4414 addAudioPatch(patchDesc->mHandle, patchDesc);
4415 } else {
4416 patchDesc->mPatch = patch;
4417 }
4418 patchDesc->mAfPatchHandle = afPatchHandle;
4419 patchDesc->mUid = mUidCached;
4420 if (patchHandle) {
4421 *patchHandle = patchDesc->mHandle;
4422 }
4423 outputDesc->mPatchHandle = patchDesc->mHandle;
4424 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004425 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004426 }
4427 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004428
4429 // inform all input as well
4430 for (size_t i = 0; i < mInputs.size(); i++) {
4431 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4432 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4433 AudioParameter inputCmd = AudioParameter();
4434 ALOGV("%s: inform input %d of device:%d", __func__,
4435 inputDescriptor->mIoHandle, device);
4436 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4437 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4438 inputCmd.toString(),
4439 delayMs);
4440 }
4441 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004442 }
Eric Laurente552edb2014-03-10 17:42:56 -07004443
4444 // update stream volumes according to new device
4445 applyStreamVolumes(output, device, delayMs);
4446
4447 return muteWaitMs;
4448}
4449
Eric Laurent1c333e22014-05-20 10:48:17 -07004450status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004451 int delayMs,
4452 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004453{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004454 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004455 ssize_t index;
4456 if (patchHandle) {
4457 index = mAudioPatches.indexOfKey(*patchHandle);
4458 } else {
4459 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4460 }
4461 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004462 return INVALID_OPERATION;
4463 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004464 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4465 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004466 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4467 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004468 removeAudioPatch(patchDesc->mHandle);
4469 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004470 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004471 return status;
4472}
4473
4474status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4475 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004476 bool force,
4477 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004478{
4479 status_t status = NO_ERROR;
4480
Eric Laurent1f2f2232014-06-02 12:01:23 -07004481 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004482 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4483 inputDesc->mDevice = device;
4484
4485 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4486 if (!deviceList.isEmpty()) {
4487 struct audio_patch patch;
4488 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004489 // AUDIO_SOURCE_HOTWORD is for internal use only:
4490 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004491 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4492 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004493 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4494 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004495 patch.num_sinks = 1;
4496 //only one input device for now
4497 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004498 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004499 ssize_t index;
4500 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4501 index = mAudioPatches.indexOfKey(*patchHandle);
4502 } else {
4503 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4504 }
4505 sp< AudioPatch> patchDesc;
4506 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4507 if (index >= 0) {
4508 patchDesc = mAudioPatches.valueAt(index);
4509 afPatchHandle = patchDesc->mAfPatchHandle;
4510 }
4511
Eric Laurent1c333e22014-05-20 10:48:17 -07004512 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004513 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004514 0);
4515 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004516 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004517 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004518 if (index < 0) {
4519 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4520 &patch, mUidCached);
4521 addAudioPatch(patchDesc->mHandle, patchDesc);
4522 } else {
4523 patchDesc->mPatch = patch;
4524 }
4525 patchDesc->mAfPatchHandle = afPatchHandle;
4526 patchDesc->mUid = mUidCached;
4527 if (patchHandle) {
4528 *patchHandle = patchDesc->mHandle;
4529 }
4530 inputDesc->mPatchHandle = patchDesc->mHandle;
4531 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004532 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004533 }
4534 }
4535 }
4536 return status;
4537}
4538
Eric Laurent6a94d692014-05-20 11:18:06 -07004539status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4540 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004541{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004542 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004543 ssize_t index;
4544 if (patchHandle) {
4545 index = mAudioPatches.indexOfKey(*patchHandle);
4546 } else {
4547 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4548 }
4549 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004550 return INVALID_OPERATION;
4551 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004552 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4553 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004554 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4555 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004556 removeAudioPatch(patchDesc->mHandle);
4557 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004558 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004559 return status;
4560}
4561
4562sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004563 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004564 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004565 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004566 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004567{
4568 // Choose an input profile based on the requested capture parameters: select the first available
4569 // profile supporting all requested parameters.
4570
4571 for (size_t i = 0; i < mHwModules.size(); i++)
4572 {
4573 if (mHwModules[i]->mHandle == 0) {
4574 continue;
4575 }
4576 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4577 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004578 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004579 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004580 if (profile->isCompatibleProfile(device, samplingRate,
4581 &samplingRate /*updatedSamplingRate*/,
4582 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004583 return profile;
4584 }
4585 }
4586 }
4587 return NULL;
4588}
4589
Eric Laurente0720872014-03-11 09:30:41 -07004590audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004591{
4592 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004593 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4594 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004595 switch (inputSource) {
4596 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004597 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004598 device = AUDIO_DEVICE_IN_VOICE_CALL;
4599 break;
4600 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004601 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004602
4603 case AUDIO_SOURCE_DEFAULT:
4604 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004605 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4606 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004607 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4608 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4609 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4610 device = AUDIO_DEVICE_IN_USB_DEVICE;
4611 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4612 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004613 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004614 break;
4615
4616 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4617 // Allow only use of devices on primary input if in call and HAL does not support routing
4618 // to voice call path.
4619 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4620 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4621 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4622 }
4623
4624 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4625 case AUDIO_POLICY_FORCE_BT_SCO:
4626 // if SCO device is requested but no SCO device is available, fall back to default case
4627 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4628 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4629 break;
4630 }
4631 // FALL THROUGH
4632
4633 default: // FORCE_NONE
4634 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4635 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4636 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4637 device = AUDIO_DEVICE_IN_USB_DEVICE;
4638 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4639 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4640 }
4641 break;
4642
4643 case AUDIO_POLICY_FORCE_SPEAKER:
4644 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4645 device = AUDIO_DEVICE_IN_BACK_MIC;
4646 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4647 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4648 }
4649 break;
4650 }
4651 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004652
Eric Laurente552edb2014-03-10 17:42:56 -07004653 case AUDIO_SOURCE_VOICE_RECOGNITION:
4654 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004655 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004656 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004657 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004658 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004659 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004660 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4661 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004662 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004663 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4664 }
4665 break;
4666 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004667 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004668 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004669 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004670 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4671 }
4672 break;
4673 case AUDIO_SOURCE_VOICE_DOWNLINK:
4674 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004675 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004676 device = AUDIO_DEVICE_IN_VOICE_CALL;
4677 }
4678 break;
4679 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004680 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004681 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4682 }
4683 break;
Hochi Huang327cb702014-09-21 09:47:31 +08004684 case AUDIO_SOURCE_FM_TUNER:
4685 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
4686 device = AUDIO_DEVICE_IN_FM_TUNER;
4687 }
4688 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004689 default:
4690 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4691 break;
4692 }
4693 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4694 return device;
4695}
4696
Eric Laurente0720872014-03-11 09:30:41 -07004697bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004698{
4699 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4700 device &= ~AUDIO_DEVICE_BIT_IN;
4701 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4702 return true;
4703 }
4704 return false;
4705}
4706
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004707bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4708 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4709}
4710
Eric Laurente0720872014-03-11 09:30:41 -07004711audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004712{
4713 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004714 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004715 if ((input_descriptor->mRefCount > 0)
4716 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4717 return mInputs.keyAt(i);
4718 }
4719 }
4720 return 0;
4721}
4722
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004723uint32_t AudioPolicyManager::activeInputsCount() const
4724{
4725 uint32_t count = 0;
4726 for (size_t i = 0; i < mInputs.size(); i++) {
4727 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4728 if (desc->mRefCount > 0) {
4729 return count++;
4730 }
4731 }
4732 return count;
4733}
4734
Eric Laurente552edb2014-03-10 17:42:56 -07004735
Eric Laurente0720872014-03-11 09:30:41 -07004736audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004737{
4738 if (device == AUDIO_DEVICE_NONE) {
4739 // this happens when forcing a route update and no track is active on an output.
4740 // In this case the returned category is not important.
4741 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004742 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004743 // Multiple device selection is either:
4744 // - speaker + one other device: give priority to speaker in this case.
4745 // - one A2DP device + another device: happens with duplicated output. In this case
4746 // retain the device on the A2DP output as the other must not correspond to an active
4747 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004748 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004749 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4750 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004751 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4752 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4753 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4754 device = AUDIO_DEVICE_OUT_AUX_LINE;
4755 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4756 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004757 } else {
4758 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4759 }
4760 }
4761
Jon Eklund11c9fb12014-06-23 14:47:03 -05004762 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4763 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4764 device = AUDIO_DEVICE_OUT_SPEAKER;
4765
Eric Laurent3b73df72014-03-11 09:06:29 -07004766 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004767 "getDeviceForVolume() invalid device combination: %08x",
4768 device);
4769
4770 return device;
4771}
4772
Eric Laurente0720872014-03-11 09:30:41 -07004773AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004774{
4775 switch(getDeviceForVolume(device)) {
4776 case AUDIO_DEVICE_OUT_EARPIECE:
4777 return DEVICE_CATEGORY_EARPIECE;
4778 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4779 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4780 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4781 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4782 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4783 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4784 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004785 case AUDIO_DEVICE_OUT_LINE:
4786 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4787 /*USB? Remote submix?*/
4788 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004789 case AUDIO_DEVICE_OUT_SPEAKER:
4790 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4791 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004792 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4793 case AUDIO_DEVICE_OUT_USB_DEVICE:
4794 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4795 default:
4796 return DEVICE_CATEGORY_SPEAKER;
4797 }
4798}
4799
Eric Laurente0720872014-03-11 09:30:41 -07004800float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004801 int indexInUi)
4802{
4803 device_category deviceCategory = getDeviceCategory(device);
4804 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4805
4806 // the volume index in the UI is relative to the min and max volume indices for this stream type
4807 int nbSteps = 1 + curve[VOLMAX].mIndex -
4808 curve[VOLMIN].mIndex;
4809 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4810 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4811
4812 // find what part of the curve this index volume belongs to, or if it's out of bounds
4813 int segment = 0;
4814 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4815 return 0.0f;
4816 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4817 segment = 0;
4818 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4819 segment = 1;
4820 } else if (volIdx <= curve[VOLMAX].mIndex) {
4821 segment = 2;
4822 } else { // out of bounds
4823 return 1.0f;
4824 }
4825
4826 // linear interpolation in the attenuation table in dB
4827 float decibels = curve[segment].mDBAttenuation +
4828 ((float)(volIdx - curve[segment].mIndex)) *
4829 ( (curve[segment+1].mDBAttenuation -
4830 curve[segment].mDBAttenuation) /
4831 ((float)(curve[segment+1].mIndex -
4832 curve[segment].mIndex)) );
4833
4834 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4835
4836 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4837 curve[segment].mIndex, volIdx,
4838 curve[segment+1].mIndex,
4839 curve[segment].mDBAttenuation,
4840 decibels,
4841 curve[segment+1].mDBAttenuation,
4842 amplification);
4843
4844 return amplification;
4845}
4846
Eric Laurente0720872014-03-11 09:30:41 -07004847const AudioPolicyManager::VolumeCurvePoint
4848 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004849 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4850};
4851
Eric Laurente0720872014-03-11 09:30:41 -07004852const AudioPolicyManager::VolumeCurvePoint
4853 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004854 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4855};
4856
Eric Laurente0720872014-03-11 09:30:41 -07004857const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004858 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4859 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4860};
4861
4862const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004863 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004864 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4865};
4866
Eric Laurente0720872014-03-11 09:30:41 -07004867const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004868 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004869 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004870};
4871
4872const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004873 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004874 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4875};
4876
Eric Laurente0720872014-03-11 09:30:41 -07004877const AudioPolicyManager::VolumeCurvePoint
4878 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004879 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4880};
4881
4882// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4883// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4884// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4885// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4886
Eric Laurente0720872014-03-11 09:30:41 -07004887const AudioPolicyManager::VolumeCurvePoint
4888 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004889 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4890};
4891
Eric Laurente0720872014-03-11 09:30:41 -07004892const AudioPolicyManager::VolumeCurvePoint
4893 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004894 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4895};
4896
Eric Laurente0720872014-03-11 09:30:41 -07004897const AudioPolicyManager::VolumeCurvePoint
4898 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004899 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4900};
4901
Eric Laurente0720872014-03-11 09:30:41 -07004902const AudioPolicyManager::VolumeCurvePoint
4903 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004904 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4905};
4906
Eric Laurente0720872014-03-11 09:30:41 -07004907const AudioPolicyManager::VolumeCurvePoint
4908 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004909 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4910};
4911
Eric Laurente0720872014-03-11 09:30:41 -07004912const AudioPolicyManager::VolumeCurvePoint
4913 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4914 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004915 { // AUDIO_STREAM_VOICE_CALL
4916 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4917 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004918 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4919 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004920 },
4921 { // AUDIO_STREAM_SYSTEM
4922 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4923 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004924 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4925 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004926 },
4927 { // AUDIO_STREAM_RING
4928 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4929 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004930 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4931 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004932 },
4933 { // AUDIO_STREAM_MUSIC
4934 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4935 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004936 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4937 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004938 },
4939 { // AUDIO_STREAM_ALARM
4940 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4941 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004942 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4943 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004944 },
4945 { // AUDIO_STREAM_NOTIFICATION
4946 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4947 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004948 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4949 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004950 },
4951 { // AUDIO_STREAM_BLUETOOTH_SCO
4952 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4953 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004954 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4955 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004956 },
4957 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4958 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4959 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004960 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4961 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004962 },
4963 { // AUDIO_STREAM_DTMF
4964 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4965 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004966 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4967 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004968 },
4969 { // AUDIO_STREAM_TTS
4970 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4971 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004972 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4973 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004974 },
4975};
4976
Eric Laurente0720872014-03-11 09:30:41 -07004977void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004978{
4979 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4980 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4981 mStreams[i].mVolumeCurve[j] =
4982 sVolumeProfiles[i][j];
4983 }
4984 }
4985
4986 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4987 if (mSpeakerDrcEnabled) {
4988 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4989 sDefaultSystemVolumeCurveDrc;
4990 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4991 sSpeakerSonificationVolumeCurveDrc;
4992 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4993 sSpeakerSonificationVolumeCurveDrc;
4994 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4995 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004996 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4997 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004998 }
4999}
5000
Eric Laurente0720872014-03-11 09:30:41 -07005001float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005002 int index,
5003 audio_io_handle_t output,
5004 audio_devices_t device)
5005{
5006 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005007 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005008 StreamDescriptor &streamDesc = mStreams[stream];
5009
5010 if (device == AUDIO_DEVICE_NONE) {
5011 device = outputDesc->device();
5012 }
5013
Eric Laurente552edb2014-03-10 17:42:56 -07005014 volume = volIndexToAmpl(device, streamDesc, index);
5015
5016 // if a headset is connected, apply the following rules to ring tones and notifications
5017 // to avoid sound level bursts in user's ears:
5018 // - always attenuate ring tones and notifications volume by 6dB
5019 // - if music is playing, always limit the volume to current music volume,
5020 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005021 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005022 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5023 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5024 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5025 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5026 ((stream_strategy == STRATEGY_SONIFICATION)
5027 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005028 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005029 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005030 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005031 streamDesc.mCanBeMuted) {
5032 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5033 // when the phone is ringing we must consider that music could have been paused just before
5034 // by the music application and behave as if music was active if the last music track was
5035 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005036 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005037 mLimitRingtoneVolume) {
5038 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005039 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5040 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005041 output,
5042 musicDevice);
5043 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5044 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5045 if (volume > minVol) {
5046 volume = minVol;
5047 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5048 }
5049 }
5050 }
5051
5052 return volume;
5053}
5054
Eric Laurente0720872014-03-11 09:30:41 -07005055status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005056 int index,
5057 audio_io_handle_t output,
5058 audio_devices_t device,
5059 int delayMs,
5060 bool force)
5061{
5062
5063 // do not change actual stream volume if the stream is muted
5064 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5065 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5066 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5067 return NO_ERROR;
5068 }
5069
5070 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005071 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5072 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5073 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5074 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005075 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005076 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005077 return INVALID_OPERATION;
5078 }
5079
5080 float volume = computeVolume(stream, index, output, device);
5081 // We actually change the volume if:
5082 // - the float value returned by computeVolume() changed
5083 // - the force flag is set
5084 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5085 force) {
5086 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5087 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5088 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5089 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005090 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5091 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005092 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005093 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005094 }
5095
Eric Laurent3b73df72014-03-11 09:06:29 -07005096 if (stream == AUDIO_STREAM_VOICE_CALL ||
5097 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005098 float voiceVolume;
5099 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005100 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005101 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5102 } else {
5103 voiceVolume = 1.0;
5104 }
5105
5106 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5107 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5108 mLastVoiceVolume = voiceVolume;
5109 }
5110 }
5111
5112 return NO_ERROR;
5113}
5114
Eric Laurente0720872014-03-11 09:30:41 -07005115void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005116 audio_devices_t device,
5117 int delayMs,
5118 bool force)
5119{
5120 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5121
Eric Laurent3b73df72014-03-11 09:06:29 -07005122 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5123 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005124 mStreams[stream].getVolumeIndex(device),
5125 output,
5126 device,
5127 delayMs,
5128 force);
5129 }
5130}
5131
Eric Laurente0720872014-03-11 09:30:41 -07005132void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005133 bool on,
5134 audio_io_handle_t output,
5135 int delayMs,
5136 audio_devices_t device)
5137{
5138 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005139 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5140 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5141 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005142 }
5143 }
5144}
5145
Eric Laurente0720872014-03-11 09:30:41 -07005146void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005147 bool on,
5148 audio_io_handle_t output,
5149 int delayMs,
5150 audio_devices_t device)
5151{
5152 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005153 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005154 if (device == AUDIO_DEVICE_NONE) {
5155 device = outputDesc->device();
5156 }
5157
5158 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5159 stream, on, output, outputDesc->mMuteCount[stream], device);
5160
5161 if (on) {
5162 if (outputDesc->mMuteCount[stream] == 0) {
5163 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005164 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5165 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005166 checkAndSetVolume(stream, 0, output, device, delayMs);
5167 }
5168 }
5169 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5170 outputDesc->mMuteCount[stream]++;
5171 } else {
5172 if (outputDesc->mMuteCount[stream] == 0) {
5173 ALOGV("setStreamMute() unmuting non muted stream!");
5174 return;
5175 }
5176 if (--outputDesc->mMuteCount[stream] == 0) {
5177 checkAndSetVolume(stream,
5178 streamDesc.getVolumeIndex(device),
5179 output,
5180 device,
5181 delayMs);
5182 }
5183 }
5184}
5185
Eric Laurente0720872014-03-11 09:30:41 -07005186void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005187 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005188{
5189 // if the stream pertains to sonification strategy and we are in call we must
5190 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5191 // in the device used for phone strategy and play the tone if the selected device does not
5192 // interfere with the device used for phone strategy
5193 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5194 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005195 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005196 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5197 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005198 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005199 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5200 stream, starting, outputDesc->mDevice, stateChange);
5201 if (outputDesc->mRefCount[stream]) {
5202 int muteCount = 1;
5203 if (stateChange) {
5204 muteCount = outputDesc->mRefCount[stream];
5205 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005206 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005207 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5208 for (int i = 0; i < muteCount; i++) {
5209 setStreamMute(stream, starting, mPrimaryOutput);
5210 }
5211 } else {
5212 ALOGV("handleIncallSonification() high visibility");
5213 if (outputDesc->device() &
5214 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5215 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5216 for (int i = 0; i < muteCount; i++) {
5217 setStreamMute(stream, starting, mPrimaryOutput);
5218 }
5219 }
5220 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005221 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5222 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005223 } else {
5224 mpClientInterface->stopTone();
5225 }
5226 }
5227 }
5228 }
5229}
5230
Eric Laurente0720872014-03-11 09:30:41 -07005231bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005232{
5233 return isStateInCall(mPhoneState);
5234}
5235
Eric Laurente0720872014-03-11 09:30:41 -07005236bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005237 return ((state == AUDIO_MODE_IN_CALL) ||
5238 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005239}
5240
Eric Laurente0720872014-03-11 09:30:41 -07005241uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005242{
5243 return MAX_EFFECTS_CPU_LOAD;
5244}
5245
Eric Laurente0720872014-03-11 09:30:41 -07005246uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005247{
5248 return MAX_EFFECTS_MEMORY;
5249}
5250
Eric Laurent6a94d692014-05-20 11:18:06 -07005251
Eric Laurente552edb2014-03-10 17:42:56 -07005252// --- AudioOutputDescriptor class implementation
5253
Eric Laurente0720872014-03-11 09:30:41 -07005254AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005255 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005256 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005257 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005258 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5259{
5260 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005261 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005262 mRefCount[i] = 0;
5263 mCurVolume[i] = -1.0;
5264 mMuteCount[i] = 0;
5265 mStopTime[i] = 0;
5266 }
5267 for (int i = 0; i < NUM_STRATEGIES; i++) {
5268 mStrategyMutedByDevice[i] = false;
5269 }
5270 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005271 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005272 mSamplingRate = profile->pickSamplingRate();
5273 mFormat = profile->pickFormat();
5274 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005275 if (profile->mGains.size() > 0) {
5276 profile->mGains[0]->getDefaultConfig(&mGain);
5277 }
Eric Laurente552edb2014-03-10 17:42:56 -07005278 }
5279}
5280
Eric Laurente0720872014-03-11 09:30:41 -07005281audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005282{
5283 if (isDuplicated()) {
5284 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5285 } else {
5286 return mDevice;
5287 }
5288}
5289
Eric Laurente0720872014-03-11 09:30:41 -07005290uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005291{
5292 if (isDuplicated()) {
5293 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5294 } else {
5295 return mLatency;
5296 }
5297}
5298
Eric Laurente0720872014-03-11 09:30:41 -07005299bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005300 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005301{
5302 if (isDuplicated()) {
5303 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5304 } else if (outputDesc->isDuplicated()){
5305 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5306 } else {
5307 return (mProfile->mModule == outputDesc->mProfile->mModule);
5308 }
5309}
5310
Eric Laurente0720872014-03-11 09:30:41 -07005311void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005312 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005313{
5314 // forward usage count change to attached outputs
5315 if (isDuplicated()) {
5316 mOutput1->changeRefCount(stream, delta);
5317 mOutput2->changeRefCount(stream, delta);
5318 }
5319 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005320 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5321 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005322 mRefCount[stream] = 0;
5323 return;
5324 }
5325 mRefCount[stream] += delta;
5326 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5327}
5328
Eric Laurente0720872014-03-11 09:30:41 -07005329audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005330{
5331 if (isDuplicated()) {
5332 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5333 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005334 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005335 }
5336}
5337
Eric Laurente0720872014-03-11 09:30:41 -07005338bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005339{
5340 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5341}
5342
Eric Laurente0720872014-03-11 09:30:41 -07005343bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005344 uint32_t inPastMs,
5345 nsecs_t sysTime) const
5346{
5347 if ((sysTime == 0) && (inPastMs != 0)) {
5348 sysTime = systemTime();
5349 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005350 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5351 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005352 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005353 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005354 return true;
5355 }
5356 }
5357 return false;
5358}
5359
Eric Laurente0720872014-03-11 09:30:41 -07005360bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005361 uint32_t inPastMs,
5362 nsecs_t sysTime) const
5363{
5364 if (mRefCount[stream] != 0) {
5365 return true;
5366 }
5367 if (inPastMs == 0) {
5368 return false;
5369 }
5370 if (sysTime == 0) {
5371 sysTime = systemTime();
5372 }
5373 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5374 return true;
5375 }
5376 return false;
5377}
5378
Eric Laurent1c333e22014-05-20 10:48:17 -07005379void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005380 struct audio_port_config *dstConfig,
5381 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005382{
Eric Laurent84c70242014-06-23 08:46:27 -07005383 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5384
Eric Laurent1f2f2232014-06-02 12:01:23 -07005385 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5386 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5387 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005388 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005389 }
5390 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5391
Eric Laurent6a94d692014-05-20 11:18:06 -07005392 dstConfig->id = mId;
5393 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5394 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005395 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5396 dstConfig->ext.mix.handle = mIoHandle;
5397 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005398}
5399
5400void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5401 struct audio_port *port) const
5402{
Eric Laurent84c70242014-06-23 08:46:27 -07005403 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005404 mProfile->toAudioPort(port);
5405 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005406 toAudioPortConfig(&port->active_config);
5407 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005408 port->ext.mix.handle = mIoHandle;
5409 port->ext.mix.latency_class =
5410 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5411}
Eric Laurente552edb2014-03-10 17:42:56 -07005412
Eric Laurente0720872014-03-11 09:30:41 -07005413status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005414{
5415 const size_t SIZE = 256;
5416 char buffer[SIZE];
5417 String8 result;
5418
Eric Laurent4d416952014-08-10 14:07:09 -07005419 snprintf(buffer, SIZE, " ID: %d\n", mId);
5420 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005421 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5422 result.append(buffer);
5423 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5424 result.append(buffer);
5425 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5426 result.append(buffer);
5427 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5428 result.append(buffer);
5429 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5430 result.append(buffer);
5431 snprintf(buffer, SIZE, " Devices %08x\n", device());
5432 result.append(buffer);
5433 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5434 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005435 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5436 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5437 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005438 result.append(buffer);
5439 }
5440 write(fd, result.string(), result.size());
5441
5442 return NO_ERROR;
5443}
5444
5445// --- AudioInputDescriptor class implementation
5446
Eric Laurent1c333e22014-05-20 10:48:17 -07005447AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005448 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005449 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005450 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005451{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005452 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005453 mSamplingRate = profile->pickSamplingRate();
5454 mFormat = profile->pickFormat();
5455 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005456 if (profile->mGains.size() > 0) {
5457 profile->mGains[0]->getDefaultConfig(&mGain);
5458 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005459 }
Eric Laurente552edb2014-03-10 17:42:56 -07005460}
5461
Eric Laurent1c333e22014-05-20 10:48:17 -07005462void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005463 struct audio_port_config *dstConfig,
5464 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005465{
Eric Laurent84c70242014-06-23 08:46:27 -07005466 ALOG_ASSERT(mProfile != 0,
5467 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005468 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5469 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5470 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005471 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005472 }
5473
5474 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5475
Eric Laurent6a94d692014-05-20 11:18:06 -07005476 dstConfig->id = mId;
5477 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5478 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005479 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5480 dstConfig->ext.mix.handle = mIoHandle;
5481 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005482}
5483
5484void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5485 struct audio_port *port) const
5486{
Eric Laurent84c70242014-06-23 08:46:27 -07005487 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5488
Eric Laurent1c333e22014-05-20 10:48:17 -07005489 mProfile->toAudioPort(port);
5490 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005491 toAudioPortConfig(&port->active_config);
5492 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005493 port->ext.mix.handle = mIoHandle;
5494 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5495}
5496
Eric Laurente0720872014-03-11 09:30:41 -07005497status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005498{
5499 const size_t SIZE = 256;
5500 char buffer[SIZE];
5501 String8 result;
5502
Eric Laurent4d416952014-08-10 14:07:09 -07005503 snprintf(buffer, SIZE, " ID: %d\n", mId);
5504 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005505 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5506 result.append(buffer);
5507 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5508 result.append(buffer);
5509 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5510 result.append(buffer);
5511 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5512 result.append(buffer);
5513 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5514 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005515 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5516 result.append(buffer);
5517
Eric Laurente552edb2014-03-10 17:42:56 -07005518 write(fd, result.string(), result.size());
5519
5520 return NO_ERROR;
5521}
5522
5523// --- StreamDescriptor class implementation
5524
Eric Laurente0720872014-03-11 09:30:41 -07005525AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005526 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5527{
5528 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5529}
5530
Eric Laurente0720872014-03-11 09:30:41 -07005531int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005532{
Eric Laurente0720872014-03-11 09:30:41 -07005533 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005534 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5535 if (mIndexCur.indexOfKey(device) < 0) {
5536 device = AUDIO_DEVICE_OUT_DEFAULT;
5537 }
5538 return mIndexCur.valueFor(device);
5539}
5540
Eric Laurente0720872014-03-11 09:30:41 -07005541void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005542{
5543 const size_t SIZE = 256;
5544 char buffer[SIZE];
5545 String8 result;
5546
5547 snprintf(buffer, SIZE, "%s %02d %02d ",
5548 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5549 result.append(buffer);
5550 for (size_t i = 0; i < mIndexCur.size(); i++) {
5551 snprintf(buffer, SIZE, "%04x : %02d, ",
5552 mIndexCur.keyAt(i),
5553 mIndexCur.valueAt(i));
5554 result.append(buffer);
5555 }
5556 result.append("\n");
5557
5558 write(fd, result.string(), result.size());
5559}
5560
5561// --- EffectDescriptor class implementation
5562
Eric Laurente0720872014-03-11 09:30:41 -07005563status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005564{
5565 const size_t SIZE = 256;
5566 char buffer[SIZE];
5567 String8 result;
5568
5569 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5570 result.append(buffer);
5571 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5572 result.append(buffer);
5573 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5574 result.append(buffer);
5575 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5576 result.append(buffer);
5577 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5578 result.append(buffer);
5579 write(fd, result.string(), result.size());
5580
5581 return NO_ERROR;
5582}
5583
Eric Laurent1c333e22014-05-20 10:48:17 -07005584// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005585
Eric Laurente0720872014-03-11 09:30:41 -07005586AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005587 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5588 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005589{
5590}
5591
Eric Laurente0720872014-03-11 09:30:41 -07005592AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005593{
5594 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005595 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005596 }
5597 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005598 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005599 }
5600 free((void *)mName);
5601}
5602
Eric Laurent1afeecb2014-05-14 08:52:28 -07005603status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5604{
5605 cnode *node = root->first_child;
5606
5607 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5608
5609 while (node) {
5610 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5611 profile->loadSamplingRates((char *)node->value);
5612 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5613 profile->loadFormats((char *)node->value);
5614 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5615 profile->loadInChannels((char *)node->value);
5616 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5617 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5618 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005619 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5620 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005621 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5622 profile->loadGains(node);
5623 }
5624 node = node->next;
5625 }
5626 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5627 "loadInput() invalid supported devices");
5628 ALOGW_IF(profile->mChannelMasks.size() == 0,
5629 "loadInput() invalid supported channel masks");
5630 ALOGW_IF(profile->mSamplingRates.size() == 0,
5631 "loadInput() invalid supported sampling rates");
5632 ALOGW_IF(profile->mFormats.size() == 0,
5633 "loadInput() invalid supported formats");
5634 if (!profile->mSupportedDevices.isEmpty() &&
5635 (profile->mChannelMasks.size() != 0) &&
5636 (profile->mSamplingRates.size() != 0) &&
5637 (profile->mFormats.size() != 0)) {
5638
5639 ALOGV("loadInput() adding input Supported Devices %04x",
5640 profile->mSupportedDevices.types());
5641
5642 mInputProfiles.add(profile);
5643 return NO_ERROR;
5644 } else {
5645 return BAD_VALUE;
5646 }
5647}
5648
5649status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5650{
5651 cnode *node = root->first_child;
5652
5653 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5654
5655 while (node) {
5656 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5657 profile->loadSamplingRates((char *)node->value);
5658 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5659 profile->loadFormats((char *)node->value);
5660 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5661 profile->loadOutChannels((char *)node->value);
5662 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5663 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5664 mDeclaredDevices);
5665 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005666 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005667 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5668 profile->loadGains(node);
5669 }
5670 node = node->next;
5671 }
5672 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5673 "loadOutput() invalid supported devices");
5674 ALOGW_IF(profile->mChannelMasks.size() == 0,
5675 "loadOutput() invalid supported channel masks");
5676 ALOGW_IF(profile->mSamplingRates.size() == 0,
5677 "loadOutput() invalid supported sampling rates");
5678 ALOGW_IF(profile->mFormats.size() == 0,
5679 "loadOutput() invalid supported formats");
5680 if (!profile->mSupportedDevices.isEmpty() &&
5681 (profile->mChannelMasks.size() != 0) &&
5682 (profile->mSamplingRates.size() != 0) &&
5683 (profile->mFormats.size() != 0)) {
5684
5685 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5686 profile->mSupportedDevices.types(), profile->mFlags);
5687
5688 mOutputProfiles.add(profile);
5689 return NO_ERROR;
5690 } else {
5691 return BAD_VALUE;
5692 }
5693}
5694
5695status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5696{
5697 cnode *node = root->first_child;
5698
5699 audio_devices_t type = AUDIO_DEVICE_NONE;
5700 while (node) {
5701 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5702 type = parseDeviceNames((char *)node->value);
5703 break;
5704 }
5705 node = node->next;
5706 }
5707 if (type == AUDIO_DEVICE_NONE ||
5708 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5709 ALOGW("loadDevice() bad type %08x", type);
5710 return BAD_VALUE;
5711 }
5712 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5713 deviceDesc->mModule = this;
5714
5715 node = root->first_child;
5716 while (node) {
5717 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5718 deviceDesc->mAddress = String8((char *)node->value);
5719 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5720 if (audio_is_input_device(type)) {
5721 deviceDesc->loadInChannels((char *)node->value);
5722 } else {
5723 deviceDesc->loadOutChannels((char *)node->value);
5724 }
5725 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5726 deviceDesc->loadGains(node);
5727 }
5728 node = node->next;
5729 }
5730
5731 ALOGV("loadDevice() adding device name %s type %08x address %s",
5732 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5733
5734 mDeclaredDevices.add(deviceDesc);
5735
5736 return NO_ERROR;
5737}
5738
Eric Laurente0720872014-03-11 09:30:41 -07005739void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005740{
5741 const size_t SIZE = 256;
5742 char buffer[SIZE];
5743 String8 result;
5744
5745 snprintf(buffer, SIZE, " - name: %s\n", mName);
5746 result.append(buffer);
5747 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5748 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005749 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5750 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005751 write(fd, result.string(), result.size());
5752 if (mOutputProfiles.size()) {
5753 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5754 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005755 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005756 write(fd, buffer, strlen(buffer));
5757 mOutputProfiles[i]->dump(fd);
5758 }
5759 }
5760 if (mInputProfiles.size()) {
5761 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5762 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005763 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005764 write(fd, buffer, strlen(buffer));
5765 mInputProfiles[i]->dump(fd);
5766 }
5767 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005768 if (mDeclaredDevices.size()) {
5769 write(fd, " - devices:\n", strlen(" - devices:\n"));
5770 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5771 mDeclaredDevices[i]->dump(fd, 4, i);
5772 }
5773 }
Eric Laurente552edb2014-03-10 17:42:56 -07005774}
5775
Eric Laurent1c333e22014-05-20 10:48:17 -07005776// --- AudioPort class implementation
5777
Eric Laurenta121f902014-06-03 13:32:54 -07005778
5779AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5780 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07005781 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07005782{
5783 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5784 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5785}
5786
Eric Laurent1c333e22014-05-20 10:48:17 -07005787void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5788{
5789 port->role = mRole;
5790 port->type = mType;
5791 unsigned int i;
5792 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005793 if (mSamplingRates[i] != 0) {
5794 port->sample_rates[i] = mSamplingRates[i];
5795 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005796 }
5797 port->num_sample_rates = i;
5798 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005799 if (mChannelMasks[i] != 0) {
5800 port->channel_masks[i] = mChannelMasks[i];
5801 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005802 }
5803 port->num_channel_masks = i;
5804 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005805 if (mFormats[i] != 0) {
5806 port->formats[i] = mFormats[i];
5807 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005808 }
5809 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005810
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005811 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005812
5813 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5814 port->gains[i] = mGains[i]->mGain;
5815 }
5816 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005817}
5818
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005819void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5820 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5821 const uint32_t rate = port->mSamplingRates.itemAt(k);
5822 if (rate != 0) { // skip "dynamic" rates
5823 bool hasRate = false;
5824 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5825 if (rate == mSamplingRates.itemAt(l)) {
5826 hasRate = true;
5827 break;
5828 }
5829 }
5830 if (!hasRate) { // never import a sampling rate twice
5831 mSamplingRates.add(rate);
5832 }
5833 }
5834 }
5835 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5836 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5837 if (mask != 0) { // skip "dynamic" masks
5838 bool hasMask = false;
5839 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5840 if (mask == mChannelMasks.itemAt(l)) {
5841 hasMask = true;
5842 break;
5843 }
5844 }
5845 if (!hasMask) { // never import a channel mask twice
5846 mChannelMasks.add(mask);
5847 }
5848 }
5849 }
5850 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5851 const audio_format_t format = port->mFormats.itemAt(k);
5852 if (format != 0) { // skip "dynamic" formats
5853 bool hasFormat = false;
5854 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5855 if (format == mFormats.itemAt(l)) {
5856 hasFormat = true;
5857 break;
5858 }
5859 }
5860 if (!hasFormat) { // never import a channel mask twice
5861 mFormats.add(format);
5862 }
5863 }
5864 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08005865 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
5866 sp<AudioGain> gain = port->mGains.itemAt(k);
5867 if (gain != 0) {
5868 bool hasGain = false;
5869 for (size_t l = 0 ; l < mGains.size() ; l++) {
5870 if (gain == mGains.itemAt(l)) {
5871 hasGain = true;
5872 break;
5873 }
5874 }
5875 if (!hasGain) { // never import a gain twice
5876 mGains.add(gain);
5877 }
5878 }
5879 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005880}
5881
5882void AudioPolicyManager::AudioPort::clearCapabilities() {
5883 mChannelMasks.clear();
5884 mFormats.clear();
5885 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08005886 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005887}
Eric Laurent1c333e22014-05-20 10:48:17 -07005888
5889void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5890{
5891 char *str = strtok(name, "|");
5892
5893 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5894 // rates should be read from the output stream after it is opened for the first time
5895 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5896 mSamplingRates.add(0);
5897 return;
5898 }
5899
5900 while (str != NULL) {
5901 uint32_t rate = atoi(str);
5902 if (rate != 0) {
5903 ALOGV("loadSamplingRates() adding rate %d", rate);
5904 mSamplingRates.add(rate);
5905 }
5906 str = strtok(NULL, "|");
5907 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005908}
5909
5910void AudioPolicyManager::AudioPort::loadFormats(char *name)
5911{
5912 char *str = strtok(name, "|");
5913
5914 // by convention, "0' in the first entry in mFormats indicates the supported formats
5915 // should be read from the output stream after it is opened for the first time
5916 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5917 mFormats.add(AUDIO_FORMAT_DEFAULT);
5918 return;
5919 }
5920
5921 while (str != NULL) {
5922 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5923 ARRAY_SIZE(sFormatNameToEnumTable),
5924 str);
5925 if (format != AUDIO_FORMAT_DEFAULT) {
5926 mFormats.add(format);
5927 }
5928 str = strtok(NULL, "|");
5929 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005930}
5931
5932void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5933{
5934 const char *str = strtok(name, "|");
5935
5936 ALOGV("loadInChannels() %s", name);
5937
5938 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5939 mChannelMasks.add(0);
5940 return;
5941 }
5942
5943 while (str != NULL) {
5944 audio_channel_mask_t channelMask =
5945 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5946 ARRAY_SIZE(sInChannelsNameToEnumTable),
5947 str);
5948 if (channelMask != 0) {
5949 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5950 mChannelMasks.add(channelMask);
5951 }
5952 str = strtok(NULL, "|");
5953 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005954}
5955
5956void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5957{
5958 const char *str = strtok(name, "|");
5959
5960 ALOGV("loadOutChannels() %s", name);
5961
5962 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5963 // masks should be read from the output stream after it is opened for the first time
5964 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5965 mChannelMasks.add(0);
5966 return;
5967 }
5968
5969 while (str != NULL) {
5970 audio_channel_mask_t channelMask =
5971 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5972 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5973 str);
5974 if (channelMask != 0) {
5975 mChannelMasks.add(channelMask);
5976 }
5977 str = strtok(NULL, "|");
5978 }
5979 return;
5980}
5981
Eric Laurent1afeecb2014-05-14 08:52:28 -07005982audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5983{
5984 const char *str = strtok(name, "|");
5985
5986 ALOGV("loadGainMode() %s", name);
5987 audio_gain_mode_t mode = 0;
5988 while (str != NULL) {
5989 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5990 ARRAY_SIZE(sGainModeNameToEnumTable),
5991 str);
5992 str = strtok(NULL, "|");
5993 }
5994 return mode;
5995}
5996
Eric Laurenta121f902014-06-03 13:32:54 -07005997void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005998{
5999 cnode *node = root->first_child;
6000
Eric Laurenta121f902014-06-03 13:32:54 -07006001 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006002
6003 while (node) {
6004 if (strcmp(node->name, GAIN_MODE) == 0) {
6005 gain->mGain.mode = loadGainMode((char *)node->value);
6006 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006007 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006008 gain->mGain.channel_mask =
6009 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6010 ARRAY_SIZE(sInChannelsNameToEnumTable),
6011 (char *)node->value);
6012 } else {
6013 gain->mGain.channel_mask =
6014 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6015 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6016 (char *)node->value);
6017 }
6018 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6019 gain->mGain.min_value = atoi((char *)node->value);
6020 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6021 gain->mGain.max_value = atoi((char *)node->value);
6022 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6023 gain->mGain.default_value = atoi((char *)node->value);
6024 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6025 gain->mGain.step_value = atoi((char *)node->value);
6026 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6027 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6028 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6029 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6030 }
6031 node = node->next;
6032 }
6033
6034 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6035 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6036
6037 if (gain->mGain.mode == 0) {
6038 return;
6039 }
6040 mGains.add(gain);
6041}
6042
6043void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6044{
6045 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006046 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006047 while (node) {
6048 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006049 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006050 node = node->next;
6051 }
6052}
6053
Glenn Kastencbd48022014-07-24 13:46:44 -07006054status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006055{
6056 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6057 if (mSamplingRates[i] == samplingRate) {
6058 return NO_ERROR;
6059 }
6060 }
6061 return BAD_VALUE;
6062}
6063
Glenn Kastencbd48022014-07-24 13:46:44 -07006064status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6065 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006066{
Glenn Kastencbd48022014-07-24 13:46:44 -07006067 // Search for the closest supported sampling rate that is above (preferred)
6068 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6069 // The sampling rates do not need to be sorted in ascending order.
6070 ssize_t maxBelow = -1;
6071 ssize_t minAbove = -1;
6072 uint32_t candidate;
6073 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6074 candidate = mSamplingRates[i];
6075 if (candidate == samplingRate) {
6076 if (updatedSamplingRate != NULL) {
6077 *updatedSamplingRate = candidate;
6078 }
6079 return NO_ERROR;
6080 }
6081 // candidate < desired
6082 if (candidate < samplingRate) {
6083 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6084 maxBelow = i;
6085 }
6086 // candidate > desired
6087 } else {
6088 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6089 minAbove = i;
6090 }
6091 }
6092 }
6093 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6094 // TODO Move these assumptions out.
6095 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6096 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6097 // due to approximation by an int32_t of the
6098 // phase increments
6099 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6100 if (minAbove >= 0) {
6101 candidate = mSamplingRates[minAbove];
6102 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6103 if (updatedSamplingRate != NULL) {
6104 *updatedSamplingRate = candidate;
6105 }
6106 return NO_ERROR;
6107 }
6108 }
6109 // But if we have to up-sample from a lower sampling rate, that's OK.
6110 if (maxBelow >= 0) {
6111 candidate = mSamplingRates[maxBelow];
6112 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6113 if (updatedSamplingRate != NULL) {
6114 *updatedSamplingRate = candidate;
6115 }
6116 return NO_ERROR;
6117 }
6118 }
6119 // leave updatedSamplingRate unmodified
6120 return BAD_VALUE;
6121}
6122
6123status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6124{
6125 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006126 if (mChannelMasks[i] == channelMask) {
6127 return NO_ERROR;
6128 }
6129 }
6130 return BAD_VALUE;
6131}
6132
Glenn Kastencbd48022014-07-24 13:46:44 -07006133status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6134 const
6135{
6136 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6137 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6138 // FIXME Does not handle multi-channel automatic conversions yet
6139 audio_channel_mask_t supported = mChannelMasks[i];
6140 if (supported == channelMask) {
6141 return NO_ERROR;
6142 }
6143 if (isRecordThread) {
6144 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6145 // FIXME Abstract this out to a table.
6146 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6147 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6148 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6149 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6150 return NO_ERROR;
6151 }
6152 }
6153 }
6154 return BAD_VALUE;
6155}
6156
Eric Laurenta121f902014-06-03 13:32:54 -07006157status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6158{
6159 for (size_t i = 0; i < mFormats.size(); i ++) {
6160 if (mFormats[i] == format) {
6161 return NO_ERROR;
6162 }
6163 }
6164 return BAD_VALUE;
6165}
6166
Eric Laurent1e693b52014-07-09 15:03:28 -07006167
6168uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6169{
6170 // special case for uninitialized dynamic profile
6171 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6172 return 0;
6173 }
6174
Eric Laurent828bcff2014-09-07 12:26:06 -07006175 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6176 // channel count / sampling rate combination chosen will be supported by the connected
6177 // sink
6178 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6179 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6180 uint32_t samplingRate = UINT_MAX;
6181 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6182 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6183 samplingRate = mSamplingRates[i];
6184 }
6185 }
6186 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6187 }
6188
Eric Laurent1e693b52014-07-09 15:03:28 -07006189 uint32_t samplingRate = 0;
6190 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6191
6192 // For mixed output and inputs, use max mixer sampling rates. Do not
6193 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006194 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006195 maxRate = UINT_MAX;
6196 }
6197 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6198 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6199 samplingRate = mSamplingRates[i];
6200 }
6201 }
6202 return samplingRate;
6203}
6204
6205audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6206{
6207 // special case for uninitialized dynamic profile
6208 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6209 return AUDIO_CHANNEL_NONE;
6210 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006211 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006212
6213 // For direct outputs, pick minimum channel count: this helps ensuring that the
6214 // channel count / sampling rate combination chosen will be supported by the connected
6215 // sink
6216 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6217 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6218 uint32_t channelCount = UINT_MAX;
6219 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6220 uint32_t cnlCount;
6221 if (mUseInChannelMask) {
6222 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6223 } else {
6224 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6225 }
6226 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6227 channelMask = mChannelMasks[i];
6228 channelCount = cnlCount;
6229 }
6230 }
6231 return channelMask;
6232 }
6233
Eric Laurent1e693b52014-07-09 15:03:28 -07006234 uint32_t channelCount = 0;
6235 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6236
6237 // For mixed output and inputs, use max mixer channel count. Do not
6238 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006239 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006240 maxCount = UINT_MAX;
6241 }
6242 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6243 uint32_t cnlCount;
6244 if (mUseInChannelMask) {
6245 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6246 } else {
6247 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6248 }
6249 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6250 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006251 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006252 }
6253 }
6254 return channelMask;
6255}
6256
Andy Hung9a605382014-07-28 16:16:31 -07006257/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006258const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6259 AUDIO_FORMAT_DEFAULT,
6260 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006261 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006262 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006263 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006264 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006265};
6266
6267int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6268 audio_format_t format2)
6269{
6270 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6271 // compressed format and better than any PCM format. This is by design of pickFormat()
6272 if (!audio_is_linear_pcm(format1)) {
6273 if (!audio_is_linear_pcm(format2)) {
6274 return 0;
6275 }
6276 return 1;
6277 }
6278 if (!audio_is_linear_pcm(format2)) {
6279 return -1;
6280 }
6281
6282 int index1 = -1, index2 = -1;
6283 for (size_t i = 0;
6284 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6285 i ++) {
6286 if (sPcmFormatCompareTable[i] == format1) {
6287 index1 = i;
6288 }
6289 if (sPcmFormatCompareTable[i] == format2) {
6290 index2 = i;
6291 }
6292 }
6293 // format1 not found => index1 < 0 => format2 > format1
6294 // format2 not found => index2 < 0 => format2 < format1
6295 return index1 - index2;
6296}
6297
6298audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6299{
6300 // special case for uninitialized dynamic profile
6301 if (mFormats.size() == 1 && mFormats[0] == 0) {
6302 return AUDIO_FORMAT_DEFAULT;
6303 }
6304
6305 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006306 audio_format_t bestFormat =
6307 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6308 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006309 // For mixed output and inputs, use best mixer output format. Do not
6310 // limit format otherwise
6311 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6312 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006313 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006314 bestFormat = AUDIO_FORMAT_INVALID;
6315 }
6316
6317 for (size_t i = 0; i < mFormats.size(); i ++) {
6318 if ((compareFormats(mFormats[i], format) > 0) &&
6319 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6320 format = mFormats[i];
6321 }
6322 }
6323 return format;
6324}
6325
Eric Laurenta121f902014-06-03 13:32:54 -07006326status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6327 int index) const
6328{
6329 if (index < 0 || (size_t)index >= mGains.size()) {
6330 return BAD_VALUE;
6331 }
6332 return mGains[index]->checkConfig(gainConfig);
6333}
6334
Eric Laurent1afeecb2014-05-14 08:52:28 -07006335void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6336{
6337 const size_t SIZE = 256;
6338 char buffer[SIZE];
6339 String8 result;
6340
6341 if (mName.size() != 0) {
6342 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6343 result.append(buffer);
6344 }
6345
6346 if (mSamplingRates.size() != 0) {
6347 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6348 result.append(buffer);
6349 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006350 if (i == 0 && mSamplingRates[i] == 0) {
6351 snprintf(buffer, SIZE, "Dynamic");
6352 } else {
6353 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6354 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006355 result.append(buffer);
6356 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6357 }
6358 result.append("\n");
6359 }
6360
6361 if (mChannelMasks.size() != 0) {
6362 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6363 result.append(buffer);
6364 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006365 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6366
6367 if (i == 0 && mChannelMasks[i] == 0) {
6368 snprintf(buffer, SIZE, "Dynamic");
6369 } else {
6370 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6371 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006372 result.append(buffer);
6373 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6374 }
6375 result.append("\n");
6376 }
6377
6378 if (mFormats.size() != 0) {
6379 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6380 result.append(buffer);
6381 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006382 const char *formatStr = enumToString(sFormatNameToEnumTable,
6383 ARRAY_SIZE(sFormatNameToEnumTable),
6384 mFormats[i]);
6385 if (i == 0 && strcmp(formatStr, "") == 0) {
6386 snprintf(buffer, SIZE, "Dynamic");
6387 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006388 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006389 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006390 result.append(buffer);
6391 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6392 }
6393 result.append("\n");
6394 }
6395 write(fd, result.string(), result.size());
6396 if (mGains.size() != 0) {
6397 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6398 write(fd, buffer, strlen(buffer) + 1);
6399 result.append(buffer);
6400 for (size_t i = 0; i < mGains.size(); i++) {
6401 mGains[i]->dump(fd, spaces + 2, i);
6402 }
6403 }
6404}
6405
6406// --- AudioGain class implementation
6407
Eric Laurenta121f902014-06-03 13:32:54 -07006408AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006409{
Eric Laurenta121f902014-06-03 13:32:54 -07006410 mIndex = index;
6411 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006412 memset(&mGain, 0, sizeof(struct audio_gain));
6413}
6414
Eric Laurenta121f902014-06-03 13:32:54 -07006415void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6416{
6417 config->index = mIndex;
6418 config->mode = mGain.mode;
6419 config->channel_mask = mGain.channel_mask;
6420 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6421 config->values[0] = mGain.default_value;
6422 } else {
6423 uint32_t numValues;
6424 if (mUseInChannelMask) {
6425 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6426 } else {
6427 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6428 }
6429 for (size_t i = 0; i < numValues; i++) {
6430 config->values[i] = mGain.default_value;
6431 }
6432 }
6433 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6434 config->ramp_duration_ms = mGain.min_ramp_ms;
6435 }
6436}
6437
6438status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6439{
6440 if ((config->mode & ~mGain.mode) != 0) {
6441 return BAD_VALUE;
6442 }
6443 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6444 if ((config->values[0] < mGain.min_value) ||
6445 (config->values[0] > mGain.max_value)) {
6446 return BAD_VALUE;
6447 }
6448 } else {
6449 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6450 return BAD_VALUE;
6451 }
6452 uint32_t numValues;
6453 if (mUseInChannelMask) {
6454 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6455 } else {
6456 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6457 }
6458 for (size_t i = 0; i < numValues; i++) {
6459 if ((config->values[i] < mGain.min_value) ||
6460 (config->values[i] > mGain.max_value)) {
6461 return BAD_VALUE;
6462 }
6463 }
6464 }
6465 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6466 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6467 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6468 return BAD_VALUE;
6469 }
6470 }
6471 return NO_ERROR;
6472}
6473
Eric Laurent1afeecb2014-05-14 08:52:28 -07006474void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6475{
6476 const size_t SIZE = 256;
6477 char buffer[SIZE];
6478 String8 result;
6479
6480 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6481 result.append(buffer);
6482 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6483 result.append(buffer);
6484 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6485 result.append(buffer);
6486 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6487 result.append(buffer);
6488 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6489 result.append(buffer);
6490 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6491 result.append(buffer);
6492 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6493 result.append(buffer);
6494 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6495 result.append(buffer);
6496 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6497 result.append(buffer);
6498
6499 write(fd, result.string(), result.size());
6500}
6501
Eric Laurent1f2f2232014-06-02 12:01:23 -07006502// --- AudioPortConfig class implementation
6503
6504AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6505{
6506 mSamplingRate = 0;
6507 mChannelMask = AUDIO_CHANNEL_NONE;
6508 mFormat = AUDIO_FORMAT_INVALID;
6509 mGain.index = -1;
6510}
6511
Eric Laurenta121f902014-06-03 13:32:54 -07006512status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6513 const struct audio_port_config *config,
6514 struct audio_port_config *backupConfig)
6515{
6516 struct audio_port_config localBackupConfig;
6517 status_t status = NO_ERROR;
6518
6519 localBackupConfig.config_mask = config->config_mask;
6520 toAudioPortConfig(&localBackupConfig);
6521
Marco Nelissen961ec212014-08-25 15:58:39 -07006522 sp<AudioPort> audioport = getAudioPort();
6523 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006524 status = NO_INIT;
6525 goto exit;
6526 }
6527 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006528 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006529 if (status != NO_ERROR) {
6530 goto exit;
6531 }
6532 mSamplingRate = config->sample_rate;
6533 }
6534 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006535 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006536 if (status != NO_ERROR) {
6537 goto exit;
6538 }
6539 mChannelMask = config->channel_mask;
6540 }
6541 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006542 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006543 if (status != NO_ERROR) {
6544 goto exit;
6545 }
6546 mFormat = config->format;
6547 }
6548 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006549 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006550 if (status != NO_ERROR) {
6551 goto exit;
6552 }
6553 mGain = config->gain;
6554 }
6555
6556exit:
6557 if (status != NO_ERROR) {
6558 applyAudioPortConfig(&localBackupConfig);
6559 }
6560 if (backupConfig != NULL) {
6561 *backupConfig = localBackupConfig;
6562 }
6563 return status;
6564}
6565
Eric Laurent1f2f2232014-06-02 12:01:23 -07006566void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6567 struct audio_port_config *dstConfig,
6568 const struct audio_port_config *srcConfig) const
6569{
6570 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6571 dstConfig->sample_rate = mSamplingRate;
6572 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6573 dstConfig->sample_rate = srcConfig->sample_rate;
6574 }
6575 } else {
6576 dstConfig->sample_rate = 0;
6577 }
6578 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6579 dstConfig->channel_mask = mChannelMask;
6580 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6581 dstConfig->channel_mask = srcConfig->channel_mask;
6582 }
6583 } else {
6584 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6585 }
6586 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6587 dstConfig->format = mFormat;
6588 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6589 dstConfig->format = srcConfig->format;
6590 }
6591 } else {
6592 dstConfig->format = AUDIO_FORMAT_INVALID;
6593 }
6594 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6595 dstConfig->gain = mGain;
6596 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6597 dstConfig->gain = srcConfig->gain;
6598 }
6599 } else {
6600 dstConfig->gain.index = -1;
6601 }
6602 if (dstConfig->gain.index != -1) {
6603 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6604 } else {
6605 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6606 }
6607}
6608
Eric Laurent1c333e22014-05-20 10:48:17 -07006609// --- IOProfile class implementation
6610
Eric Laurent1afeecb2014-05-14 08:52:28 -07006611AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006612 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006613 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006614{
6615}
6616
Eric Laurente0720872014-03-11 09:30:41 -07006617AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006618{
6619}
6620
6621// checks if the IO profile is compatible with specified parameters.
6622// Sampling rate, format and channel mask must be specified in order to
6623// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006624bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006625 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006626 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006627 audio_format_t format,
6628 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006629 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006630{
Glenn Kastencbd48022014-07-24 13:46:44 -07006631 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6632 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6633 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006634
Glenn Kastencbd48022014-07-24 13:46:44 -07006635 if ((mSupportedDevices.types() & device) != device) {
6636 return false;
6637 }
6638
6639 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006640 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006641 }
6642 uint32_t myUpdatedSamplingRate = samplingRate;
6643 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006644 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006645 }
6646 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6647 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006648 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006649 }
6650
6651 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6652 return false;
6653 }
6654
6655 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6656 checkExactChannelMask(channelMask) != NO_ERROR)) {
6657 return false;
6658 }
6659 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6660 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6661 return false;
6662 }
6663
6664 if (isPlaybackThread && (mFlags & flags) != flags) {
6665 return false;
6666 }
6667 // The only input flag that is allowed to be different is the fast flag.
6668 // An existing fast stream is compatible with a normal track request.
6669 // An existing normal stream is compatible with a fast track request,
6670 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006671 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006672 ~AUDIO_INPUT_FLAG_FAST)) {
6673 return false;
6674 }
6675
6676 if (updatedSamplingRate != NULL) {
6677 *updatedSamplingRate = myUpdatedSamplingRate;
6678 }
6679 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006680}
6681
Eric Laurente0720872014-03-11 09:30:41 -07006682void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006683{
6684 const size_t SIZE = 256;
6685 char buffer[SIZE];
6686 String8 result;
6687
Eric Laurent1afeecb2014-05-14 08:52:28 -07006688 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006689
Eric Laurente552edb2014-03-10 17:42:56 -07006690 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6691 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006692 snprintf(buffer, SIZE, " - devices:\n");
6693 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006694 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006695 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6696 mSupportedDevices[i]->dump(fd, 6, i);
6697 }
Eric Laurente552edb2014-03-10 17:42:56 -07006698}
6699
Eric Laurentd4692962014-05-05 18:13:44 -07006700void AudioPolicyManager::IOProfile::log()
6701{
6702 const size_t SIZE = 256;
6703 char buffer[SIZE];
6704 String8 result;
6705
6706 ALOGV(" - sampling rates: ");
6707 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6708 ALOGV(" %d", mSamplingRates[i]);
6709 }
6710
6711 ALOGV(" - channel masks: ");
6712 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6713 ALOGV(" 0x%04x", mChannelMasks[i]);
6714 }
6715
6716 ALOGV(" - formats: ");
6717 for (size_t i = 0; i < mFormats.size(); i++) {
6718 ALOGV(" 0x%08x", mFormats[i]);
6719 }
6720
6721 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6722 ALOGV(" - flags: 0x%04x\n", mFlags);
6723}
6724
6725
Eric Laurent3a4311c2014-03-17 12:00:47 -07006726// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006727
Eric Laurent1f2f2232014-06-02 12:01:23 -07006728
6729AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6730 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6731 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6732 AUDIO_PORT_ROLE_SOURCE,
6733 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006734 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006735{
Eric Laurenta121f902014-06-03 13:32:54 -07006736 if (mGains.size() > 0) {
6737 mGains[0]->getDefaultConfig(&mGain);
6738 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006739}
6740
Eric Laurent3a4311c2014-03-17 12:00:47 -07006741bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006742{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006743 // Devices are considered equal if they:
6744 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6745 // - have the same address or one device does not specify the address
6746 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006747 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006748 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006749 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006750 mChannelMask == other->mChannelMask);
6751}
6752
6753void AudioPolicyManager::DeviceVector::refreshTypes()
6754{
Eric Laurent1c333e22014-05-20 10:48:17 -07006755 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006756 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006757 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006758 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006759 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006760}
6761
6762ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6763{
6764 for(size_t i = 0; i < size(); i++) {
6765 if (item->equals(itemAt(i))) {
6766 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006767 }
6768 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006769 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006770}
6771
Eric Laurent3a4311c2014-03-17 12:00:47 -07006772ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006773{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006774 ssize_t ret = indexOf(item);
6775
6776 if (ret < 0) {
6777 ret = SortedVector::add(item);
6778 if (ret >= 0) {
6779 refreshTypes();
6780 }
6781 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006782 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006783 ret = -1;
6784 }
6785 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006786}
6787
Eric Laurent3a4311c2014-03-17 12:00:47 -07006788ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6789{
6790 size_t i;
6791 ssize_t ret = indexOf(item);
6792
6793 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006794 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006795 } else {
6796 ret = SortedVector::removeAt(ret);
6797 if (ret >= 0) {
6798 refreshTypes();
6799 }
6800 }
6801 return ret;
6802}
6803
6804void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6805{
6806 DeviceVector deviceList;
6807
6808 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6809 types &= ~role_bit;
6810
6811 while (types) {
6812 uint32_t i = 31 - __builtin_clz(types);
6813 uint32_t type = 1 << i;
6814 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006815 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006816 }
6817}
6818
Eric Laurent1afeecb2014-05-14 08:52:28 -07006819void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6820 const DeviceVector& declaredDevices)
6821{
6822 char *devName = strtok(name, "|");
6823 while (devName != NULL) {
6824 if (strlen(devName) != 0) {
6825 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6826 ARRAY_SIZE(sDeviceNameToEnumTable),
6827 devName);
6828 if (type != AUDIO_DEVICE_NONE) {
6829 add(new DeviceDescriptor(String8(""), type));
6830 } else {
6831 sp<DeviceDescriptor> deviceDesc =
6832 declaredDevices.getDeviceFromName(String8(devName));
6833 if (deviceDesc != 0) {
6834 add(deviceDesc);
6835 }
6836 }
6837 }
6838 devName = strtok(NULL, "|");
6839 }
6840}
6841
Eric Laurent1c333e22014-05-20 10:48:17 -07006842sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6843 audio_devices_t type, String8 address) const
6844{
6845 sp<DeviceDescriptor> device;
6846 for (size_t i = 0; i < size(); i++) {
6847 if (itemAt(i)->mDeviceType == type) {
6848 device = itemAt(i);
6849 if (itemAt(i)->mAddress = address) {
6850 break;
6851 }
6852 }
6853 }
6854 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6855 type, address.string(), device.get());
6856 return device;
6857}
6858
Eric Laurent6a94d692014-05-20 11:18:06 -07006859sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6860 audio_port_handle_t id) const
6861{
6862 sp<DeviceDescriptor> device;
6863 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006864 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006865 if (itemAt(i)->mId == id) {
6866 device = itemAt(i);
6867 break;
6868 }
6869 }
6870 return device;
6871}
6872
Eric Laurent1c333e22014-05-20 10:48:17 -07006873AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6874 audio_devices_t type) const
6875{
6876 DeviceVector devices;
6877 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6878 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6879 devices.add(itemAt(i));
6880 type &= ~itemAt(i)->mDeviceType;
6881 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6882 itemAt(i)->mDeviceType, itemAt(i).get());
6883 }
6884 }
6885 return devices;
6886}
6887
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006888AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6889 audio_devices_t type, String8 address) const
6890{
6891 DeviceVector devices;
6892 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6893 for (size_t i = 0; i < size(); i++) {
6894 //ALOGV(" at i=%d: device=%x, addr=%s",
6895 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6896 if (itemAt(i)->mDeviceType == type) {
6897 if (itemAt(i)->mAddress == address) {
6898 //ALOGV(" found matching address %s", address.string());
6899 devices.add(itemAt(i));
6900 }
6901 }
6902 }
6903 return devices;
6904}
6905
Eric Laurent1afeecb2014-05-14 08:52:28 -07006906sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6907 const String8& name) const
6908{
6909 sp<DeviceDescriptor> device;
6910 for (size_t i = 0; i < size(); i++) {
6911 if (itemAt(i)->mName == name) {
6912 device = itemAt(i);
6913 break;
6914 }
6915 }
6916 return device;
6917}
6918
Eric Laurent6a94d692014-05-20 11:18:06 -07006919void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6920 struct audio_port_config *dstConfig,
6921 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006922{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006923 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6924 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006925 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006926 }
6927
6928 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6929
Eric Laurent6a94d692014-05-20 11:18:06 -07006930 dstConfig->id = mId;
6931 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006932 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006933 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006934 dstConfig->ext.device.type = mDeviceType;
6935 dstConfig->ext.device.hw_module = mModule->mHandle;
6936 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006937}
6938
6939void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6940{
Eric Laurent83b88082014-06-20 18:31:16 -07006941 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006942 AudioPort::toAudioPort(port);
6943 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006944 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006945 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006946 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006947 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6948}
6949
Eric Laurent1afeecb2014-05-14 08:52:28 -07006950status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006951{
6952 const size_t SIZE = 256;
6953 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006954 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006955
Eric Laurent1afeecb2014-05-14 08:52:28 -07006956 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6957 result.append(buffer);
6958 if (mId != 0) {
6959 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6960 result.append(buffer);
6961 }
6962 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6963 enumToString(sDeviceNameToEnumTable,
6964 ARRAY_SIZE(sDeviceNameToEnumTable),
6965 mDeviceType));
6966 result.append(buffer);
6967 if (mAddress.size() != 0) {
6968 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6969 result.append(buffer);
6970 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006971 write(fd, result.string(), result.size());
6972 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006973
6974 return NO_ERROR;
6975}
6976
Eric Laurent4d416952014-08-10 14:07:09 -07006977status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6978{
6979 const size_t SIZE = 256;
6980 char buffer[SIZE];
6981 String8 result;
6982
6983
6984 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6985 result.append(buffer);
6986 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6987 result.append(buffer);
6988 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6989 result.append(buffer);
6990 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6991 result.append(buffer);
6992 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6993 result.append(buffer);
6994 for (size_t i = 0; i < mPatch.num_sources; i++) {
6995 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6996 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6997 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6998 ARRAY_SIZE(sDeviceNameToEnumTable),
6999 mPatch.sources[i].ext.device.type));
7000 } else {
7001 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7002 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7003 }
7004 result.append(buffer);
7005 }
7006 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7007 result.append(buffer);
7008 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7009 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7010 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7011 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7012 ARRAY_SIZE(sDeviceNameToEnumTable),
7013 mPatch.sinks[i].ext.device.type));
7014 } else {
7015 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7016 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7017 }
7018 result.append(buffer);
7019 }
7020
7021 write(fd, result.string(), result.size());
7022 return NO_ERROR;
7023}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007024
7025// --- audio_policy.conf file parsing
7026
Eric Laurent5dbe4712014-09-19 19:04:57 -07007027uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007028{
7029 uint32_t flag = 0;
7030
7031 // it is OK to cast name to non const here as we are not going to use it after
7032 // strtok() modifies it
7033 char *flagName = strtok(name, "|");
7034 while (flagName != NULL) {
7035 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007036 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7037 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007038 flagName);
7039 }
7040 flagName = strtok(NULL, "|");
7041 }
7042 //force direct flag if offload flag is set: offloading implies a direct output stream
7043 // and all common behaviors are driven by checking only the direct flag
7044 // this should normally be set appropriately in the policy configuration file
7045 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7046 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7047 }
7048
Eric Laurent5dbe4712014-09-19 19:04:57 -07007049 return flag;
7050}
7051
7052uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7053{
7054 uint32_t flag = 0;
7055
7056 // it is OK to cast name to non const here as we are not going to use it after
7057 // strtok() modifies it
7058 char *flagName = strtok(name, "|");
7059 while (flagName != NULL) {
7060 if (strlen(flagName) != 0) {
7061 flag |= stringToEnum(sInputFlagNameToEnumTable,
7062 ARRAY_SIZE(sInputFlagNameToEnumTable),
7063 flagName);
7064 }
7065 flagName = strtok(NULL, "|");
7066 }
7067 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007068}
7069
Eric Laurente0720872014-03-11 09:30:41 -07007070audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007071{
7072 uint32_t device = 0;
7073
7074 char *devName = strtok(name, "|");
7075 while (devName != NULL) {
7076 if (strlen(devName) != 0) {
7077 device |= stringToEnum(sDeviceNameToEnumTable,
7078 ARRAY_SIZE(sDeviceNameToEnumTable),
7079 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007080 }
Eric Laurente552edb2014-03-10 17:42:56 -07007081 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007082 }
Eric Laurente552edb2014-03-10 17:42:56 -07007083 return device;
7084}
7085
Eric Laurente0720872014-03-11 09:30:41 -07007086void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007087{
Eric Laurente552edb2014-03-10 17:42:56 -07007088 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007089 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007090 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007091
Eric Laurent1afeecb2014-05-14 08:52:28 -07007092 node = config_find(root, DEVICES_TAG);
7093 if (node != NULL) {
7094 node = node->first_child;
7095 while (node) {
7096 ALOGV("loadHwModule() loading device %s", node->name);
7097 status_t tmpStatus = module->loadDevice(node);
7098 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7099 status = tmpStatus;
7100 }
7101 node = node->next;
7102 }
7103 }
7104 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007105 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007106 node = node->first_child;
7107 while (node) {
7108 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007109 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007110 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7111 status = tmpStatus;
7112 }
7113 node = node->next;
7114 }
7115 }
7116 node = config_find(root, INPUTS_TAG);
7117 if (node != NULL) {
7118 node = node->first_child;
7119 while (node) {
7120 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007121 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007122 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7123 status = tmpStatus;
7124 }
7125 node = node->next;
7126 }
7127 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007128 loadGlobalConfig(root, module);
7129
Eric Laurente552edb2014-03-10 17:42:56 -07007130 if (status == NO_ERROR) {
7131 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007132 }
7133}
7134
Eric Laurente0720872014-03-11 09:30:41 -07007135void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007136{
7137 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7138 if (node == NULL) {
7139 return;
7140 }
7141
7142 node = node->first_child;
7143 while (node) {
7144 ALOGV("loadHwModules() loading module %s", node->name);
7145 loadHwModule(node);
7146 node = node->next;
7147 }
7148}
7149
Eric Laurent1f2f2232014-06-02 12:01:23 -07007150void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007151{
7152 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007153
Eric Laurente552edb2014-03-10 17:42:56 -07007154 if (node == NULL) {
7155 return;
7156 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007157 DeviceVector declaredDevices;
7158 if (module != NULL) {
7159 declaredDevices = module->mDeclaredDevices;
7160 }
7161
Eric Laurente552edb2014-03-10 17:42:56 -07007162 node = node->first_child;
7163 while (node) {
7164 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007165 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7166 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007167 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7168 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007169 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007170 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007171 ARRAY_SIZE(sDeviceNameToEnumTable),
7172 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007173 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007174 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007175 } else {
7176 ALOGW("loadGlobalConfig() default device not specified");
7177 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007178 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007179 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007180 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7181 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007182 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007183 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7184 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7185 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007186 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7187 uint32_t major, minor;
7188 sscanf((char *)node->value, "%u.%u", &major, &minor);
7189 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7190 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7191 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007192 }
7193 node = node->next;
7194 }
7195}
7196
Eric Laurente0720872014-03-11 09:30:41 -07007197status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007198{
7199 cnode *root;
7200 char *data;
7201
7202 data = (char *)load_file(path, NULL);
7203 if (data == NULL) {
7204 return -ENODEV;
7205 }
7206 root = config_node("", "");
7207 config_load(root, data);
7208
Eric Laurente552edb2014-03-10 17:42:56 -07007209 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007210 // legacy audio_policy.conf files have one global_configuration section
7211 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007212 config_free(root);
7213 free(root);
7214 free(data);
7215
7216 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7217
7218 return NO_ERROR;
7219}
7220
Eric Laurente0720872014-03-11 09:30:41 -07007221void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007222{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007223 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007224 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007225 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7226 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007227 mAvailableOutputDevices.add(mDefaultOutputDevice);
7228 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007229
7230 module = new HwModule("primary");
7231
Eric Laurent1afeecb2014-05-14 08:52:28 -07007232 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007233 profile->mSamplingRates.add(44100);
7234 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7235 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007236 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007237 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7238 module->mOutputProfiles.add(profile);
7239
Eric Laurent1afeecb2014-05-14 08:52:28 -07007240 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007241 profile->mSamplingRates.add(8000);
7242 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7243 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007244 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007245 module->mInputProfiles.add(profile);
7246
7247 mHwModules.add(module);
7248}
7249
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007250audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7251{
7252 // flags to stream type mapping
7253 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7254 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7255 }
7256 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7257 return AUDIO_STREAM_BLUETOOTH_SCO;
7258 }
7259
7260 // usage to stream type mapping
7261 switch (attr->usage) {
7262 case AUDIO_USAGE_MEDIA:
7263 case AUDIO_USAGE_GAME:
7264 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7265 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7266 return AUDIO_STREAM_MUSIC;
7267 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7268 return AUDIO_STREAM_SYSTEM;
7269 case AUDIO_USAGE_VOICE_COMMUNICATION:
7270 return AUDIO_STREAM_VOICE_CALL;
7271
7272 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7273 return AUDIO_STREAM_DTMF;
7274
7275 case AUDIO_USAGE_ALARM:
7276 return AUDIO_STREAM_ALARM;
7277 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7278 return AUDIO_STREAM_RING;
7279
7280 case AUDIO_USAGE_NOTIFICATION:
7281 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7282 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7283 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7284 case AUDIO_USAGE_NOTIFICATION_EVENT:
7285 return AUDIO_STREAM_NOTIFICATION;
7286
7287 case AUDIO_USAGE_UNKNOWN:
7288 default:
7289 return AUDIO_STREAM_MUSIC;
7290 }
7291}
Eric Laurente552edb2014-03-10 17:42:56 -07007292}; // namespace android