blob: 54f1ea1e8ecc14ba6feaa4e00ee3931775b34ead [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
933 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
934 audio_channel_count_from_out_mask(channelMask) <= 2) {
935 goto non_direct_output;
936 }
937
Eric Laurente552edb2014-03-10 17:42:56 -0700938 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
939 // creating an offloaded track and tearing it down immediately after start when audioflinger
940 // detects there is an active non offloadable effect.
941 // FIXME: We should check the audio session here but we do not have it in this context.
942 // This may prevent offloading in rare situations where effects are left active by apps
943 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700944
Eric Laurente552edb2014-03-10 17:42:56 -0700945 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
946 !isNonOffloadableEffectEnabled()) {
947 profile = getProfileForDirectOutput(device,
948 samplingRate,
949 format,
950 channelMask,
951 (audio_output_flags_t)flags);
952 }
953
Eric Laurent1c333e22014-05-20 10:48:17 -0700954 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700955 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700956
957 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700958 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700959 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
960 outputDesc = desc;
961 // reuse direct output if currently open and configured with same parameters
962 if ((samplingRate == outputDesc->mSamplingRate) &&
963 (format == outputDesc->mFormat) &&
964 (channelMask == outputDesc->mChannelMask)) {
965 outputDesc->mDirectOpenCount++;
966 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
967 return mOutputs.keyAt(i);
968 }
969 }
970 }
971 // close direct output if currently open and configured with different parameters
972 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700973 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700974 }
975 outputDesc = new AudioOutputDescriptor(profile);
976 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700977 outputDesc->mLatency = 0;
978 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700979 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
980 config.sample_rate = samplingRate;
981 config.channel_mask = channelMask;
982 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700983 if (offloadInfo != NULL) {
984 config.offload_info = *offloadInfo;
985 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700986 status = mpClientInterface->openOutput(profile->mModule->mHandle,
987 &output,
988 &config,
989 &outputDesc->mDevice,
990 String8(""),
991 &outputDesc->mLatency,
992 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700993
994 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700995 if (status != NO_ERROR ||
996 (samplingRate != 0 && samplingRate != config.sample_rate) ||
997 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
998 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700999 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1000 "format %d %d, channelMask %04x %04x", output, samplingRate,
1001 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1002 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001003 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001004 mpClientInterface->closeOutput(output);
1005 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001006 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001007 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001008 outputDesc->mSamplingRate = config.sample_rate;
1009 outputDesc->mChannelMask = config.channel_mask;
1010 outputDesc->mFormat = config.format;
1011 outputDesc->mRefCount[stream] = 0;
1012 outputDesc->mStopTime[stream] = 0;
1013 outputDesc->mDirectOpenCount = 1;
1014
Eric Laurente552edb2014-03-10 17:42:56 -07001015 audio_io_handle_t srcOutput = getOutputForEffect();
1016 addOutput(output, outputDesc);
1017 audio_io_handle_t dstOutput = getOutputForEffect();
1018 if (dstOutput == output) {
1019 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1020 }
1021 mPreviousOutputs = mOutputs;
1022 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001023 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001024 return output;
1025 }
1026
Eric Laurentb732cf52014-09-24 19:08:21 -07001027non_direct_output:
1028
Eric Laurente552edb2014-03-10 17:42:56 -07001029 // ignoring channel mask due to downmix capability in mixer
1030
1031 // open a non direct output
1032
1033 // for non direct outputs, only PCM is supported
1034 if (audio_is_linear_pcm(format)) {
1035 // get which output is suitable for the specified stream. The actual
1036 // routing change will happen when startOutput() will be called
1037 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1038
Eric Laurent8838a382014-09-08 16:44:28 -07001039 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1040 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1041 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001042 }
1043 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1044 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1045
1046 ALOGV("getOutput() returns output %d", output);
1047
1048 return output;
1049}
1050
Eric Laurente0720872014-03-11 09:30:41 -07001051audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001052 audio_output_flags_t flags,
1053 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001054{
1055 // select one output among several that provide a path to a particular device or set of
1056 // devices (the list was previously build by getOutputsForDevice()).
1057 // The priority is as follows:
1058 // 1: the output with the highest number of requested policy flags
1059 // 2: the primary output
1060 // 3: the first output in the list
1061
1062 if (outputs.size() == 0) {
1063 return 0;
1064 }
1065 if (outputs.size() == 1) {
1066 return outputs[0];
1067 }
1068
1069 int maxCommonFlags = 0;
1070 audio_io_handle_t outputFlags = 0;
1071 audio_io_handle_t outputPrimary = 0;
1072
1073 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001074 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001075 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001076 // if a valid format is specified, skip output if not compatible
1077 if (format != AUDIO_FORMAT_INVALID) {
1078 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1079 if (format != outputDesc->mFormat) {
1080 continue;
1081 }
1082 } else if (!audio_is_linear_pcm(format)) {
1083 continue;
1084 }
1085 }
1086
Eric Laurent3b73df72014-03-11 09:06:29 -07001087 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001088 if (commonFlags > maxCommonFlags) {
1089 outputFlags = outputs[i];
1090 maxCommonFlags = commonFlags;
1091 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1092 }
1093 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1094 outputPrimary = outputs[i];
1095 }
1096 }
1097 }
1098
1099 if (outputFlags != 0) {
1100 return outputFlags;
1101 }
1102 if (outputPrimary != 0) {
1103 return outputPrimary;
1104 }
1105
1106 return outputs[0];
1107}
1108
Eric Laurente0720872014-03-11 09:30:41 -07001109status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001110 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001111 int session)
1112{
1113 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1114 ssize_t index = mOutputs.indexOfKey(output);
1115 if (index < 0) {
1116 ALOGW("startOutput() unknown output %d", output);
1117 return BAD_VALUE;
1118 }
1119
Eric Laurent1f2f2232014-06-02 12:01:23 -07001120 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001121
1122 // increment usage count for this stream on the requested output:
1123 // NOTE that the usage count is the same for duplicated output and hardware output which is
1124 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1125 outputDesc->changeRefCount(stream, 1);
1126
1127 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001128 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001129 routing_strategy strategy = getStrategy(stream);
1130 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1131 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1132 uint32_t waitMs = 0;
1133 bool force = false;
1134 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001135 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001136 if (desc != outputDesc) {
1137 // force a device change if any other output is managed by the same hw
1138 // module and has a current device selection that differs from selected device.
1139 // In this case, the audio HAL must receive the new device selection so that it can
1140 // change the device currently selected by the other active output.
1141 if (outputDesc->sharesHwModuleWith(desc) &&
1142 desc->device() != newDevice) {
1143 force = true;
1144 }
1145 // wait for audio on other active outputs to be presented when starting
1146 // a notification so that audio focus effect can propagate.
1147 uint32_t latency = desc->latency();
1148 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1149 waitMs = latency;
1150 }
1151 }
1152 }
1153 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1154
1155 // handle special case for sonification while in call
1156 if (isInCall()) {
1157 handleIncallSonification(stream, true, false);
1158 }
1159
1160 // apply volume rules for current stream and device if necessary
1161 checkAndSetVolume(stream,
1162 mStreams[stream].getVolumeIndex(newDevice),
1163 output,
1164 newDevice);
1165
1166 // update the outputs if starting an output with a stream that can affect notification
1167 // routing
1168 handleNotificationRoutingForStream(stream);
1169 if (waitMs > muteWaitMs) {
1170 usleep((waitMs - muteWaitMs) * 2 * 1000);
1171 }
1172 }
1173 return NO_ERROR;
1174}
1175
1176
Eric Laurente0720872014-03-11 09:30:41 -07001177status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001178 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001179 int session)
1180{
1181 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1182 ssize_t index = mOutputs.indexOfKey(output);
1183 if (index < 0) {
1184 ALOGW("stopOutput() unknown output %d", output);
1185 return BAD_VALUE;
1186 }
1187
Eric Laurent1f2f2232014-06-02 12:01:23 -07001188 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001189
1190 // handle special case for sonification while in call
1191 if (isInCall()) {
1192 handleIncallSonification(stream, false, false);
1193 }
1194
1195 if (outputDesc->mRefCount[stream] > 0) {
1196 // decrement usage count of this stream on the output
1197 outputDesc->changeRefCount(stream, -1);
1198 // store time at which the stream was stopped - see isStreamActive()
1199 if (outputDesc->mRefCount[stream] == 0) {
1200 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001201 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001202 // delay the device switch by twice the latency because stopOutput() is executed when
1203 // the track stop() command is received and at that time the audio track buffer can
1204 // still contain data that needs to be drained. The latency only covers the audio HAL
1205 // and kernel buffers. Also the latency does not always include additional delay in the
1206 // audio path (audio DSP, CODEC ...)
1207 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1208
1209 // force restoring the device selection on other active outputs if it differs from the
1210 // one being selected for this output
1211 for (size_t i = 0; i < mOutputs.size(); i++) {
1212 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001213 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001214 if (curOutput != output &&
1215 desc->isActive() &&
1216 outputDesc->sharesHwModuleWith(desc) &&
1217 (newDevice != desc->device())) {
1218 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001219 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001220 true,
1221 outputDesc->mLatency*2);
1222 }
1223 }
1224 // update the outputs if stopping one with a stream that can affect notification routing
1225 handleNotificationRoutingForStream(stream);
1226 }
1227 return NO_ERROR;
1228 } else {
1229 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1230 return INVALID_OPERATION;
1231 }
1232}
1233
Eric Laurente0720872014-03-11 09:30:41 -07001234void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001235{
1236 ALOGV("releaseOutput() %d", output);
1237 ssize_t index = mOutputs.indexOfKey(output);
1238 if (index < 0) {
1239 ALOGW("releaseOutput() releasing unknown output %d", output);
1240 return;
1241 }
1242
1243#ifdef AUDIO_POLICY_TEST
1244 int testIndex = testOutputIndex(output);
1245 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001246 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001247 if (outputDesc->isActive()) {
1248 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001249 mOutputs.removeItem(output);
1250 mTestOutputs[testIndex] = 0;
1251 }
1252 return;
1253 }
1254#endif //AUDIO_POLICY_TEST
1255
Eric Laurent1f2f2232014-06-02 12:01:23 -07001256 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001257 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001258 if (desc->mDirectOpenCount <= 0) {
1259 ALOGW("releaseOutput() invalid open count %d for output %d",
1260 desc->mDirectOpenCount, output);
1261 return;
1262 }
1263 if (--desc->mDirectOpenCount == 0) {
1264 closeOutput(output);
1265 // If effects where present on the output, audioflinger moved them to the primary
1266 // output by default: move them back to the appropriate output.
1267 audio_io_handle_t dstOutput = getOutputForEffect();
1268 if (dstOutput != mPrimaryOutput) {
1269 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1270 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001271 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001272 }
1273 }
1274}
1275
1276
Eric Laurente0720872014-03-11 09:30:41 -07001277audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001278 uint32_t samplingRate,
1279 audio_format_t format,
1280 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001281 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001282 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001283{
Eric Laurent4dc68062014-07-28 17:26:49 -07001284 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001285 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001286 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001287
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001288 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001289
1290 if (device == AUDIO_DEVICE_NONE) {
1291 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001292 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001293 }
1294
1295 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001296 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001297 case AUDIO_SOURCE_VOICE_UPLINK:
1298 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1299 break;
1300 case AUDIO_SOURCE_VOICE_DOWNLINK:
1301 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1302 break;
1303 case AUDIO_SOURCE_VOICE_CALL:
1304 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1305 break;
1306 default:
1307 break;
1308 }
1309
Eric Laurent5dbe4712014-09-19 19:04:57 -07001310 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1311 bool isSoundTrigger = false;
1312 audio_source_t halInputSource = inputSource;
1313 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1314 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1315 if (index >= 0) {
1316 input = mSoundTriggerSessions.valueFor(session);
1317 isSoundTrigger = true;
1318 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1319 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1320 } else {
1321 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1322 }
1323 }
1324
Eric Laurent1c333e22014-05-20 10:48:17 -07001325 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001326 samplingRate,
1327 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001328 channelMask,
1329 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001330 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001331 //retry without flags
1332 audio_input_flags_t log_flags = flags;
1333 flags = AUDIO_INPUT_FLAG_NONE;
1334 profile = getInputProfile(device,
1335 samplingRate,
1336 format,
1337 channelMask,
1338 flags);
1339 if (profile == 0) {
1340 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1341 "channelMask 0x%X, flags %#x",
1342 device, samplingRate, format, channelMask, log_flags);
1343 return AUDIO_IO_HANDLE_NONE;
1344 }
Eric Laurente552edb2014-03-10 17:42:56 -07001345 }
1346
1347 if (profile->mModule->mHandle == 0) {
1348 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001349 return AUDIO_IO_HANDLE_NONE;
1350 }
1351
1352 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1353 config.sample_rate = samplingRate;
1354 config.channel_mask = channelMask;
1355 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001356
Eric Laurentcf2c0212014-07-25 16:20:43 -07001357 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1358 &input,
1359 &config,
1360 &device,
1361 String8(""),
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001362 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001363 flags);
1364
1365 // only accept input with the exact requested set of parameters
1366 if (status != NO_ERROR ||
1367 (samplingRate != config.sample_rate) ||
1368 (format != config.format) ||
1369 (channelMask != config.channel_mask)) {
1370 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1371 samplingRate, format, channelMask);
1372 if (input != AUDIO_IO_HANDLE_NONE) {
1373 mpClientInterface->closeInput(input);
1374 }
1375 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001376 }
1377
Eric Laurent1f2f2232014-06-02 12:01:23 -07001378 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001379 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001380 inputDesc->mRefCount = 0;
1381 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001382 inputDesc->mSamplingRate = samplingRate;
1383 inputDesc->mFormat = format;
1384 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001385 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001386 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001387 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001388
Eric Laurentd4692962014-05-05 18:13:44 -07001389 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001390 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001391 return input;
1392}
1393
Eric Laurent4dc68062014-07-28 17:26:49 -07001394status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1395 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001396{
1397 ALOGV("startInput() input %d", input);
1398 ssize_t index = mInputs.indexOfKey(input);
1399 if (index < 0) {
1400 ALOGW("startInput() unknown input %d", input);
1401 return BAD_VALUE;
1402 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001403 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001404
Eric Laurent4dc68062014-07-28 17:26:49 -07001405 index = inputDesc->mSessions.indexOf(session);
1406 if (index < 0) {
1407 ALOGW("startInput() unknown session %d on input %d", session, input);
1408 return BAD_VALUE;
1409 }
1410
Glenn Kasten74a8e252014-07-24 14:09:55 -07001411 // virtual input devices are compatible with other input devices
1412 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1413
1414 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001415 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001416 if (activeInput != 0 && activeInput != input) {
1417
1418 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1419 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001420 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001421 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001422 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001423 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1424 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001425 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001426 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001427 return INVALID_OPERATION;
1428 }
1429 }
1430 }
1431
Glenn Kasten74a8e252014-07-24 14:09:55 -07001432 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001433 if (activeInputsCount() == 0) {
1434 SoundTrigger::setCaptureState(true);
1435 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001436 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001437
Glenn Kasten74a8e252014-07-24 14:09:55 -07001438 // Automatically enable the remote submix output when input is started.
1439 // For remote submix (a virtual device), we open only one input per capture request.
1440 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1441 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1442 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1443 }
Eric Laurente552edb2014-03-10 17:42:56 -07001444 }
1445
Eric Laurente552edb2014-03-10 17:42:56 -07001446 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1447
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001448 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001449 return NO_ERROR;
1450}
1451
Eric Laurent4dc68062014-07-28 17:26:49 -07001452status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1453 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001454{
1455 ALOGV("stopInput() input %d", input);
1456 ssize_t index = mInputs.indexOfKey(input);
1457 if (index < 0) {
1458 ALOGW("stopInput() unknown input %d", input);
1459 return BAD_VALUE;
1460 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001461 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001462
Eric Laurent4dc68062014-07-28 17:26:49 -07001463 index = inputDesc->mSessions.indexOf(session);
1464 if (index < 0) {
1465 ALOGW("stopInput() unknown session %d on input %d", session, input);
1466 return BAD_VALUE;
1467 }
1468
Eric Laurente552edb2014-03-10 17:42:56 -07001469 if (inputDesc->mRefCount == 0) {
1470 ALOGW("stopInput() input %d already stopped", input);
1471 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001472 }
1473
1474 inputDesc->mRefCount--;
1475 if (inputDesc->mRefCount == 0) {
1476
Eric Laurente552edb2014-03-10 17:42:56 -07001477 // automatically disable the remote submix output when input is stopped
1478 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1479 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001480 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001481 }
1482
Eric Laurent1c333e22014-05-20 10:48:17 -07001483 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001484
1485 if (activeInputsCount() == 0) {
1486 SoundTrigger::setCaptureState(false);
1487 }
Eric Laurente552edb2014-03-10 17:42:56 -07001488 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001489 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001490}
1491
Eric Laurent4dc68062014-07-28 17:26:49 -07001492void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1493 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001494{
1495 ALOGV("releaseInput() %d", input);
1496 ssize_t index = mInputs.indexOfKey(input);
1497 if (index < 0) {
1498 ALOGW("releaseInput() releasing unknown input %d", input);
1499 return;
1500 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001501 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1502 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001503
1504 index = inputDesc->mSessions.indexOf(session);
1505 if (index < 0) {
1506 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1507 return;
1508 }
1509 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001510 if (inputDesc->mOpenRefCount == 0) {
1511 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1512 return;
1513 }
1514 inputDesc->mOpenRefCount--;
1515 if (inputDesc->mOpenRefCount > 0) {
1516 ALOGV("releaseInput() exit > 0");
1517 return;
1518 }
1519
Eric Laurent05b90f82014-08-27 15:32:29 -07001520 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001521 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001522 ALOGV("releaseInput() exit");
1523}
1524
Eric Laurentd4692962014-05-05 18:13:44 -07001525void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001526 bool patchRemoved = false;
1527
Eric Laurentd4692962014-05-05 18:13:44 -07001528 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001529 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1530 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1531 if (patch_index >= 0) {
1532 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1533 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1534 mAudioPatches.removeItemsAt(patch_index);
1535 patchRemoved = true;
1536 }
Eric Laurentd4692962014-05-05 18:13:44 -07001537 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1538 }
1539 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001540 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001541
1542 if (patchRemoved) {
1543 mpClientInterface->onAudioPatchListUpdate();
1544 }
Eric Laurentd4692962014-05-05 18:13:44 -07001545}
1546
Eric Laurente0720872014-03-11 09:30:41 -07001547void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001548 int indexMin,
1549 int indexMax)
1550{
1551 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1552 if (indexMin < 0 || indexMin >= indexMax) {
1553 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1554 return;
1555 }
1556 mStreams[stream].mIndexMin = indexMin;
1557 mStreams[stream].mIndexMax = indexMax;
1558}
1559
Eric Laurente0720872014-03-11 09:30:41 -07001560status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001561 int index,
1562 audio_devices_t device)
1563{
1564
1565 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1566 return BAD_VALUE;
1567 }
1568 if (!audio_is_output_device(device)) {
1569 return BAD_VALUE;
1570 }
1571
1572 // Force max volume if stream cannot be muted
1573 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1574
1575 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1576 stream, device, index);
1577
1578 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1579 // clear all device specific values
1580 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1581 mStreams[stream].mIndexCur.clear();
1582 }
1583 mStreams[stream].mIndexCur.add(device, index);
1584
1585 // compute and apply stream volume on all outputs according to connected device
1586 status_t status = NO_ERROR;
1587 for (size_t i = 0; i < mOutputs.size(); i++) {
1588 audio_devices_t curDevice =
1589 getDeviceForVolume(mOutputs.valueAt(i)->device());
1590 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1591 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1592 if (volStatus != NO_ERROR) {
1593 status = volStatus;
1594 }
1595 }
1596 }
1597 return status;
1598}
1599
Eric Laurente0720872014-03-11 09:30:41 -07001600status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001601 int *index,
1602 audio_devices_t device)
1603{
1604 if (index == NULL) {
1605 return BAD_VALUE;
1606 }
1607 if (!audio_is_output_device(device)) {
1608 return BAD_VALUE;
1609 }
1610 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1611 // the strategy the stream belongs to.
1612 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1613 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1614 }
1615 device = getDeviceForVolume(device);
1616
1617 *index = mStreams[stream].getVolumeIndex(device);
1618 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1619 return NO_ERROR;
1620}
1621
Eric Laurente0720872014-03-11 09:30:41 -07001622audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001623 const SortedVector<audio_io_handle_t>& outputs)
1624{
1625 // select one output among several suitable for global effects.
1626 // The priority is as follows:
1627 // 1: An offloaded output. If the effect ends up not being offloadable,
1628 // AudioFlinger will invalidate the track and the offloaded output
1629 // will be closed causing the effect to be moved to a PCM output.
1630 // 2: A deep buffer output
1631 // 3: the first output in the list
1632
1633 if (outputs.size() == 0) {
1634 return 0;
1635 }
1636
1637 audio_io_handle_t outputOffloaded = 0;
1638 audio_io_handle_t outputDeepBuffer = 0;
1639
1640 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001641 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001642 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001643 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1644 outputOffloaded = outputs[i];
1645 }
1646 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1647 outputDeepBuffer = outputs[i];
1648 }
1649 }
1650
1651 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1652 outputOffloaded, outputDeepBuffer);
1653 if (outputOffloaded != 0) {
1654 return outputOffloaded;
1655 }
1656 if (outputDeepBuffer != 0) {
1657 return outputDeepBuffer;
1658 }
1659
1660 return outputs[0];
1661}
1662
Eric Laurente0720872014-03-11 09:30:41 -07001663audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001664{
1665 // apply simple rule where global effects are attached to the same output as MUSIC streams
1666
Eric Laurent3b73df72014-03-11 09:06:29 -07001667 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001668 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1669 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1670
1671 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1672 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1673 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1674
1675 return output;
1676}
1677
Eric Laurente0720872014-03-11 09:30:41 -07001678status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001679 audio_io_handle_t io,
1680 uint32_t strategy,
1681 int session,
1682 int id)
1683{
1684 ssize_t index = mOutputs.indexOfKey(io);
1685 if (index < 0) {
1686 index = mInputs.indexOfKey(io);
1687 if (index < 0) {
1688 ALOGW("registerEffect() unknown io %d", io);
1689 return INVALID_OPERATION;
1690 }
1691 }
1692
1693 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1694 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1695 desc->name, desc->memoryUsage);
1696 return INVALID_OPERATION;
1697 }
1698 mTotalEffectsMemory += desc->memoryUsage;
1699 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1700 desc->name, io, strategy, session, id);
1701 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1702
Eric Laurent1f2f2232014-06-02 12:01:23 -07001703 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1704 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1705 effectDesc->mIo = io;
1706 effectDesc->mStrategy = (routing_strategy)strategy;
1707 effectDesc->mSession = session;
1708 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001709
Eric Laurent1f2f2232014-06-02 12:01:23 -07001710 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001711
1712 return NO_ERROR;
1713}
1714
Eric Laurente0720872014-03-11 09:30:41 -07001715status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001716{
1717 ssize_t index = mEffects.indexOfKey(id);
1718 if (index < 0) {
1719 ALOGW("unregisterEffect() unknown effect ID %d", id);
1720 return INVALID_OPERATION;
1721 }
1722
Eric Laurent1f2f2232014-06-02 12:01:23 -07001723 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001724
Eric Laurent1f2f2232014-06-02 12:01:23 -07001725 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001726
Eric Laurent1f2f2232014-06-02 12:01:23 -07001727 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001728 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001729 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1730 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001731 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001732 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001733 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001734 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001735
1736 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001737
1738 return NO_ERROR;
1739}
1740
Eric Laurente0720872014-03-11 09:30:41 -07001741status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001742{
1743 ssize_t index = mEffects.indexOfKey(id);
1744 if (index < 0) {
1745 ALOGW("unregisterEffect() unknown effect ID %d", id);
1746 return INVALID_OPERATION;
1747 }
1748
1749 return setEffectEnabled(mEffects.valueAt(index), enabled);
1750}
1751
Eric Laurent1f2f2232014-06-02 12:01:23 -07001752status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001753{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001754 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001755 ALOGV("setEffectEnabled(%s) effect already %s",
1756 enabled?"true":"false", enabled?"enabled":"disabled");
1757 return INVALID_OPERATION;
1758 }
1759
1760 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001761 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001762 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001763 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001764 return INVALID_OPERATION;
1765 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001766 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001767 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1768 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001769 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001770 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001771 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1772 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001773 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001774 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001775 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1776 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001777 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001778 return NO_ERROR;
1779}
1780
Eric Laurente0720872014-03-11 09:30:41 -07001781bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001782{
1783 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001784 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1785 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1786 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001787 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001788 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001789 return true;
1790 }
1791 }
1792 return false;
1793}
1794
Eric Laurente0720872014-03-11 09:30:41 -07001795bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001796{
1797 nsecs_t sysTime = systemTime();
1798 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001799 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001800 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001801 return true;
1802 }
1803 }
1804 return false;
1805}
1806
Eric Laurente0720872014-03-11 09:30:41 -07001807bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001808 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001809{
1810 nsecs_t sysTime = systemTime();
1811 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001812 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001813 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001814 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001815 return true;
1816 }
1817 }
1818 return false;
1819}
1820
Eric Laurente0720872014-03-11 09:30:41 -07001821bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001822{
1823 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001824 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001825 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001826 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001827 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1828 && (inputDescriptor->mRefCount > 0)) {
1829 return true;
1830 }
1831 }
1832 return false;
1833}
1834
1835
Eric Laurente0720872014-03-11 09:30:41 -07001836status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001837{
1838 const size_t SIZE = 256;
1839 char buffer[SIZE];
1840 String8 result;
1841
1842 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1843 result.append(buffer);
1844
1845 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1846 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001847 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1848 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001849 snprintf(buffer, SIZE, " Force use for communications %d\n",
1850 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001851 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001852 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001853 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001854 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001855 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001856 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001857 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001858 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001859 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001860 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1861 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1862 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001863
Eric Laurent3a4311c2014-03-17 12:00:47 -07001864 snprintf(buffer, SIZE, " Available output devices:\n");
1865 result.append(buffer);
1866 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001867 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001868 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001869 }
1870 snprintf(buffer, SIZE, "\n Available input devices:\n");
1871 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001872 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001873 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001874 }
Eric Laurente552edb2014-03-10 17:42:56 -07001875
1876 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1877 write(fd, buffer, strlen(buffer));
1878 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001879 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001880 write(fd, buffer, strlen(buffer));
1881 mHwModules[i]->dump(fd);
1882 }
1883
1884 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1885 write(fd, buffer, strlen(buffer));
1886 for (size_t i = 0; i < mOutputs.size(); i++) {
1887 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1888 write(fd, buffer, strlen(buffer));
1889 mOutputs.valueAt(i)->dump(fd);
1890 }
1891
1892 snprintf(buffer, SIZE, "\nInputs dump:\n");
1893 write(fd, buffer, strlen(buffer));
1894 for (size_t i = 0; i < mInputs.size(); i++) {
1895 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1896 write(fd, buffer, strlen(buffer));
1897 mInputs.valueAt(i)->dump(fd);
1898 }
1899
1900 snprintf(buffer, SIZE, "\nStreams dump:\n");
1901 write(fd, buffer, strlen(buffer));
1902 snprintf(buffer, SIZE,
1903 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1904 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001905 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001906 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001907 write(fd, buffer, strlen(buffer));
1908 mStreams[i].dump(fd);
1909 }
1910
1911 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1912 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1913 write(fd, buffer, strlen(buffer));
1914
1915 snprintf(buffer, SIZE, "Registered effects:\n");
1916 write(fd, buffer, strlen(buffer));
1917 for (size_t i = 0; i < mEffects.size(); i++) {
1918 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1919 write(fd, buffer, strlen(buffer));
1920 mEffects.valueAt(i)->dump(fd);
1921 }
1922
Eric Laurent4d416952014-08-10 14:07:09 -07001923 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1924 write(fd, buffer, strlen(buffer));
1925 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1926 mAudioPatches[i]->dump(fd, 2, i);
1927 }
Eric Laurente552edb2014-03-10 17:42:56 -07001928
1929 return NO_ERROR;
1930}
1931
1932// This function checks for the parameters which can be offloaded.
1933// This can be enhanced depending on the capability of the DSP and policy
1934// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001935bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001936{
1937 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001938 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001939 offloadInfo.sample_rate, offloadInfo.channel_mask,
1940 offloadInfo.format,
1941 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1942 offloadInfo.has_video);
1943
1944 // Check if offload has been disabled
1945 char propValue[PROPERTY_VALUE_MAX];
1946 if (property_get("audio.offload.disable", propValue, "0")) {
1947 if (atoi(propValue) != 0) {
1948 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1949 return false;
1950 }
1951 }
1952
1953 // Check if stream type is music, then only allow offload as of now.
1954 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1955 {
1956 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1957 return false;
1958 }
1959
1960 //TODO: enable audio offloading with video when ready
1961 if (offloadInfo.has_video)
1962 {
1963 ALOGV("isOffloadSupported: has_video == true, returning false");
1964 return false;
1965 }
1966
1967 //If duration is less than minimum value defined in property, return false
1968 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1969 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1970 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1971 return false;
1972 }
1973 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1974 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1975 return false;
1976 }
1977
1978 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1979 // creating an offloaded track and tearing it down immediately after start when audioflinger
1980 // detects there is an active non offloadable effect.
1981 // FIXME: We should check the audio session here but we do not have it in this context.
1982 // This may prevent offloading in rare situations where effects are left active by apps
1983 // in the background.
1984 if (isNonOffloadableEffectEnabled()) {
1985 return false;
1986 }
1987
1988 // See if there is a profile to support this.
1989 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001990 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001991 offloadInfo.sample_rate,
1992 offloadInfo.format,
1993 offloadInfo.channel_mask,
1994 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001995 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1996 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001997}
1998
Eric Laurent6a94d692014-05-20 11:18:06 -07001999status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2000 audio_port_type_t type,
2001 unsigned int *num_ports,
2002 struct audio_port *ports,
2003 unsigned int *generation)
2004{
2005 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2006 generation == NULL) {
2007 return BAD_VALUE;
2008 }
2009 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2010 if (ports == NULL) {
2011 *num_ports = 0;
2012 }
2013
2014 size_t portsWritten = 0;
2015 size_t portsMax = *num_ports;
2016 *num_ports = 0;
2017 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2018 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2019 for (size_t i = 0;
2020 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2021 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2022 }
2023 *num_ports += mAvailableOutputDevices.size();
2024 }
2025 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2026 for (size_t i = 0;
2027 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2028 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2029 }
2030 *num_ports += mAvailableInputDevices.size();
2031 }
2032 }
2033 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2034 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2035 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2036 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2037 }
2038 *num_ports += mInputs.size();
2039 }
2040 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002041 size_t numOutputs = 0;
2042 for (size_t i = 0; i < mOutputs.size(); i++) {
2043 if (!mOutputs[i]->isDuplicated()) {
2044 numOutputs++;
2045 if (portsWritten < portsMax) {
2046 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2047 }
2048 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002049 }
Eric Laurent84c70242014-06-23 08:46:27 -07002050 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002051 }
2052 }
2053 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002054 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002055 return NO_ERROR;
2056}
2057
2058status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2059{
2060 return NO_ERROR;
2061}
2062
Eric Laurent1f2f2232014-06-02 12:01:23 -07002063sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002064 audio_port_handle_t id) const
2065{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002066 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002067 for (size_t i = 0; i < mOutputs.size(); i++) {
2068 outputDesc = mOutputs.valueAt(i);
2069 if (outputDesc->mId == id) {
2070 break;
2071 }
2072 }
2073 return outputDesc;
2074}
2075
Eric Laurent1f2f2232014-06-02 12:01:23 -07002076sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002077 audio_port_handle_t id) const
2078{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002079 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002080 for (size_t i = 0; i < mInputs.size(); i++) {
2081 inputDesc = mInputs.valueAt(i);
2082 if (inputDesc->mId == id) {
2083 break;
2084 }
2085 }
2086 return inputDesc;
2087}
2088
Eric Laurent1f2f2232014-06-02 12:01:23 -07002089sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2090 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002091{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002092 sp <HwModule> module;
2093
Eric Laurent6a94d692014-05-20 11:18:06 -07002094 for (size_t i = 0; i < mHwModules.size(); i++) {
2095 if (mHwModules[i]->mHandle == 0) {
2096 continue;
2097 }
2098 if (audio_is_output_device(device)) {
2099 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2100 {
2101 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2102 return mHwModules[i];
2103 }
2104 }
2105 } else {
2106 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2107 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2108 device & ~AUDIO_DEVICE_BIT_IN) {
2109 return mHwModules[i];
2110 }
2111 }
2112 }
2113 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002114 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002115}
2116
Eric Laurent1f2f2232014-06-02 12:01:23 -07002117sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002118{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002119 sp <HwModule> module;
2120
Eric Laurent1afeecb2014-05-14 08:52:28 -07002121 for (size_t i = 0; i < mHwModules.size(); i++)
2122 {
2123 if (strcmp(mHwModules[i]->mName, name) == 0) {
2124 return mHwModules[i];
2125 }
2126 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002127 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002128}
2129
Eric Laurentc2730ba2014-07-20 15:47:07 -07002130audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2131{
2132 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2133 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2134 return devices & mAvailableOutputDevices.types();
2135}
2136
2137audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2138{
2139 audio_module_handle_t primaryHandle =
2140 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2141 audio_devices_t devices = AUDIO_DEVICE_NONE;
2142 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2143 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2144 devices |= mAvailableInputDevices[i]->mDeviceType;
2145 }
2146 }
2147 return devices;
2148}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002149
Eric Laurent6a94d692014-05-20 11:18:06 -07002150status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2151 audio_patch_handle_t *handle,
2152 uid_t uid)
2153{
2154 ALOGV("createAudioPatch()");
2155
2156 if (handle == NULL || patch == NULL) {
2157 return BAD_VALUE;
2158 }
2159 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2160
Eric Laurent874c42872014-08-08 15:13:39 -07002161 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2162 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2163 return BAD_VALUE;
2164 }
2165 // only one source per audio patch supported for now
2166 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002167 return INVALID_OPERATION;
2168 }
Eric Laurent874c42872014-08-08 15:13:39 -07002169
2170 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002171 return INVALID_OPERATION;
2172 }
Eric Laurent874c42872014-08-08 15:13:39 -07002173 for (size_t i = 0; i < patch->num_sinks; i++) {
2174 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2175 return INVALID_OPERATION;
2176 }
2177 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002178
2179 sp<AudioPatch> patchDesc;
2180 ssize_t index = mAudioPatches.indexOfKey(*handle);
2181
Eric Laurent6a94d692014-05-20 11:18:06 -07002182 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2183 patch->sources[0].role,
2184 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002185#if LOG_NDEBUG == 0
2186 for (size_t i = 0; i < patch->num_sinks; i++) {
2187 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2188 patch->sinks[i].role,
2189 patch->sinks[i].type);
2190 }
2191#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002192
2193 if (index >= 0) {
2194 patchDesc = mAudioPatches.valueAt(index);
2195 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2196 mUidCached, patchDesc->mUid, uid);
2197 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2198 return INVALID_OPERATION;
2199 }
2200 } else {
2201 *handle = 0;
2202 }
2203
2204 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002205 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002206 if (outputDesc == NULL) {
2207 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2208 return BAD_VALUE;
2209 }
Eric Laurent84c70242014-06-23 08:46:27 -07002210 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2211 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002212 if (patchDesc != 0) {
2213 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2214 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2215 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2216 return BAD_VALUE;
2217 }
2218 }
Eric Laurent874c42872014-08-08 15:13:39 -07002219 DeviceVector devices;
2220 for (size_t i = 0; i < patch->num_sinks; i++) {
2221 // Only support mix to devices connection
2222 // TODO add support for mix to mix connection
2223 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2224 ALOGV("createAudioPatch() source mix but sink is not a device");
2225 return INVALID_OPERATION;
2226 }
2227 sp<DeviceDescriptor> devDesc =
2228 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2229 if (devDesc == 0) {
2230 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2231 return BAD_VALUE;
2232 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002233
Eric Laurent874c42872014-08-08 15:13:39 -07002234 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2235 patch->sources[0].sample_rate,
2236 NULL, // updatedSamplingRate
2237 patch->sources[0].format,
2238 patch->sources[0].channel_mask,
2239 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2240 ALOGV("createAudioPatch() profile not supported for device %08x",
2241 devDesc->mDeviceType);
2242 return INVALID_OPERATION;
2243 }
2244 devices.add(devDesc);
2245 }
2246 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002247 return INVALID_OPERATION;
2248 }
Eric Laurent874c42872014-08-08 15:13:39 -07002249
Eric Laurent6a94d692014-05-20 11:18:06 -07002250 // TODO: reconfigure output format and channels here
2251 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002252 devices.types(), outputDesc->mIoHandle);
2253 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002254 index = mAudioPatches.indexOfKey(*handle);
2255 if (index >= 0) {
2256 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2257 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2258 }
2259 patchDesc = mAudioPatches.valueAt(index);
2260 patchDesc->mUid = uid;
2261 ALOGV("createAudioPatch() success");
2262 } else {
2263 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2264 return INVALID_OPERATION;
2265 }
2266 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2267 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2268 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002269 // only one sink supported when connecting an input device to a mix
2270 if (patch->num_sinks > 1) {
2271 return INVALID_OPERATION;
2272 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002273 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002274 if (inputDesc == NULL) {
2275 return BAD_VALUE;
2276 }
2277 if (patchDesc != 0) {
2278 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2279 return BAD_VALUE;
2280 }
2281 }
2282 sp<DeviceDescriptor> devDesc =
2283 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2284 if (devDesc == 0) {
2285 return BAD_VALUE;
2286 }
2287
Eric Laurent84c70242014-06-23 08:46:27 -07002288 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002289 patch->sinks[0].sample_rate,
2290 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002291 patch->sinks[0].format,
2292 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002293 // FIXME for the parameter type,
2294 // and the NONE
2295 (audio_output_flags_t)
2296 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002297 return INVALID_OPERATION;
2298 }
2299 // TODO: reconfigure output format and channels here
2300 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002301 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002302 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002303 index = mAudioPatches.indexOfKey(*handle);
2304 if (index >= 0) {
2305 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2306 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2307 }
2308 patchDesc = mAudioPatches.valueAt(index);
2309 patchDesc->mUid = uid;
2310 ALOGV("createAudioPatch() success");
2311 } else {
2312 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2313 return INVALID_OPERATION;
2314 }
2315 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2316 // device to device connection
2317 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002318 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002319 return BAD_VALUE;
2320 }
2321 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002322 sp<DeviceDescriptor> srcDeviceDesc =
2323 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002324 if (srcDeviceDesc == 0) {
2325 return BAD_VALUE;
2326 }
Eric Laurent874c42872014-08-08 15:13:39 -07002327
Eric Laurent6a94d692014-05-20 11:18:06 -07002328 //update source and sink with our own data as the data passed in the patch may
2329 // be incomplete.
2330 struct audio_patch newPatch = *patch;
2331 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002332
Eric Laurent874c42872014-08-08 15:13:39 -07002333 for (size_t i = 0; i < patch->num_sinks; i++) {
2334 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2335 ALOGV("createAudioPatch() source device but one sink is not a device");
2336 return INVALID_OPERATION;
2337 }
2338
2339 sp<DeviceDescriptor> sinkDeviceDesc =
2340 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2341 if (sinkDeviceDesc == 0) {
2342 return BAD_VALUE;
2343 }
2344 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2345
2346 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2347 // only one sink supported when connected devices across HW modules
2348 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002349 return INVALID_OPERATION;
2350 }
Eric Laurent874c42872014-08-08 15:13:39 -07002351 SortedVector<audio_io_handle_t> outputs =
2352 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2353 mOutputs);
2354 // if the sink device is reachable via an opened output stream, request to go via
2355 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002356 audio_io_handle_t output = selectOutput(outputs,
2357 AUDIO_OUTPUT_FLAG_NONE,
2358 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002359 if (output != AUDIO_IO_HANDLE_NONE) {
2360 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2361 if (outputDesc->isDuplicated()) {
2362 return INVALID_OPERATION;
2363 }
2364 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2365 newPatch.num_sources = 2;
2366 }
Eric Laurent83b88082014-06-20 18:31:16 -07002367 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002368 }
2369 // TODO: check from routing capabilities in config file and other conflicting patches
2370
2371 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2372 if (index >= 0) {
2373 afPatchHandle = patchDesc->mAfPatchHandle;
2374 }
2375
2376 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2377 &afPatchHandle,
2378 0);
2379 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2380 status, afPatchHandle);
2381 if (status == NO_ERROR) {
2382 if (index < 0) {
2383 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2384 &newPatch, uid);
2385 addAudioPatch(patchDesc->mHandle, patchDesc);
2386 } else {
2387 patchDesc->mPatch = newPatch;
2388 }
2389 patchDesc->mAfPatchHandle = afPatchHandle;
2390 *handle = patchDesc->mHandle;
2391 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002392 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002393 } else {
2394 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2395 status);
2396 return INVALID_OPERATION;
2397 }
2398 } else {
2399 return BAD_VALUE;
2400 }
2401 } else {
2402 return BAD_VALUE;
2403 }
2404 return NO_ERROR;
2405}
2406
2407status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2408 uid_t uid)
2409{
2410 ALOGV("releaseAudioPatch() patch %d", handle);
2411
2412 ssize_t index = mAudioPatches.indexOfKey(handle);
2413
2414 if (index < 0) {
2415 return BAD_VALUE;
2416 }
2417 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2418 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2419 mUidCached, patchDesc->mUid, uid);
2420 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2421 return INVALID_OPERATION;
2422 }
2423
2424 struct audio_patch *patch = &patchDesc->mPatch;
2425 patchDesc->mUid = mUidCached;
2426 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002427 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002428 if (outputDesc == NULL) {
2429 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2430 return BAD_VALUE;
2431 }
2432
2433 setOutputDevice(outputDesc->mIoHandle,
2434 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2435 true,
2436 0,
2437 NULL);
2438 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2439 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002440 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002441 if (inputDesc == NULL) {
2442 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2443 return BAD_VALUE;
2444 }
2445 setInputDevice(inputDesc->mIoHandle,
2446 getNewInputDevice(inputDesc->mIoHandle),
2447 true,
2448 NULL);
2449 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2450 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2451 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2452 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2453 status, patchDesc->mAfPatchHandle);
2454 removeAudioPatch(patchDesc->mHandle);
2455 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002456 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002457 } else {
2458 return BAD_VALUE;
2459 }
2460 } else {
2461 return BAD_VALUE;
2462 }
2463 return NO_ERROR;
2464}
2465
2466status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2467 struct audio_patch *patches,
2468 unsigned int *generation)
2469{
2470 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2471 generation == NULL) {
2472 return BAD_VALUE;
2473 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002474 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002475 *num_patches, patches, mAudioPatches.size());
2476 if (patches == NULL) {
2477 *num_patches = 0;
2478 }
2479
2480 size_t patchesWritten = 0;
2481 size_t patchesMax = *num_patches;
2482 for (size_t i = 0;
2483 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2484 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2485 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002486 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002487 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2488 }
2489 *num_patches = mAudioPatches.size();
2490
2491 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002492 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002493 return NO_ERROR;
2494}
2495
Eric Laurente1715a42014-05-20 11:30:42 -07002496status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002497{
Eric Laurente1715a42014-05-20 11:30:42 -07002498 ALOGV("setAudioPortConfig()");
2499
2500 if (config == NULL) {
2501 return BAD_VALUE;
2502 }
2503 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2504 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002505 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2506 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002507 }
2508
Eric Laurenta121f902014-06-03 13:32:54 -07002509 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002510 if (config->type == AUDIO_PORT_TYPE_MIX) {
2511 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002512 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002513 if (outputDesc == NULL) {
2514 return BAD_VALUE;
2515 }
Eric Laurent84c70242014-06-23 08:46:27 -07002516 ALOG_ASSERT(!outputDesc->isDuplicated(),
2517 "setAudioPortConfig() called on duplicated output %d",
2518 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002519 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002520 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002521 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002522 if (inputDesc == NULL) {
2523 return BAD_VALUE;
2524 }
Eric Laurenta121f902014-06-03 13:32:54 -07002525 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002526 } else {
2527 return BAD_VALUE;
2528 }
2529 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2530 sp<DeviceDescriptor> deviceDesc;
2531 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2532 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2533 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2534 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2535 } else {
2536 return BAD_VALUE;
2537 }
2538 if (deviceDesc == NULL) {
2539 return BAD_VALUE;
2540 }
Eric Laurenta121f902014-06-03 13:32:54 -07002541 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002542 } else {
2543 return BAD_VALUE;
2544 }
2545
Eric Laurenta121f902014-06-03 13:32:54 -07002546 struct audio_port_config backupConfig;
2547 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2548 if (status == NO_ERROR) {
2549 struct audio_port_config newConfig;
2550 audioPortConfig->toAudioPortConfig(&newConfig, config);
2551 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002552 }
Eric Laurenta121f902014-06-03 13:32:54 -07002553 if (status != NO_ERROR) {
2554 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002555 }
Eric Laurente1715a42014-05-20 11:30:42 -07002556
2557 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002558}
2559
2560void AudioPolicyManager::clearAudioPatches(uid_t uid)
2561{
2562 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2563 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2564 if (patchDesc->mUid == uid) {
2565 // releaseAudioPatch() removes the patch from mAudioPatches
2566 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2567 i--;
2568 }
2569 }
2570 }
2571}
2572
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002573status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2574 audio_io_handle_t *ioHandle,
2575 audio_devices_t *device)
2576{
2577 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2578 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2579 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2580
2581 mSoundTriggerSessions.add(*session, *ioHandle);
2582
2583 return NO_ERROR;
2584}
2585
2586status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2587{
2588 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2589 if (index < 0) {
2590 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2591 return BAD_VALUE;
2592 }
2593
2594 mSoundTriggerSessions.removeItem(session);
2595 return NO_ERROR;
2596}
2597
Eric Laurent6a94d692014-05-20 11:18:06 -07002598status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2599 const sp<AudioPatch>& patch)
2600{
2601 ssize_t index = mAudioPatches.indexOfKey(handle);
2602
2603 if (index >= 0) {
2604 ALOGW("addAudioPatch() patch %d already in", handle);
2605 return ALREADY_EXISTS;
2606 }
2607 mAudioPatches.add(handle, patch);
2608 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2609 "sink handle %d",
2610 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2611 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2612 return NO_ERROR;
2613}
2614
2615status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2616{
2617 ssize_t index = mAudioPatches.indexOfKey(handle);
2618
2619 if (index < 0) {
2620 ALOGW("removeAudioPatch() patch %d not in", handle);
2621 return ALREADY_EXISTS;
2622 }
2623 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2624 mAudioPatches.valueAt(index)->mAfPatchHandle);
2625 mAudioPatches.removeItemsAt(index);
2626 return NO_ERROR;
2627}
2628
Eric Laurente552edb2014-03-10 17:42:56 -07002629// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002630// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002631// ----------------------------------------------------------------------------
2632
Eric Laurent3a4311c2014-03-17 12:00:47 -07002633uint32_t AudioPolicyManager::nextUniqueId()
2634{
2635 return android_atomic_inc(&mNextUniqueId);
2636}
2637
Eric Laurent6a94d692014-05-20 11:18:06 -07002638uint32_t AudioPolicyManager::nextAudioPortGeneration()
2639{
2640 return android_atomic_inc(&mAudioPortGeneration);
2641}
2642
Eric Laurente0720872014-03-11 09:30:41 -07002643AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002644 :
2645#ifdef AUDIO_POLICY_TEST
2646 Thread(false),
2647#endif //AUDIO_POLICY_TEST
2648 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002649 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002650 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2651 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002652 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002653 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2654 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002655{
Eric Laurent6a94d692014-05-20 11:18:06 -07002656 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002657 mpClientInterface = clientInterface;
2658
Eric Laurent3b73df72014-03-11 09:06:29 -07002659 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2660 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002661 }
2662
Eric Laurent1afeecb2014-05-14 08:52:28 -07002663 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002664 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2665 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2666 ALOGE("could not load audio policy configuration file, setting defaults");
2667 defaultAudioPolicyConfig();
2668 }
2669 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002670 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002671
2672 // must be done after reading the policy
2673 initializeVolumeCurves();
2674
2675 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002676 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2677 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002678 for (size_t i = 0; i < mHwModules.size(); i++) {
2679 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2680 if (mHwModules[i]->mHandle == 0) {
2681 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2682 continue;
2683 }
2684 // open all output streams needed to access attached devices
2685 // except for direct output streams that are only opened when they are actually
2686 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002687 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002688 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2689 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002690 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002691
Eric Laurent3a4311c2014-03-17 12:00:47 -07002692 if (outProfile->mSupportedDevices.isEmpty()) {
2693 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2694 continue;
2695 }
2696
Eric Laurentd78f1532014-09-16 16:38:20 -07002697 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2698 continue;
2699 }
Eric Laurent83b88082014-06-20 18:31:16 -07002700 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2701 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2702 profileType = mDefaultOutputDevice->mDeviceType;
2703 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002704 // chose first device present in mSupportedDevices also part of
2705 // outputDeviceTypes
2706 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2707 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2708 if ((profileType & outputDeviceTypes) != 0) {
2709 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002710 }
Eric Laurente552edb2014-03-10 17:42:56 -07002711 }
2712 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002713 if ((profileType & outputDeviceTypes) == 0) {
2714 continue;
2715 }
2716 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2717
2718 outputDesc->mDevice = profileType;
2719 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2720 config.sample_rate = outputDesc->mSamplingRate;
2721 config.channel_mask = outputDesc->mChannelMask;
2722 config.format = outputDesc->mFormat;
2723 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2724 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2725 &output,
2726 &config,
2727 &outputDesc->mDevice,
2728 String8(""),
2729 &outputDesc->mLatency,
2730 outputDesc->mFlags);
2731
2732 if (status != NO_ERROR) {
2733 ALOGW("Cannot open output stream for device %08x on hw module %s",
2734 outputDesc->mDevice,
2735 mHwModules[i]->mName);
2736 } else {
2737 outputDesc->mSamplingRate = config.sample_rate;
2738 outputDesc->mChannelMask = config.channel_mask;
2739 outputDesc->mFormat = config.format;
2740
2741 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2742 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2743 ssize_t index =
2744 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2745 // give a valid ID to an attached device once confirmed it is reachable
2746 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2747 mAvailableOutputDevices[index]->mId = nextUniqueId();
2748 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2749 }
2750 }
2751 if (mPrimaryOutput == 0 &&
2752 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2753 mPrimaryOutput = output;
2754 }
2755 addOutput(output, outputDesc);
2756 setOutputDevice(output,
2757 outputDesc->mDevice,
2758 true);
2759 }
Eric Laurente552edb2014-03-10 17:42:56 -07002760 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002761 // open input streams needed to access attached devices to validate
2762 // mAvailableInputDevices list
2763 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2764 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002765 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002766
Eric Laurent3a4311c2014-03-17 12:00:47 -07002767 if (inProfile->mSupportedDevices.isEmpty()) {
2768 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2769 continue;
2770 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002771 // chose first device present in mSupportedDevices also part of
2772 // inputDeviceTypes
2773 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2774 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2775 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2776 if (profileType & inputDeviceTypes) {
2777 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002778 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002779 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002780 if ((profileType & inputDeviceTypes) == 0) {
2781 continue;
2782 }
2783 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2784
2785 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2786 inputDesc->mDevice = profileType;
2787
2788 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2789 config.sample_rate = inputDesc->mSamplingRate;
2790 config.channel_mask = inputDesc->mChannelMask;
2791 config.format = inputDesc->mFormat;
2792 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2793 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2794 &input,
2795 &config,
2796 &inputDesc->mDevice,
2797 String8(""),
2798 AUDIO_SOURCE_MIC,
2799 AUDIO_INPUT_FLAG_NONE);
2800
2801 if (status == NO_ERROR) {
2802 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2803 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2804 ssize_t index =
2805 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2806 // give a valid ID to an attached device once confirmed it is reachable
2807 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2808 mAvailableInputDevices[index]->mId = nextUniqueId();
2809 mAvailableInputDevices[index]->mModule = mHwModules[i];
2810 }
2811 }
2812 mpClientInterface->closeInput(input);
2813 } else {
2814 ALOGW("Cannot open input stream for device %08x on hw module %s",
2815 inputDesc->mDevice,
2816 mHwModules[i]->mName);
2817 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002818 }
2819 }
2820 // make sure all attached devices have been allocated a unique ID
2821 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2822 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002823 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002824 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2825 continue;
2826 }
2827 i++;
2828 }
2829 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2830 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002831 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002832 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2833 continue;
2834 }
2835 i++;
2836 }
2837 // make sure default device is reachable
2838 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002839 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002840 }
Eric Laurente552edb2014-03-10 17:42:56 -07002841
2842 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2843
2844 updateDevicesAndOutputs();
2845
2846#ifdef AUDIO_POLICY_TEST
2847 if (mPrimaryOutput != 0) {
2848 AudioParameter outputCmd = AudioParameter();
2849 outputCmd.addInt(String8("set_id"), 0);
2850 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2851
2852 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2853 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002854 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2855 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002856 mTestLatencyMs = 0;
2857 mCurOutput = 0;
2858 mDirectOutput = false;
2859 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2860 mTestOutputs[i] = 0;
2861 }
2862
2863 const size_t SIZE = 256;
2864 char buffer[SIZE];
2865 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2866 run(buffer, ANDROID_PRIORITY_AUDIO);
2867 }
2868#endif //AUDIO_POLICY_TEST
2869}
2870
Eric Laurente0720872014-03-11 09:30:41 -07002871AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002872{
2873#ifdef AUDIO_POLICY_TEST
2874 exit();
2875#endif //AUDIO_POLICY_TEST
2876 for (size_t i = 0; i < mOutputs.size(); i++) {
2877 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002878 }
2879 for (size_t i = 0; i < mInputs.size(); i++) {
2880 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002881 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002882 mAvailableOutputDevices.clear();
2883 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002884 mOutputs.clear();
2885 mInputs.clear();
2886 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002887}
2888
Eric Laurente0720872014-03-11 09:30:41 -07002889status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002890{
2891 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2892}
2893
2894#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002895bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002896{
2897 ALOGV("entering threadLoop()");
2898 while (!exitPending())
2899 {
2900 String8 command;
2901 int valueInt;
2902 String8 value;
2903
2904 Mutex::Autolock _l(mLock);
2905 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2906
2907 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2908 AudioParameter param = AudioParameter(command);
2909
2910 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2911 valueInt != 0) {
2912 ALOGV("Test command %s received", command.string());
2913 String8 target;
2914 if (param.get(String8("target"), target) != NO_ERROR) {
2915 target = "Manager";
2916 }
2917 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2918 param.remove(String8("test_cmd_policy_output"));
2919 mCurOutput = valueInt;
2920 }
2921 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2922 param.remove(String8("test_cmd_policy_direct"));
2923 if (value == "false") {
2924 mDirectOutput = false;
2925 } else if (value == "true") {
2926 mDirectOutput = true;
2927 }
2928 }
2929 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2930 param.remove(String8("test_cmd_policy_input"));
2931 mTestInput = valueInt;
2932 }
2933
2934 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2935 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002936 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002937 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002938 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002939 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002940 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002941 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002942 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002943 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002944 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002945 if (target == "Manager") {
2946 mTestFormat = format;
2947 } else if (mTestOutputs[mCurOutput] != 0) {
2948 AudioParameter outputParam = AudioParameter();
2949 outputParam.addInt(String8("format"), format);
2950 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2951 }
2952 }
2953 }
2954 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2955 param.remove(String8("test_cmd_policy_channels"));
2956 int channels = 0;
2957
2958 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002959 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002960 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002961 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002962 }
2963 if (channels != 0) {
2964 if (target == "Manager") {
2965 mTestChannels = channels;
2966 } else if (mTestOutputs[mCurOutput] != 0) {
2967 AudioParameter outputParam = AudioParameter();
2968 outputParam.addInt(String8("channels"), channels);
2969 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2970 }
2971 }
2972 }
2973 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2974 param.remove(String8("test_cmd_policy_sampleRate"));
2975 if (valueInt >= 0 && valueInt <= 96000) {
2976 int samplingRate = valueInt;
2977 if (target == "Manager") {
2978 mTestSamplingRate = samplingRate;
2979 } else if (mTestOutputs[mCurOutput] != 0) {
2980 AudioParameter outputParam = AudioParameter();
2981 outputParam.addInt(String8("sampling_rate"), samplingRate);
2982 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2983 }
2984 }
2985 }
2986
2987 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2988 param.remove(String8("test_cmd_policy_reopen"));
2989
Eric Laurent1f2f2232014-06-02 12:01:23 -07002990 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002991 mpClientInterface->closeOutput(mPrimaryOutput);
2992
2993 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2994
Eric Laurente552edb2014-03-10 17:42:56 -07002995 mOutputs.removeItem(mPrimaryOutput);
2996
Eric Laurent1f2f2232014-06-02 12:01:23 -07002997 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002998 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002999 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3000 config.sample_rate = outputDesc->mSamplingRate;
3001 config.channel_mask = outputDesc->mChannelMask;
3002 config.format = outputDesc->mFormat;
3003 status_t status = mpClientInterface->openOutput(moduleHandle,
3004 &mPrimaryOutput,
3005 &config,
3006 &outputDesc->mDevice,
3007 String8(""),
3008 &outputDesc->mLatency,
3009 outputDesc->mFlags);
3010 if (status != NO_ERROR) {
3011 ALOGE("Failed to reopen hardware output stream, "
3012 "samplingRate: %d, format %d, channels %d",
3013 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003014 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003015 outputDesc->mSamplingRate = config.sample_rate;
3016 outputDesc->mChannelMask = config.channel_mask;
3017 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003018 AudioParameter outputCmd = AudioParameter();
3019 outputCmd.addInt(String8("set_id"), 0);
3020 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3021 addOutput(mPrimaryOutput, outputDesc);
3022 }
3023 }
3024
3025
3026 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3027 }
3028 }
3029 return false;
3030}
3031
Eric Laurente0720872014-03-11 09:30:41 -07003032void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003033{
3034 {
3035 AutoMutex _l(mLock);
3036 requestExit();
3037 mWaitWorkCV.signal();
3038 }
3039 requestExitAndWait();
3040}
3041
Eric Laurente0720872014-03-11 09:30:41 -07003042int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003043{
3044 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3045 if (output == mTestOutputs[i]) return i;
3046 }
3047 return 0;
3048}
3049#endif //AUDIO_POLICY_TEST
3050
3051// ---
3052
Eric Laurent1f2f2232014-06-02 12:01:23 -07003053void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003054{
Eric Laurent1c333e22014-05-20 10:48:17 -07003055 outputDesc->mIoHandle = output;
3056 outputDesc->mId = nextUniqueId();
3057 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003058 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003059}
3060
Eric Laurent1f2f2232014-06-02 12:01:23 -07003061void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003062{
Eric Laurent1c333e22014-05-20 10:48:17 -07003063 inputDesc->mIoHandle = input;
3064 inputDesc->mId = nextUniqueId();
3065 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003066 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003067}
Eric Laurente552edb2014-03-10 17:42:56 -07003068
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003069void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3070 const String8 address /*in*/,
3071 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3072 // look for a match on the given address on the addresses of the outputs:
3073 // find the address by finding the patch that maps to this output
3074 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3075 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3076 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3077 if (patchIdx >= 0) {
3078 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3079 const int numSinks = patchDesc->mPatch.num_sinks;
3080 for (ssize_t j=0; j < numSinks; j++) {
3081 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3082 const char* patchAddr =
3083 patchDesc->mPatch.sinks[j].ext.device.address;
3084 if (strncmp(patchAddr,
3085 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003086 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003087 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3088 outputs.add(desc->mIoHandle);
3089 break;
3090 }
3091 }
3092 }
3093 }
3094}
3095
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003096status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003097 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003098 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003099 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003100{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003101 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003102 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003103 // erase all current sample rates, formats and channel masks
3104 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003105
Eric Laurent3b73df72014-03-11 09:06:29 -07003106 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003107 // first list already open outputs that can be routed to this device
3108 for (size_t i = 0; i < mOutputs.size(); i++) {
3109 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003110 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003111 if (!deviceDistinguishesOnAddress(device)) {
3112 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3113 outputs.add(mOutputs.keyAt(i));
3114 } else {
3115 ALOGV(" checking address match due to device 0x%x", device);
3116 findIoHandlesByAddress(desc, address, outputs);
3117 }
Eric Laurente552edb2014-03-10 17:42:56 -07003118 }
3119 }
3120 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003121 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003122 for (size_t i = 0; i < mHwModules.size(); i++)
3123 {
3124 if (mHwModules[i]->mHandle == 0) {
3125 continue;
3126 }
3127 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3128 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003129 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003130 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003131 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3132 }
3133 }
3134 }
3135
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003136 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3137
Eric Laurente552edb2014-03-10 17:42:56 -07003138 if (profiles.isEmpty() && outputs.isEmpty()) {
3139 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3140 return BAD_VALUE;
3141 }
3142
3143 // open outputs for matching profiles if needed. Direct outputs are also opened to
3144 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3145 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003146 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003147
3148 // nothing to do if one output is already opened for this profile
3149 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003150 for (j = 0; j < outputs.size(); j++) {
3151 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003152 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003153 // matching profile: save the sample rates, format and channel masks supported
3154 // by the profile in our device descriptor
3155 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003156 break;
3157 }
3158 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003159 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003160 continue;
3161 }
3162
Eric Laurent83b88082014-06-20 18:31:16 -07003163 ALOGV("opening output for device %08x with params %s profile %p",
3164 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003165 desc = new AudioOutputDescriptor(profile);
3166 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003167 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3168 config.sample_rate = desc->mSamplingRate;
3169 config.channel_mask = desc->mChannelMask;
3170 config.format = desc->mFormat;
3171 config.offload_info.sample_rate = desc->mSamplingRate;
3172 config.offload_info.channel_mask = desc->mChannelMask;
3173 config.offload_info.format = desc->mFormat;
3174 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3175 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3176 &output,
3177 &config,
3178 &desc->mDevice,
3179 address,
3180 &desc->mLatency,
3181 desc->mFlags);
3182 if (status == NO_ERROR) {
3183 desc->mSamplingRate = config.sample_rate;
3184 desc->mChannelMask = config.channel_mask;
3185 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003186
Eric Laurentd4692962014-05-05 18:13:44 -07003187 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003188 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003189 char *param = audio_device_address_to_parameter(device, address);
3190 mpClientInterface->setParameters(output, String8(param));
3191 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003192 }
3193
Eric Laurentd4692962014-05-05 18:13:44 -07003194 // Here is where we step through and resolve any "dynamic" fields
3195 String8 reply;
3196 char *value;
3197 if (profile->mSamplingRates[0] == 0) {
3198 reply = mpClientInterface->getParameters(output,
3199 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003200 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003201 reply.string());
3202 value = strpbrk((char *)reply.string(), "=");
3203 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003204 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003205 }
Eric Laurentd4692962014-05-05 18:13:44 -07003206 }
3207 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3208 reply = mpClientInterface->getParameters(output,
3209 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003210 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003211 reply.string());
3212 value = strpbrk((char *)reply.string(), "=");
3213 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003214 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003215 }
Eric Laurentd4692962014-05-05 18:13:44 -07003216 }
3217 if (profile->mChannelMasks[0] == 0) {
3218 reply = mpClientInterface->getParameters(output,
3219 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003220 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003221 reply.string());
3222 value = strpbrk((char *)reply.string(), "=");
3223 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003224 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003225 }
Eric Laurentd4692962014-05-05 18:13:44 -07003226 }
3227 if (((profile->mSamplingRates[0] == 0) &&
3228 (profile->mSamplingRates.size() < 2)) ||
3229 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3230 (profile->mFormats.size() < 2)) ||
3231 ((profile->mChannelMasks[0] == 0) &&
3232 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003233 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003234 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003235 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003236 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3237 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003238 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003239 config.sample_rate = profile->pickSamplingRate();
3240 config.channel_mask = profile->pickChannelMask();
3241 config.format = profile->pickFormat();
3242 config.offload_info.sample_rate = config.sample_rate;
3243 config.offload_info.channel_mask = config.channel_mask;
3244 config.offload_info.format = config.format;
3245 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3246 &output,
3247 &config,
3248 &desc->mDevice,
3249 address,
3250 &desc->mLatency,
3251 desc->mFlags);
3252 if (status == NO_ERROR) {
3253 desc->mSamplingRate = config.sample_rate;
3254 desc->mChannelMask = config.channel_mask;
3255 desc->mFormat = config.format;
3256 } else {
3257 output = AUDIO_IO_HANDLE_NONE;
3258 }
Eric Laurentd4692962014-05-05 18:13:44 -07003259 }
3260
Eric Laurentcf2c0212014-07-25 16:20:43 -07003261 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003262 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003263 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003264 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003265
Eric Laurentd4692962014-05-05 18:13:44 -07003266 // set initial stream volume for device
3267 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003268
Eric Laurentd4692962014-05-05 18:13:44 -07003269 //TODO: configure audio effect output stage here
3270
3271 // open a duplicating output thread for the new output and the primary output
3272 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3273 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003274 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003275 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003276 sp<AudioOutputDescriptor> dupOutputDesc =
3277 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003278 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3279 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3280 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3281 dupOutputDesc->mFormat = desc->mFormat;
3282 dupOutputDesc->mChannelMask = desc->mChannelMask;
3283 dupOutputDesc->mLatency = desc->mLatency;
3284 addOutput(duplicatedOutput, dupOutputDesc);
3285 applyStreamVolumes(duplicatedOutput, device, 0, true);
3286 } else {
3287 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3288 mPrimaryOutput, output);
3289 mpClientInterface->closeOutput(output);
3290 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003291 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003292 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003293 }
Eric Laurente552edb2014-03-10 17:42:56 -07003294 }
3295 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003296 } else {
3297 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003298 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003299 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003300 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003301 profiles.removeAt(profile_index);
3302 profile_index--;
3303 } else {
3304 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003305 devDesc->importAudioPort(profile);
3306
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003307 if (deviceDistinguishesOnAddress(device)) {
3308 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3309 device, address.string());
3310 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3311 NULL/*patch handle*/, address.string());
3312 }
Eric Laurente552edb2014-03-10 17:42:56 -07003313 ALOGV("checkOutputsForDevice(): adding output %d", output);
3314 }
3315 }
3316
3317 if (profiles.isEmpty()) {
3318 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3319 return BAD_VALUE;
3320 }
Eric Laurentd4692962014-05-05 18:13:44 -07003321 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003322 // check if one opened output is not needed any more after disconnecting one device
3323 for (size_t i = 0; i < mOutputs.size(); i++) {
3324 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003325 if (!desc->isDuplicated()) {
3326 if (!(desc->mProfile->mSupportedDevices.types()
3327 & mAvailableOutputDevices.types())) {
3328 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3329 mOutputs.keyAt(i));
3330 outputs.add(mOutputs.keyAt(i));
3331 } else if (deviceDistinguishesOnAddress(device) &&
3332 // exact match on device
3333 (desc->mProfile->mSupportedDevices.types() == device)) {
3334 findIoHandlesByAddress(desc, address, outputs);
3335 }
Eric Laurente552edb2014-03-10 17:42:56 -07003336 }
3337 }
Eric Laurentd4692962014-05-05 18:13:44 -07003338 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003339 for (size_t i = 0; i < mHwModules.size(); i++)
3340 {
3341 if (mHwModules[i]->mHandle == 0) {
3342 continue;
3343 }
3344 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3345 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003346 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003347 if (profile->mSupportedDevices.types() & device) {
3348 ALOGV("checkOutputsForDevice(): "
3349 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003350 if (profile->mSamplingRates[0] == 0) {
3351 profile->mSamplingRates.clear();
3352 profile->mSamplingRates.add(0);
3353 }
3354 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3355 profile->mFormats.clear();
3356 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3357 }
3358 if (profile->mChannelMasks[0] == 0) {
3359 profile->mChannelMasks.clear();
3360 profile->mChannelMasks.add(0);
3361 }
3362 }
3363 }
3364 }
3365 }
3366 return NO_ERROR;
3367}
3368
Eric Laurentd4692962014-05-05 18:13:44 -07003369status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3370 audio_policy_dev_state_t state,
3371 SortedVector<audio_io_handle_t>& inputs,
3372 const String8 address)
3373{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003374 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003375 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3376 // first list already open inputs that can be routed to this device
3377 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3378 desc = mInputs.valueAt(input_index);
3379 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3380 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3381 inputs.add(mInputs.keyAt(input_index));
3382 }
3383 }
3384
3385 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003386 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003387 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3388 {
3389 if (mHwModules[module_idx]->mHandle == 0) {
3390 continue;
3391 }
3392 for (size_t profile_index = 0;
3393 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3394 profile_index++)
3395 {
3396 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3397 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003398 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003399 profile_index, module_idx);
3400 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3401 }
3402 }
3403 }
3404
3405 if (profiles.isEmpty() && inputs.isEmpty()) {
3406 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3407 return BAD_VALUE;
3408 }
3409
3410 // open inputs for matching profiles if needed. Direct inputs are also opened to
3411 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3412 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3413
Eric Laurent1c333e22014-05-20 10:48:17 -07003414 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003415 // nothing to do if one input is already opened for this profile
3416 size_t input_index;
3417 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3418 desc = mInputs.valueAt(input_index);
3419 if (desc->mProfile == profile) {
3420 break;
3421 }
3422 }
3423 if (input_index != mInputs.size()) {
3424 continue;
3425 }
3426
3427 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3428 desc = new AudioInputDescriptor(profile);
3429 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003430 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3431 config.sample_rate = desc->mSamplingRate;
3432 config.channel_mask = desc->mChannelMask;
3433 config.format = desc->mFormat;
3434 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3435 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3436 &input,
3437 &config,
3438 &desc->mDevice,
3439 address,
3440 AUDIO_SOURCE_MIC,
3441 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003442
Eric Laurentcf2c0212014-07-25 16:20:43 -07003443 if (status == NO_ERROR) {
3444 desc->mSamplingRate = config.sample_rate;
3445 desc->mChannelMask = config.channel_mask;
3446 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003447
Eric Laurentd4692962014-05-05 18:13:44 -07003448 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003449 char *param = audio_device_address_to_parameter(device, address);
3450 mpClientInterface->setParameters(input, String8(param));
3451 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003452 }
3453
3454 // Here is where we step through and resolve any "dynamic" fields
3455 String8 reply;
3456 char *value;
3457 if (profile->mSamplingRates[0] == 0) {
3458 reply = mpClientInterface->getParameters(input,
3459 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3460 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3461 reply.string());
3462 value = strpbrk((char *)reply.string(), "=");
3463 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003464 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003465 }
3466 }
3467 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3468 reply = mpClientInterface->getParameters(input,
3469 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3470 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3471 value = strpbrk((char *)reply.string(), "=");
3472 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003473 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003474 }
3475 }
3476 if (profile->mChannelMasks[0] == 0) {
3477 reply = mpClientInterface->getParameters(input,
3478 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3479 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3480 reply.string());
3481 value = strpbrk((char *)reply.string(), "=");
3482 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003483 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003484 }
3485 }
3486 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3487 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3488 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3489 ALOGW("checkInputsForDevice() direct input missing param");
3490 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003491 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003492 }
3493
3494 if (input != 0) {
3495 addInput(input, desc);
3496 }
3497 } // endif input != 0
3498
Eric Laurentcf2c0212014-07-25 16:20:43 -07003499 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003500 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003501 profiles.removeAt(profile_index);
3502 profile_index--;
3503 } else {
3504 inputs.add(input);
3505 ALOGV("checkInputsForDevice(): adding input %d", input);
3506 }
3507 } // end scan profiles
3508
3509 if (profiles.isEmpty()) {
3510 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3511 return BAD_VALUE;
3512 }
3513 } else {
3514 // Disconnect
3515 // check if one opened input is not needed any more after disconnecting one device
3516 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3517 desc = mInputs.valueAt(input_index);
3518 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3519 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3520 mInputs.keyAt(input_index));
3521 inputs.add(mInputs.keyAt(input_index));
3522 }
3523 }
3524 // Clear any profiles associated with the disconnected device.
3525 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3526 if (mHwModules[module_index]->mHandle == 0) {
3527 continue;
3528 }
3529 for (size_t profile_index = 0;
3530 profile_index < mHwModules[module_index]->mInputProfiles.size();
3531 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003532 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003533 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003534 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003535 profile_index, module_index);
3536 if (profile->mSamplingRates[0] == 0) {
3537 profile->mSamplingRates.clear();
3538 profile->mSamplingRates.add(0);
3539 }
3540 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3541 profile->mFormats.clear();
3542 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3543 }
3544 if (profile->mChannelMasks[0] == 0) {
3545 profile->mChannelMasks.clear();
3546 profile->mChannelMasks.add(0);
3547 }
3548 }
3549 }
3550 }
3551 } // end disconnect
3552
3553 return NO_ERROR;
3554}
3555
3556
Eric Laurente0720872014-03-11 09:30:41 -07003557void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003558{
3559 ALOGV("closeOutput(%d)", output);
3560
Eric Laurent1f2f2232014-06-02 12:01:23 -07003561 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003562 if (outputDesc == NULL) {
3563 ALOGW("closeOutput() unknown output %d", output);
3564 return;
3565 }
3566
3567 // look for duplicated outputs connected to the output being removed.
3568 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003569 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003570 if (dupOutputDesc->isDuplicated() &&
3571 (dupOutputDesc->mOutput1 == outputDesc ||
3572 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003573 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003574 if (dupOutputDesc->mOutput1 == outputDesc) {
3575 outputDesc2 = dupOutputDesc->mOutput2;
3576 } else {
3577 outputDesc2 = dupOutputDesc->mOutput1;
3578 }
3579 // As all active tracks on duplicated output will be deleted,
3580 // and as they were also referenced on the other output, the reference
3581 // count for their stream type must be adjusted accordingly on
3582 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003583 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003584 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003585 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003586 }
3587 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3588 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3589
3590 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003591 mOutputs.removeItem(duplicatedOutput);
3592 }
3593 }
3594
Eric Laurent05b90f82014-08-27 15:32:29 -07003595 nextAudioPortGeneration();
3596
3597 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3598 if (index >= 0) {
3599 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3600 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3601 mAudioPatches.removeItemsAt(index);
3602 mpClientInterface->onAudioPatchListUpdate();
3603 }
3604
Eric Laurente552edb2014-03-10 17:42:56 -07003605 AudioParameter param;
3606 param.add(String8("closing"), String8("true"));
3607 mpClientInterface->setParameters(output, param.toString());
3608
3609 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003610 mOutputs.removeItem(output);
3611 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003612}
3613
3614void AudioPolicyManager::closeInput(audio_io_handle_t input)
3615{
3616 ALOGV("closeInput(%d)", input);
3617
3618 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3619 if (inputDesc == NULL) {
3620 ALOGW("closeInput() unknown input %d", input);
3621 return;
3622 }
3623
Eric Laurent6a94d692014-05-20 11:18:06 -07003624 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003625
3626 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3627 if (index >= 0) {
3628 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3629 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3630 mAudioPatches.removeItemsAt(index);
3631 mpClientInterface->onAudioPatchListUpdate();
3632 }
3633
3634 mpClientInterface->closeInput(input);
3635 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003636}
3637
Eric Laurente0720872014-03-11 09:30:41 -07003638SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003639 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003640{
3641 SortedVector<audio_io_handle_t> outputs;
3642
3643 ALOGVV("getOutputsForDevice() device %04x", device);
3644 for (size_t i = 0; i < openOutputs.size(); i++) {
3645 ALOGVV("output %d isDuplicated=%d device=%04x",
3646 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3647 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3648 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3649 outputs.add(openOutputs.keyAt(i));
3650 }
3651 }
3652 return outputs;
3653}
3654
Eric Laurente0720872014-03-11 09:30:41 -07003655bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003656 SortedVector<audio_io_handle_t>& outputs2)
3657{
3658 if (outputs1.size() != outputs2.size()) {
3659 return false;
3660 }
3661 for (size_t i = 0; i < outputs1.size(); i++) {
3662 if (outputs1[i] != outputs2[i]) {
3663 return false;
3664 }
3665 }
3666 return true;
3667}
3668
Eric Laurente0720872014-03-11 09:30:41 -07003669void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003670{
3671 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3672 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3673 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3674 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3675
3676 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3677 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3678 strategy, srcOutputs[0], dstOutputs[0]);
3679 // mute strategy while moving tracks from one output to another
3680 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003681 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003682 if (desc->isStrategyActive(strategy)) {
3683 setStrategyMute(strategy, true, srcOutputs[i]);
3684 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3685 }
3686 }
3687
3688 // Move effects associated to this strategy from previous output to new output
3689 if (strategy == STRATEGY_MEDIA) {
3690 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3691 SortedVector<audio_io_handle_t> moved;
3692 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003693 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3694 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3695 effectDesc->mIo != fxOutput) {
3696 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003697 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3698 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003699 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003700 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003701 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003702 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003703 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003704 }
3705 }
3706 }
3707 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003708 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3709 if (getStrategy((audio_stream_type_t)i) == strategy) {
3710 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003711 }
3712 }
3713 }
3714}
3715
Eric Laurente0720872014-03-11 09:30:41 -07003716void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003717{
Jon Eklund966095e2014-09-09 15:39:49 -05003718 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3719 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003720 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003721 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3722 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003723 checkOutputForStrategy(STRATEGY_SONIFICATION);
3724 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3725 checkOutputForStrategy(STRATEGY_MEDIA);
3726 checkOutputForStrategy(STRATEGY_DTMF);
3727}
3728
Eric Laurente0720872014-03-11 09:30:41 -07003729audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003730{
Eric Laurente552edb2014-03-10 17:42:56 -07003731 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003732 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003733 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3734 return mOutputs.keyAt(i);
3735 }
3736 }
3737
3738 return 0;
3739}
3740
Eric Laurente0720872014-03-11 09:30:41 -07003741void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003742{
Eric Laurente552edb2014-03-10 17:42:56 -07003743 audio_io_handle_t a2dpOutput = getA2dpOutput();
3744 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003745 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003746 return;
3747 }
3748
Eric Laurent3a4311c2014-03-17 12:00:47 -07003749 bool isScoConnected =
3750 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003751 // suspend A2DP output if:
3752 // (NOT already suspended) &&
3753 // ((SCO device is connected &&
3754 // (forced usage for communication || for record is SCO))) ||
3755 // (phone state is ringing || in call)
3756 //
3757 // restore A2DP output if:
3758 // (Already suspended) &&
3759 // ((SCO device is NOT connected ||
3760 // (forced usage NOT for communication && NOT for record is SCO))) &&
3761 // (phone state is NOT ringing && NOT in call)
3762 //
3763 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003764 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003765 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3766 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3767 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3768 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003769
3770 mpClientInterface->restoreOutput(a2dpOutput);
3771 mA2dpSuspended = false;
3772 }
3773 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003774 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003775 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3776 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3777 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3778 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003779
3780 mpClientInterface->suspendOutput(a2dpOutput);
3781 mA2dpSuspended = true;
3782 }
3783 }
3784}
3785
Eric Laurent1c333e22014-05-20 10:48:17 -07003786audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003787{
3788 audio_devices_t device = AUDIO_DEVICE_NONE;
3789
Eric Laurent1f2f2232014-06-02 12:01:23 -07003790 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003791
3792 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3793 if (index >= 0) {
3794 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3795 if (patchDesc->mUid != mUidCached) {
3796 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3797 outputDesc->device(), outputDesc->mPatchHandle);
3798 return outputDesc->device();
3799 }
3800 }
3801
Eric Laurente552edb2014-03-10 17:42:56 -07003802 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003803 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003804 // use device for strategy enforced audible
3805 // 2: we are in call or the strategy phone is active on the output:
3806 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003807 // 3: the strategy for enforced audible is active but not enforced on the output:
3808 // use the device for strategy enforced audible
3809 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003810 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003811 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003812 // use device for strategy "respectful" sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003813 // 6: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003814 // use device for strategy media
Jon Eklund966095e2014-09-09 15:39:49 -05003815 // 7: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003816 // use device for strategy DTMF
Jon Eklund966095e2014-09-09 15:39:49 -05003817 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3818 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003819 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3820 } else if (isInCall() ||
3821 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3822 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003823 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3824 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003825 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3826 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3827 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3828 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3829 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3830 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3831 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3832 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3833 }
3834
Eric Laurent1c333e22014-05-20 10:48:17 -07003835 ALOGV("getNewOutputDevice() selected device %x", device);
3836 return device;
3837}
3838
3839audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3840{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003841 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003842
3843 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3844 if (index >= 0) {
3845 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3846 if (patchDesc->mUid != mUidCached) {
3847 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3848 inputDesc->mDevice, inputDesc->mPatchHandle);
3849 return inputDesc->mDevice;
3850 }
3851 }
3852
Eric Laurent1c333e22014-05-20 10:48:17 -07003853 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3854
3855 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003856 return device;
3857}
3858
Eric Laurente0720872014-03-11 09:30:41 -07003859uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003860 return (uint32_t)getStrategy(stream);
3861}
3862
Eric Laurente0720872014-03-11 09:30:41 -07003863audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003864 // By checking the range of stream before calling getStrategy, we avoid
3865 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3866 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003867 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003868 return AUDIO_DEVICE_NONE;
3869 }
3870 audio_devices_t devices;
3871 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3872 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3873 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3874 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003875 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003876 if (outputDesc->isStrategyActive(strategy)) {
3877 devices = outputDesc->device();
3878 break;
3879 }
Eric Laurente552edb2014-03-10 17:42:56 -07003880 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003881
3882 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
3883 and doesn't really need to.*/
3884 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
3885 devices |= AUDIO_DEVICE_OUT_SPEAKER;
3886 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3887 }
3888
Eric Laurente552edb2014-03-10 17:42:56 -07003889 return devices;
3890}
3891
Eric Laurente0720872014-03-11 09:30:41 -07003892AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003893 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003894 // stream to strategy mapping
3895 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003896 case AUDIO_STREAM_VOICE_CALL:
3897 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003898 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003899 case AUDIO_STREAM_RING:
3900 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003901 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003902 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003903 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003904 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003905 return STRATEGY_DTMF;
3906 default:
3907 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003908 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003909 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3910 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003911 case AUDIO_STREAM_TTS:
3912 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003913 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003914 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003915 return STRATEGY_ENFORCED_AUDIBLE;
3916 }
3917}
3918
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003919uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3920 // flags to strategy mapping
3921 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3922 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3923 }
3924
3925 // usage to strategy mapping
3926 switch (attr->usage) {
3927 case AUDIO_USAGE_MEDIA:
3928 case AUDIO_USAGE_GAME:
3929 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3930 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3931 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3932 return (uint32_t) STRATEGY_MEDIA;
3933
3934 case AUDIO_USAGE_VOICE_COMMUNICATION:
3935 return (uint32_t) STRATEGY_PHONE;
3936
3937 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3938 return (uint32_t) STRATEGY_DTMF;
3939
3940 case AUDIO_USAGE_ALARM:
3941 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3942 return (uint32_t) STRATEGY_SONIFICATION;
3943
3944 case AUDIO_USAGE_NOTIFICATION:
3945 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3946 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3947 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3948 case AUDIO_USAGE_NOTIFICATION_EVENT:
3949 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3950
3951 case AUDIO_USAGE_UNKNOWN:
3952 default:
3953 return (uint32_t) STRATEGY_MEDIA;
3954 }
3955}
3956
Eric Laurente0720872014-03-11 09:30:41 -07003957void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003958 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003959 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003960 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3961 updateDevicesAndOutputs();
3962 break;
3963 default:
3964 break;
3965 }
3966}
3967
Eric Laurente0720872014-03-11 09:30:41 -07003968audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003969 bool fromCache)
3970{
3971 uint32_t device = AUDIO_DEVICE_NONE;
3972
3973 if (fromCache) {
3974 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3975 strategy, mDeviceForStrategy[strategy]);
3976 return mDeviceForStrategy[strategy];
3977 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003978 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003979 switch (strategy) {
3980
3981 case STRATEGY_SONIFICATION_RESPECTFUL:
3982 if (isInCall()) {
3983 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003984 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003985 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3986 // while media is playing on a remote device, use the the sonification behavior.
3987 // Note that we test this usecase before testing if media is playing because
3988 // the isStreamActive() method only informs about the activity of a stream, not
3989 // if it's for local playback. Note also that we use the same delay between both tests
3990 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05003991 //user "safe" speaker if available instead of normal speaker to avoid triggering
3992 //other acoustic safety mechanisms for notification
3993 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
3994 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003995 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003996 // while media is playing (or has recently played), use the same device
3997 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3998 } else {
3999 // when media is not playing anymore, fall back on the sonification behavior
4000 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004001 //user "safe" speaker if available instead of normal speaker to avoid triggering
4002 //other acoustic safety mechanisms for notification
4003 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4004 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004005 }
4006
4007 break;
4008
4009 case STRATEGY_DTMF:
4010 if (!isInCall()) {
4011 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4012 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4013 break;
4014 }
4015 // when in call, DTMF and PHONE strategies follow the same rules
4016 // FALL THROUGH
4017
4018 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004019 // Force use of only devices on primary output if:
4020 // - in call AND
4021 // - cannot route from voice call RX OR
4022 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4023 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4024 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4025 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4026 if (((mAvailableInputDevices.types() &
4027 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4028 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004029 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004030 AUDIO_DEVICE_API_VERSION_3_0))) {
4031 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4032 }
4033 }
Eric Laurente552edb2014-03-10 17:42:56 -07004034 // for phone strategy, we first consider the forced use and then the available devices by order
4035 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004036 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4037 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004038 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004039 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004040 if (device) break;
4041 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004042 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004043 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004044 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004045 if (device) break;
4046 // if SCO device is requested but no SCO device is available, fall back to default case
4047 // FALL THROUGH
4048
4049 default: // FORCE_NONE
4050 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004051 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004052 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004053 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004054 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004055 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004056 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004057 if (device) break;
4058 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004059 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004060 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004061 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004062 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004063 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4064 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004065 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004066 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004067 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004069 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004070 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004071 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004072 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004073 if (device) break;
4074 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004075 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004076 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004077 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004078 if (device == AUDIO_DEVICE_NONE) {
4079 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4080 }
4081 break;
4082
Eric Laurent3b73df72014-03-11 09:06:29 -07004083 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004084 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4085 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004086 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004087 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004088 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004089 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004090 if (device) break;
4091 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004092 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004093 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004094 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004095 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004096 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004097 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004098 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004099 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004100 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004101 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004102 if (device) break;
4103 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004104 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4105 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004106 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004107 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004108 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004109 if (device == AUDIO_DEVICE_NONE) {
4110 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4111 }
4112 break;
4113 }
4114 break;
4115
4116 case STRATEGY_SONIFICATION:
4117
4118 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4119 // handleIncallSonification().
4120 if (isInCall()) {
4121 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4122 break;
4123 }
4124 // FALL THROUGH
4125
4126 case STRATEGY_ENFORCED_AUDIBLE:
4127 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4128 // except:
4129 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4130 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4131
4132 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004133 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004134 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004135 if (device == AUDIO_DEVICE_NONE) {
4136 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4137 }
4138 }
4139 // The second device used for sonification is the same as the device used by media strategy
4140 // FALL THROUGH
4141
4142 case STRATEGY_MEDIA: {
4143 uint32_t device2 = AUDIO_DEVICE_NONE;
4144 if (strategy != STRATEGY_SONIFICATION) {
4145 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004146 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004147 }
4148 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004149 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004150 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004151 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004152 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004153 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004154 }
4155 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004156 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004157 }
4158 }
Hochi Huang327cb702014-09-21 09:47:31 +08004159 if ((device2 == AUDIO_DEVICE_NONE) &&
4160 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4161 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4162 }
Eric Laurente552edb2014-03-10 17:42:56 -07004163 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004164 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004165 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004166 if ((device2 == AUDIO_DEVICE_NONE)) {
4167 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4168 }
Eric Laurente552edb2014-03-10 17:42:56 -07004169 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004170 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004171 }
4172 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004173 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004174 }
4175 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004176 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004177 }
4178 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004179 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004180 }
4181 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4182 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004183 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004184 }
4185 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004186 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004187 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004188 }
4189 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004190 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004191 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004192 int device3 = AUDIO_DEVICE_NONE;
4193 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004194 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004195 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4196 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004197 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004198 }
Eric Laurente552edb2014-03-10 17:42:56 -07004199
Jungshik Jang839e4f32014-06-26 17:23:40 +09004200 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004201 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4202 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4203 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004204
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004205 // If hdmi system audio mode is on, remove speaker out of output list.
4206 if ((strategy == STRATEGY_MEDIA) &&
4207 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4208 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4209 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4210 }
4211
Eric Laurente552edb2014-03-10 17:42:56 -07004212 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004213 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004214 if (device == AUDIO_DEVICE_NONE) {
4215 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4216 }
4217 } break;
4218
4219 default:
4220 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4221 break;
4222 }
4223
4224 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4225 return device;
4226}
4227
Eric Laurente0720872014-03-11 09:30:41 -07004228void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004229{
4230 for (int i = 0; i < NUM_STRATEGIES; i++) {
4231 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4232 }
4233 mPreviousOutputs = mOutputs;
4234}
4235
Eric Laurent1f2f2232014-06-02 12:01:23 -07004236uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004237 audio_devices_t prevDevice,
4238 uint32_t delayMs)
4239{
4240 // mute/unmute strategies using an incompatible device combination
4241 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4242 // if unmuting, unmute only after the specified delay
4243 if (outputDesc->isDuplicated()) {
4244 return 0;
4245 }
4246
4247 uint32_t muteWaitMs = 0;
4248 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004249 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004250
4251 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4252 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4253 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4254 bool doMute = false;
4255
4256 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4257 doMute = true;
4258 outputDesc->mStrategyMutedByDevice[i] = true;
4259 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4260 doMute = true;
4261 outputDesc->mStrategyMutedByDevice[i] = false;
4262 }
Eric Laurent99401132014-05-07 19:48:15 -07004263 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004264 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004265 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004266 // skip output if it does not share any device with current output
4267 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4268 == AUDIO_DEVICE_NONE) {
4269 continue;
4270 }
4271 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4272 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4273 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4274 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4275 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004276 if (mute) {
4277 // FIXME: should not need to double latency if volume could be applied
4278 // immediately by the audioflinger mixer. We must account for the delay
4279 // between now and the next time the audioflinger thread for this output
4280 // will process a buffer (which corresponds to one buffer size,
4281 // usually 1/2 or 1/4 of the latency).
4282 if (muteWaitMs < desc->latency() * 2) {
4283 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004284 }
4285 }
4286 }
4287 }
4288 }
4289 }
4290
Eric Laurent99401132014-05-07 19:48:15 -07004291 // temporary mute output if device selection changes to avoid volume bursts due to
4292 // different per device volumes
4293 if (outputDesc->isActive() && (device != prevDevice)) {
4294 if (muteWaitMs < outputDesc->latency() * 2) {
4295 muteWaitMs = outputDesc->latency() * 2;
4296 }
4297 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4298 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004299 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004300 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004301 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004302 muteWaitMs *2, device);
4303 }
4304 }
4305 }
4306
Eric Laurente552edb2014-03-10 17:42:56 -07004307 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4308 if (muteWaitMs > delayMs) {
4309 muteWaitMs -= delayMs;
4310 usleep(muteWaitMs * 1000);
4311 return muteWaitMs;
4312 }
4313 return 0;
4314}
4315
Eric Laurente0720872014-03-11 09:30:41 -07004316uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004317 audio_devices_t device,
4318 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004319 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004320 audio_patch_handle_t *patchHandle,
4321 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004322{
4323 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004324 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004325 AudioParameter param;
4326 uint32_t muteWaitMs;
4327
4328 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004329 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4330 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004331 return muteWaitMs;
4332 }
4333 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4334 // output profile
4335 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004336 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004337 return 0;
4338 }
4339
4340 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004341 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004342
4343 audio_devices_t prevDevice = outputDesc->mDevice;
4344
4345 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4346
4347 if (device != AUDIO_DEVICE_NONE) {
4348 outputDesc->mDevice = device;
4349 }
4350 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4351
4352 // Do not change the routing if:
4353 // - the requested device is AUDIO_DEVICE_NONE
4354 // - the requested device is the same as current device and force is not specified.
4355 // Doing this check here allows the caller to call setOutputDevice() without conditions
4356 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4357 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4358 return muteWaitMs;
4359 }
4360
4361 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004362
Eric Laurente552edb2014-03-10 17:42:56 -07004363 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004364 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004365 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004366 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004367 DeviceVector deviceList = (address == NULL) ?
4368 mAvailableOutputDevices.getDevicesFromType(device)
4369 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004370 if (!deviceList.isEmpty()) {
4371 struct audio_patch patch;
4372 outputDesc->toAudioPortConfig(&patch.sources[0]);
4373 patch.num_sources = 1;
4374 patch.num_sinks = 0;
4375 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4376 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004377 patch.num_sinks++;
4378 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004379 ssize_t index;
4380 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4381 index = mAudioPatches.indexOfKey(*patchHandle);
4382 } else {
4383 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4384 }
4385 sp< AudioPatch> patchDesc;
4386 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4387 if (index >= 0) {
4388 patchDesc = mAudioPatches.valueAt(index);
4389 afPatchHandle = patchDesc->mAfPatchHandle;
4390 }
4391
Eric Laurent1c333e22014-05-20 10:48:17 -07004392 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004393 &afPatchHandle,
4394 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004395 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4396 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004397 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004398 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004399 if (index < 0) {
4400 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4401 &patch, mUidCached);
4402 addAudioPatch(patchDesc->mHandle, patchDesc);
4403 } else {
4404 patchDesc->mPatch = patch;
4405 }
4406 patchDesc->mAfPatchHandle = afPatchHandle;
4407 patchDesc->mUid = mUidCached;
4408 if (patchHandle) {
4409 *patchHandle = patchDesc->mHandle;
4410 }
4411 outputDesc->mPatchHandle = patchDesc->mHandle;
4412 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004413 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004414 }
4415 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004416
4417 // inform all input as well
4418 for (size_t i = 0; i < mInputs.size(); i++) {
4419 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4420 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4421 AudioParameter inputCmd = AudioParameter();
4422 ALOGV("%s: inform input %d of device:%d", __func__,
4423 inputDescriptor->mIoHandle, device);
4424 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4425 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4426 inputCmd.toString(),
4427 delayMs);
4428 }
4429 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004430 }
Eric Laurente552edb2014-03-10 17:42:56 -07004431
4432 // update stream volumes according to new device
4433 applyStreamVolumes(output, device, delayMs);
4434
4435 return muteWaitMs;
4436}
4437
Eric Laurent1c333e22014-05-20 10:48:17 -07004438status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004439 int delayMs,
4440 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004441{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004442 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004443 ssize_t index;
4444 if (patchHandle) {
4445 index = mAudioPatches.indexOfKey(*patchHandle);
4446 } else {
4447 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4448 }
4449 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004450 return INVALID_OPERATION;
4451 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004452 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4453 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004454 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4455 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004456 removeAudioPatch(patchDesc->mHandle);
4457 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004458 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004459 return status;
4460}
4461
4462status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4463 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004464 bool force,
4465 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004466{
4467 status_t status = NO_ERROR;
4468
Eric Laurent1f2f2232014-06-02 12:01:23 -07004469 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004470 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4471 inputDesc->mDevice = device;
4472
4473 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4474 if (!deviceList.isEmpty()) {
4475 struct audio_patch patch;
4476 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004477 // AUDIO_SOURCE_HOTWORD is for internal use only:
4478 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004479 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4480 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004481 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4482 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004483 patch.num_sinks = 1;
4484 //only one input device for now
4485 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004486 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004487 ssize_t index;
4488 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4489 index = mAudioPatches.indexOfKey(*patchHandle);
4490 } else {
4491 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4492 }
4493 sp< AudioPatch> patchDesc;
4494 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4495 if (index >= 0) {
4496 patchDesc = mAudioPatches.valueAt(index);
4497 afPatchHandle = patchDesc->mAfPatchHandle;
4498 }
4499
Eric Laurent1c333e22014-05-20 10:48:17 -07004500 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004501 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004502 0);
4503 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004504 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004505 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004506 if (index < 0) {
4507 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4508 &patch, mUidCached);
4509 addAudioPatch(patchDesc->mHandle, patchDesc);
4510 } else {
4511 patchDesc->mPatch = patch;
4512 }
4513 patchDesc->mAfPatchHandle = afPatchHandle;
4514 patchDesc->mUid = mUidCached;
4515 if (patchHandle) {
4516 *patchHandle = patchDesc->mHandle;
4517 }
4518 inputDesc->mPatchHandle = patchDesc->mHandle;
4519 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004520 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004521 }
4522 }
4523 }
4524 return status;
4525}
4526
Eric Laurent6a94d692014-05-20 11:18:06 -07004527status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4528 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004529{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004530 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004531 ssize_t index;
4532 if (patchHandle) {
4533 index = mAudioPatches.indexOfKey(*patchHandle);
4534 } else {
4535 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4536 }
4537 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004538 return INVALID_OPERATION;
4539 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004540 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4541 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004542 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4543 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004544 removeAudioPatch(patchDesc->mHandle);
4545 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004546 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004547 return status;
4548}
4549
4550sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004551 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004552 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004553 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004554 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004555{
4556 // Choose an input profile based on the requested capture parameters: select the first available
4557 // profile supporting all requested parameters.
4558
4559 for (size_t i = 0; i < mHwModules.size(); i++)
4560 {
4561 if (mHwModules[i]->mHandle == 0) {
4562 continue;
4563 }
4564 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4565 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004566 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004567 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004568 if (profile->isCompatibleProfile(device, samplingRate,
4569 &samplingRate /*updatedSamplingRate*/,
4570 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004571 return profile;
4572 }
4573 }
4574 }
4575 return NULL;
4576}
4577
Eric Laurente0720872014-03-11 09:30:41 -07004578audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004579{
4580 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004581 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4582 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004583 switch (inputSource) {
4584 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004585 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004586 device = AUDIO_DEVICE_IN_VOICE_CALL;
4587 break;
4588 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004589 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004590
4591 case AUDIO_SOURCE_DEFAULT:
4592 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004593 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4594 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004595 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4596 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4597 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4598 device = AUDIO_DEVICE_IN_USB_DEVICE;
4599 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4600 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004601 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004602 break;
4603
4604 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4605 // Allow only use of devices on primary input if in call and HAL does not support routing
4606 // to voice call path.
4607 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4608 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4609 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4610 }
4611
4612 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4613 case AUDIO_POLICY_FORCE_BT_SCO:
4614 // if SCO device is requested but no SCO device is available, fall back to default case
4615 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4616 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4617 break;
4618 }
4619 // FALL THROUGH
4620
4621 default: // FORCE_NONE
4622 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4623 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4624 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4625 device = AUDIO_DEVICE_IN_USB_DEVICE;
4626 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4627 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4628 }
4629 break;
4630
4631 case AUDIO_POLICY_FORCE_SPEAKER:
4632 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4633 device = AUDIO_DEVICE_IN_BACK_MIC;
4634 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4635 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4636 }
4637 break;
4638 }
4639 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004640
Eric Laurente552edb2014-03-10 17:42:56 -07004641 case AUDIO_SOURCE_VOICE_RECOGNITION:
4642 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004643 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004644 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004645 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004646 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004647 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004648 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4649 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004650 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004651 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4652 }
4653 break;
4654 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004655 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004656 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004657 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004658 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4659 }
4660 break;
4661 case AUDIO_SOURCE_VOICE_DOWNLINK:
4662 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004663 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004664 device = AUDIO_DEVICE_IN_VOICE_CALL;
4665 }
4666 break;
4667 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004668 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004669 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4670 }
4671 break;
Hochi Huang327cb702014-09-21 09:47:31 +08004672 case AUDIO_SOURCE_FM_TUNER:
4673 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
4674 device = AUDIO_DEVICE_IN_FM_TUNER;
4675 }
4676 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004677 default:
4678 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4679 break;
4680 }
4681 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4682 return device;
4683}
4684
Eric Laurente0720872014-03-11 09:30:41 -07004685bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004686{
4687 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4688 device &= ~AUDIO_DEVICE_BIT_IN;
4689 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4690 return true;
4691 }
4692 return false;
4693}
4694
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004695bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4696 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4697}
4698
Eric Laurente0720872014-03-11 09:30:41 -07004699audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004700{
4701 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004702 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004703 if ((input_descriptor->mRefCount > 0)
4704 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4705 return mInputs.keyAt(i);
4706 }
4707 }
4708 return 0;
4709}
4710
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004711uint32_t AudioPolicyManager::activeInputsCount() const
4712{
4713 uint32_t count = 0;
4714 for (size_t i = 0; i < mInputs.size(); i++) {
4715 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4716 if (desc->mRefCount > 0) {
4717 return count++;
4718 }
4719 }
4720 return count;
4721}
4722
Eric Laurente552edb2014-03-10 17:42:56 -07004723
Eric Laurente0720872014-03-11 09:30:41 -07004724audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004725{
4726 if (device == AUDIO_DEVICE_NONE) {
4727 // this happens when forcing a route update and no track is active on an output.
4728 // In this case the returned category is not important.
4729 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004730 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004731 // Multiple device selection is either:
4732 // - speaker + one other device: give priority to speaker in this case.
4733 // - one A2DP device + another device: happens with duplicated output. In this case
4734 // retain the device on the A2DP output as the other must not correspond to an active
4735 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004736 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004737 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4738 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004739 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4740 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4741 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4742 device = AUDIO_DEVICE_OUT_AUX_LINE;
4743 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4744 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004745 } else {
4746 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4747 }
4748 }
4749
Jon Eklund11c9fb12014-06-23 14:47:03 -05004750 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4751 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4752 device = AUDIO_DEVICE_OUT_SPEAKER;
4753
Eric Laurent3b73df72014-03-11 09:06:29 -07004754 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004755 "getDeviceForVolume() invalid device combination: %08x",
4756 device);
4757
4758 return device;
4759}
4760
Eric Laurente0720872014-03-11 09:30:41 -07004761AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004762{
4763 switch(getDeviceForVolume(device)) {
4764 case AUDIO_DEVICE_OUT_EARPIECE:
4765 return DEVICE_CATEGORY_EARPIECE;
4766 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4767 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4768 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4769 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4770 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4771 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4772 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004773 case AUDIO_DEVICE_OUT_LINE:
4774 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4775 /*USB? Remote submix?*/
4776 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004777 case AUDIO_DEVICE_OUT_SPEAKER:
4778 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4779 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004780 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4781 case AUDIO_DEVICE_OUT_USB_DEVICE:
4782 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4783 default:
4784 return DEVICE_CATEGORY_SPEAKER;
4785 }
4786}
4787
Eric Laurente0720872014-03-11 09:30:41 -07004788float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004789 int indexInUi)
4790{
4791 device_category deviceCategory = getDeviceCategory(device);
4792 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4793
4794 // the volume index in the UI is relative to the min and max volume indices for this stream type
4795 int nbSteps = 1 + curve[VOLMAX].mIndex -
4796 curve[VOLMIN].mIndex;
4797 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4798 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4799
4800 // find what part of the curve this index volume belongs to, or if it's out of bounds
4801 int segment = 0;
4802 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4803 return 0.0f;
4804 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4805 segment = 0;
4806 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4807 segment = 1;
4808 } else if (volIdx <= curve[VOLMAX].mIndex) {
4809 segment = 2;
4810 } else { // out of bounds
4811 return 1.0f;
4812 }
4813
4814 // linear interpolation in the attenuation table in dB
4815 float decibels = curve[segment].mDBAttenuation +
4816 ((float)(volIdx - curve[segment].mIndex)) *
4817 ( (curve[segment+1].mDBAttenuation -
4818 curve[segment].mDBAttenuation) /
4819 ((float)(curve[segment+1].mIndex -
4820 curve[segment].mIndex)) );
4821
4822 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4823
4824 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4825 curve[segment].mIndex, volIdx,
4826 curve[segment+1].mIndex,
4827 curve[segment].mDBAttenuation,
4828 decibels,
4829 curve[segment+1].mDBAttenuation,
4830 amplification);
4831
4832 return amplification;
4833}
4834
Eric Laurente0720872014-03-11 09:30:41 -07004835const AudioPolicyManager::VolumeCurvePoint
4836 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004837 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4838};
4839
Eric Laurente0720872014-03-11 09:30:41 -07004840const AudioPolicyManager::VolumeCurvePoint
4841 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004842 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4843};
4844
Eric Laurente0720872014-03-11 09:30:41 -07004845const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004846 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4847 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4848};
4849
4850const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004851 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004852 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4853};
4854
Eric Laurente0720872014-03-11 09:30:41 -07004855const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004856 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004857 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004858};
4859
4860const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004861 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004862 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4863};
4864
Eric Laurente0720872014-03-11 09:30:41 -07004865const AudioPolicyManager::VolumeCurvePoint
4866 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004867 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4868};
4869
4870// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4871// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4872// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4873// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4874
Eric Laurente0720872014-03-11 09:30:41 -07004875const AudioPolicyManager::VolumeCurvePoint
4876 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004877 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4878};
4879
Eric Laurente0720872014-03-11 09:30:41 -07004880const AudioPolicyManager::VolumeCurvePoint
4881 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004882 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4883};
4884
Eric Laurente0720872014-03-11 09:30:41 -07004885const AudioPolicyManager::VolumeCurvePoint
4886 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004887 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4888};
4889
Eric Laurente0720872014-03-11 09:30:41 -07004890const AudioPolicyManager::VolumeCurvePoint
4891 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004892 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4893};
4894
Eric Laurente0720872014-03-11 09:30:41 -07004895const AudioPolicyManager::VolumeCurvePoint
4896 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004897 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4898};
4899
Eric Laurente0720872014-03-11 09:30:41 -07004900const AudioPolicyManager::VolumeCurvePoint
4901 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4902 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004903 { // AUDIO_STREAM_VOICE_CALL
4904 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4905 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004906 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4907 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004908 },
4909 { // AUDIO_STREAM_SYSTEM
4910 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4911 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004912 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4913 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004914 },
4915 { // AUDIO_STREAM_RING
4916 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4917 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004918 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4919 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004920 },
4921 { // AUDIO_STREAM_MUSIC
4922 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4923 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004924 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4925 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004926 },
4927 { // AUDIO_STREAM_ALARM
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_NOTIFICATION
4934 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4935 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004936 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4937 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004938 },
4939 { // AUDIO_STREAM_BLUETOOTH_SCO
4940 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4941 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004942 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4943 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004944 },
4945 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4946 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4947 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004948 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4949 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004950 },
4951 { // AUDIO_STREAM_DTMF
4952 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4953 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004954 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4955 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004956 },
4957 { // AUDIO_STREAM_TTS
4958 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4959 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004960 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4961 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004962 },
4963};
4964
Eric Laurente0720872014-03-11 09:30:41 -07004965void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004966{
4967 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4968 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4969 mStreams[i].mVolumeCurve[j] =
4970 sVolumeProfiles[i][j];
4971 }
4972 }
4973
4974 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4975 if (mSpeakerDrcEnabled) {
4976 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4977 sDefaultSystemVolumeCurveDrc;
4978 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4979 sSpeakerSonificationVolumeCurveDrc;
4980 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4981 sSpeakerSonificationVolumeCurveDrc;
4982 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4983 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004984 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4985 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004986 }
4987}
4988
Eric Laurente0720872014-03-11 09:30:41 -07004989float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004990 int index,
4991 audio_io_handle_t output,
4992 audio_devices_t device)
4993{
4994 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004995 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004996 StreamDescriptor &streamDesc = mStreams[stream];
4997
4998 if (device == AUDIO_DEVICE_NONE) {
4999 device = outputDesc->device();
5000 }
5001
Eric Laurente552edb2014-03-10 17:42:56 -07005002 volume = volIndexToAmpl(device, streamDesc, index);
5003
5004 // if a headset is connected, apply the following rules to ring tones and notifications
5005 // to avoid sound level bursts in user's ears:
5006 // - always attenuate ring tones and notifications volume by 6dB
5007 // - if music is playing, always limit the volume to current music volume,
5008 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005009 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005010 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5011 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5012 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5013 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5014 ((stream_strategy == STRATEGY_SONIFICATION)
5015 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005016 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005017 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005018 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005019 streamDesc.mCanBeMuted) {
5020 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5021 // when the phone is ringing we must consider that music could have been paused just before
5022 // by the music application and behave as if music was active if the last music track was
5023 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005024 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005025 mLimitRingtoneVolume) {
5026 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005027 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5028 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005029 output,
5030 musicDevice);
5031 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5032 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5033 if (volume > minVol) {
5034 volume = minVol;
5035 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5036 }
5037 }
5038 }
5039
5040 return volume;
5041}
5042
Eric Laurente0720872014-03-11 09:30:41 -07005043status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005044 int index,
5045 audio_io_handle_t output,
5046 audio_devices_t device,
5047 int delayMs,
5048 bool force)
5049{
5050
5051 // do not change actual stream volume if the stream is muted
5052 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5053 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5054 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5055 return NO_ERROR;
5056 }
5057
5058 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005059 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5060 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5061 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5062 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005063 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005064 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005065 return INVALID_OPERATION;
5066 }
5067
5068 float volume = computeVolume(stream, index, output, device);
5069 // We actually change the volume if:
5070 // - the float value returned by computeVolume() changed
5071 // - the force flag is set
5072 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5073 force) {
5074 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5075 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5076 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5077 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005078 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5079 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005080 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005081 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005082 }
5083
Eric Laurent3b73df72014-03-11 09:06:29 -07005084 if (stream == AUDIO_STREAM_VOICE_CALL ||
5085 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005086 float voiceVolume;
5087 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005088 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005089 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5090 } else {
5091 voiceVolume = 1.0;
5092 }
5093
5094 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5095 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5096 mLastVoiceVolume = voiceVolume;
5097 }
5098 }
5099
5100 return NO_ERROR;
5101}
5102
Eric Laurente0720872014-03-11 09:30:41 -07005103void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005104 audio_devices_t device,
5105 int delayMs,
5106 bool force)
5107{
5108 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5109
Eric Laurent3b73df72014-03-11 09:06:29 -07005110 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5111 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005112 mStreams[stream].getVolumeIndex(device),
5113 output,
5114 device,
5115 delayMs,
5116 force);
5117 }
5118}
5119
Eric Laurente0720872014-03-11 09:30:41 -07005120void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005121 bool on,
5122 audio_io_handle_t output,
5123 int delayMs,
5124 audio_devices_t device)
5125{
5126 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005127 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5128 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5129 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005130 }
5131 }
5132}
5133
Eric Laurente0720872014-03-11 09:30:41 -07005134void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005135 bool on,
5136 audio_io_handle_t output,
5137 int delayMs,
5138 audio_devices_t device)
5139{
5140 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005141 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005142 if (device == AUDIO_DEVICE_NONE) {
5143 device = outputDesc->device();
5144 }
5145
5146 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5147 stream, on, output, outputDesc->mMuteCount[stream], device);
5148
5149 if (on) {
5150 if (outputDesc->mMuteCount[stream] == 0) {
5151 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005152 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5153 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005154 checkAndSetVolume(stream, 0, output, device, delayMs);
5155 }
5156 }
5157 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5158 outputDesc->mMuteCount[stream]++;
5159 } else {
5160 if (outputDesc->mMuteCount[stream] == 0) {
5161 ALOGV("setStreamMute() unmuting non muted stream!");
5162 return;
5163 }
5164 if (--outputDesc->mMuteCount[stream] == 0) {
5165 checkAndSetVolume(stream,
5166 streamDesc.getVolumeIndex(device),
5167 output,
5168 device,
5169 delayMs);
5170 }
5171 }
5172}
5173
Eric Laurente0720872014-03-11 09:30:41 -07005174void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005175 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005176{
5177 // if the stream pertains to sonification strategy and we are in call we must
5178 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5179 // in the device used for phone strategy and play the tone if the selected device does not
5180 // interfere with the device used for phone strategy
5181 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5182 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005183 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005184 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5185 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005186 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005187 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5188 stream, starting, outputDesc->mDevice, stateChange);
5189 if (outputDesc->mRefCount[stream]) {
5190 int muteCount = 1;
5191 if (stateChange) {
5192 muteCount = outputDesc->mRefCount[stream];
5193 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005194 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005195 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5196 for (int i = 0; i < muteCount; i++) {
5197 setStreamMute(stream, starting, mPrimaryOutput);
5198 }
5199 } else {
5200 ALOGV("handleIncallSonification() high visibility");
5201 if (outputDesc->device() &
5202 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5203 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5204 for (int i = 0; i < muteCount; i++) {
5205 setStreamMute(stream, starting, mPrimaryOutput);
5206 }
5207 }
5208 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005209 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5210 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005211 } else {
5212 mpClientInterface->stopTone();
5213 }
5214 }
5215 }
5216 }
5217}
5218
Eric Laurente0720872014-03-11 09:30:41 -07005219bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005220{
5221 return isStateInCall(mPhoneState);
5222}
5223
Eric Laurente0720872014-03-11 09:30:41 -07005224bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005225 return ((state == AUDIO_MODE_IN_CALL) ||
5226 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005227}
5228
Eric Laurente0720872014-03-11 09:30:41 -07005229uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005230{
5231 return MAX_EFFECTS_CPU_LOAD;
5232}
5233
Eric Laurente0720872014-03-11 09:30:41 -07005234uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005235{
5236 return MAX_EFFECTS_MEMORY;
5237}
5238
Eric Laurent6a94d692014-05-20 11:18:06 -07005239
Eric Laurente552edb2014-03-10 17:42:56 -07005240// --- AudioOutputDescriptor class implementation
5241
Eric Laurente0720872014-03-11 09:30:41 -07005242AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005243 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005244 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005245 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005246 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5247{
5248 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005249 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005250 mRefCount[i] = 0;
5251 mCurVolume[i] = -1.0;
5252 mMuteCount[i] = 0;
5253 mStopTime[i] = 0;
5254 }
5255 for (int i = 0; i < NUM_STRATEGIES; i++) {
5256 mStrategyMutedByDevice[i] = false;
5257 }
5258 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005259 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005260 mSamplingRate = profile->pickSamplingRate();
5261 mFormat = profile->pickFormat();
5262 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005263 if (profile->mGains.size() > 0) {
5264 profile->mGains[0]->getDefaultConfig(&mGain);
5265 }
Eric Laurente552edb2014-03-10 17:42:56 -07005266 }
5267}
5268
Eric Laurente0720872014-03-11 09:30:41 -07005269audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005270{
5271 if (isDuplicated()) {
5272 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5273 } else {
5274 return mDevice;
5275 }
5276}
5277
Eric Laurente0720872014-03-11 09:30:41 -07005278uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005279{
5280 if (isDuplicated()) {
5281 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5282 } else {
5283 return mLatency;
5284 }
5285}
5286
Eric Laurente0720872014-03-11 09:30:41 -07005287bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005288 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005289{
5290 if (isDuplicated()) {
5291 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5292 } else if (outputDesc->isDuplicated()){
5293 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5294 } else {
5295 return (mProfile->mModule == outputDesc->mProfile->mModule);
5296 }
5297}
5298
Eric Laurente0720872014-03-11 09:30:41 -07005299void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005300 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005301{
5302 // forward usage count change to attached outputs
5303 if (isDuplicated()) {
5304 mOutput1->changeRefCount(stream, delta);
5305 mOutput2->changeRefCount(stream, delta);
5306 }
5307 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005308 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5309 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005310 mRefCount[stream] = 0;
5311 return;
5312 }
5313 mRefCount[stream] += delta;
5314 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5315}
5316
Eric Laurente0720872014-03-11 09:30:41 -07005317audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005318{
5319 if (isDuplicated()) {
5320 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5321 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005322 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005323 }
5324}
5325
Eric Laurente0720872014-03-11 09:30:41 -07005326bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005327{
5328 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5329}
5330
Eric Laurente0720872014-03-11 09:30:41 -07005331bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005332 uint32_t inPastMs,
5333 nsecs_t sysTime) const
5334{
5335 if ((sysTime == 0) && (inPastMs != 0)) {
5336 sysTime = systemTime();
5337 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005338 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5339 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005340 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005341 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005342 return true;
5343 }
5344 }
5345 return false;
5346}
5347
Eric Laurente0720872014-03-11 09:30:41 -07005348bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005349 uint32_t inPastMs,
5350 nsecs_t sysTime) const
5351{
5352 if (mRefCount[stream] != 0) {
5353 return true;
5354 }
5355 if (inPastMs == 0) {
5356 return false;
5357 }
5358 if (sysTime == 0) {
5359 sysTime = systemTime();
5360 }
5361 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5362 return true;
5363 }
5364 return false;
5365}
5366
Eric Laurent1c333e22014-05-20 10:48:17 -07005367void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005368 struct audio_port_config *dstConfig,
5369 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005370{
Eric Laurent84c70242014-06-23 08:46:27 -07005371 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5372
Eric Laurent1f2f2232014-06-02 12:01:23 -07005373 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5374 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5375 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005376 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005377 }
5378 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5379
Eric Laurent6a94d692014-05-20 11:18:06 -07005380 dstConfig->id = mId;
5381 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5382 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005383 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5384 dstConfig->ext.mix.handle = mIoHandle;
5385 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005386}
5387
5388void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5389 struct audio_port *port) const
5390{
Eric Laurent84c70242014-06-23 08:46:27 -07005391 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005392 mProfile->toAudioPort(port);
5393 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005394 toAudioPortConfig(&port->active_config);
5395 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005396 port->ext.mix.handle = mIoHandle;
5397 port->ext.mix.latency_class =
5398 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5399}
Eric Laurente552edb2014-03-10 17:42:56 -07005400
Eric Laurente0720872014-03-11 09:30:41 -07005401status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005402{
5403 const size_t SIZE = 256;
5404 char buffer[SIZE];
5405 String8 result;
5406
Eric Laurent4d416952014-08-10 14:07:09 -07005407 snprintf(buffer, SIZE, " ID: %d\n", mId);
5408 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005409 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5410 result.append(buffer);
5411 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5412 result.append(buffer);
5413 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5414 result.append(buffer);
5415 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5416 result.append(buffer);
5417 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5418 result.append(buffer);
5419 snprintf(buffer, SIZE, " Devices %08x\n", device());
5420 result.append(buffer);
5421 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5422 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005423 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5424 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5425 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005426 result.append(buffer);
5427 }
5428 write(fd, result.string(), result.size());
5429
5430 return NO_ERROR;
5431}
5432
5433// --- AudioInputDescriptor class implementation
5434
Eric Laurent1c333e22014-05-20 10:48:17 -07005435AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005436 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005437 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005438 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005439{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005440 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005441 mSamplingRate = profile->pickSamplingRate();
5442 mFormat = profile->pickFormat();
5443 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005444 if (profile->mGains.size() > 0) {
5445 profile->mGains[0]->getDefaultConfig(&mGain);
5446 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005447 }
Eric Laurente552edb2014-03-10 17:42:56 -07005448}
5449
Eric Laurent1c333e22014-05-20 10:48:17 -07005450void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005451 struct audio_port_config *dstConfig,
5452 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005453{
Eric Laurent84c70242014-06-23 08:46:27 -07005454 ALOG_ASSERT(mProfile != 0,
5455 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005456 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5457 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5458 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005459 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005460 }
5461
5462 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5463
Eric Laurent6a94d692014-05-20 11:18:06 -07005464 dstConfig->id = mId;
5465 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5466 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005467 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5468 dstConfig->ext.mix.handle = mIoHandle;
5469 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005470}
5471
5472void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5473 struct audio_port *port) const
5474{
Eric Laurent84c70242014-06-23 08:46:27 -07005475 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5476
Eric Laurent1c333e22014-05-20 10:48:17 -07005477 mProfile->toAudioPort(port);
5478 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005479 toAudioPortConfig(&port->active_config);
5480 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005481 port->ext.mix.handle = mIoHandle;
5482 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5483}
5484
Eric Laurente0720872014-03-11 09:30:41 -07005485status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005486{
5487 const size_t SIZE = 256;
5488 char buffer[SIZE];
5489 String8 result;
5490
Eric Laurent4d416952014-08-10 14:07:09 -07005491 snprintf(buffer, SIZE, " ID: %d\n", mId);
5492 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005493 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5494 result.append(buffer);
5495 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5496 result.append(buffer);
5497 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5498 result.append(buffer);
5499 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5500 result.append(buffer);
5501 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5502 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005503 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5504 result.append(buffer);
5505
Eric Laurente552edb2014-03-10 17:42:56 -07005506 write(fd, result.string(), result.size());
5507
5508 return NO_ERROR;
5509}
5510
5511// --- StreamDescriptor class implementation
5512
Eric Laurente0720872014-03-11 09:30:41 -07005513AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005514 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5515{
5516 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5517}
5518
Eric Laurente0720872014-03-11 09:30:41 -07005519int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005520{
Eric Laurente0720872014-03-11 09:30:41 -07005521 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005522 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5523 if (mIndexCur.indexOfKey(device) < 0) {
5524 device = AUDIO_DEVICE_OUT_DEFAULT;
5525 }
5526 return mIndexCur.valueFor(device);
5527}
5528
Eric Laurente0720872014-03-11 09:30:41 -07005529void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005530{
5531 const size_t SIZE = 256;
5532 char buffer[SIZE];
5533 String8 result;
5534
5535 snprintf(buffer, SIZE, "%s %02d %02d ",
5536 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5537 result.append(buffer);
5538 for (size_t i = 0; i < mIndexCur.size(); i++) {
5539 snprintf(buffer, SIZE, "%04x : %02d, ",
5540 mIndexCur.keyAt(i),
5541 mIndexCur.valueAt(i));
5542 result.append(buffer);
5543 }
5544 result.append("\n");
5545
5546 write(fd, result.string(), result.size());
5547}
5548
5549// --- EffectDescriptor class implementation
5550
Eric Laurente0720872014-03-11 09:30:41 -07005551status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005552{
5553 const size_t SIZE = 256;
5554 char buffer[SIZE];
5555 String8 result;
5556
5557 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5558 result.append(buffer);
5559 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5560 result.append(buffer);
5561 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5562 result.append(buffer);
5563 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5564 result.append(buffer);
5565 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5566 result.append(buffer);
5567 write(fd, result.string(), result.size());
5568
5569 return NO_ERROR;
5570}
5571
Eric Laurent1c333e22014-05-20 10:48:17 -07005572// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005573
Eric Laurente0720872014-03-11 09:30:41 -07005574AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005575 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5576 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005577{
5578}
5579
Eric Laurente0720872014-03-11 09:30:41 -07005580AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005581{
5582 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005583 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005584 }
5585 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005586 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005587 }
5588 free((void *)mName);
5589}
5590
Eric Laurent1afeecb2014-05-14 08:52:28 -07005591status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5592{
5593 cnode *node = root->first_child;
5594
5595 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5596
5597 while (node) {
5598 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5599 profile->loadSamplingRates((char *)node->value);
5600 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5601 profile->loadFormats((char *)node->value);
5602 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5603 profile->loadInChannels((char *)node->value);
5604 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5605 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5606 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005607 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5608 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005609 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5610 profile->loadGains(node);
5611 }
5612 node = node->next;
5613 }
5614 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5615 "loadInput() invalid supported devices");
5616 ALOGW_IF(profile->mChannelMasks.size() == 0,
5617 "loadInput() invalid supported channel masks");
5618 ALOGW_IF(profile->mSamplingRates.size() == 0,
5619 "loadInput() invalid supported sampling rates");
5620 ALOGW_IF(profile->mFormats.size() == 0,
5621 "loadInput() invalid supported formats");
5622 if (!profile->mSupportedDevices.isEmpty() &&
5623 (profile->mChannelMasks.size() != 0) &&
5624 (profile->mSamplingRates.size() != 0) &&
5625 (profile->mFormats.size() != 0)) {
5626
5627 ALOGV("loadInput() adding input Supported Devices %04x",
5628 profile->mSupportedDevices.types());
5629
5630 mInputProfiles.add(profile);
5631 return NO_ERROR;
5632 } else {
5633 return BAD_VALUE;
5634 }
5635}
5636
5637status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5638{
5639 cnode *node = root->first_child;
5640
5641 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5642
5643 while (node) {
5644 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5645 profile->loadSamplingRates((char *)node->value);
5646 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5647 profile->loadFormats((char *)node->value);
5648 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5649 profile->loadOutChannels((char *)node->value);
5650 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5651 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5652 mDeclaredDevices);
5653 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005654 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005655 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5656 profile->loadGains(node);
5657 }
5658 node = node->next;
5659 }
5660 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5661 "loadOutput() invalid supported devices");
5662 ALOGW_IF(profile->mChannelMasks.size() == 0,
5663 "loadOutput() invalid supported channel masks");
5664 ALOGW_IF(profile->mSamplingRates.size() == 0,
5665 "loadOutput() invalid supported sampling rates");
5666 ALOGW_IF(profile->mFormats.size() == 0,
5667 "loadOutput() invalid supported formats");
5668 if (!profile->mSupportedDevices.isEmpty() &&
5669 (profile->mChannelMasks.size() != 0) &&
5670 (profile->mSamplingRates.size() != 0) &&
5671 (profile->mFormats.size() != 0)) {
5672
5673 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5674 profile->mSupportedDevices.types(), profile->mFlags);
5675
5676 mOutputProfiles.add(profile);
5677 return NO_ERROR;
5678 } else {
5679 return BAD_VALUE;
5680 }
5681}
5682
5683status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5684{
5685 cnode *node = root->first_child;
5686
5687 audio_devices_t type = AUDIO_DEVICE_NONE;
5688 while (node) {
5689 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5690 type = parseDeviceNames((char *)node->value);
5691 break;
5692 }
5693 node = node->next;
5694 }
5695 if (type == AUDIO_DEVICE_NONE ||
5696 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5697 ALOGW("loadDevice() bad type %08x", type);
5698 return BAD_VALUE;
5699 }
5700 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5701 deviceDesc->mModule = this;
5702
5703 node = root->first_child;
5704 while (node) {
5705 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5706 deviceDesc->mAddress = String8((char *)node->value);
5707 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5708 if (audio_is_input_device(type)) {
5709 deviceDesc->loadInChannels((char *)node->value);
5710 } else {
5711 deviceDesc->loadOutChannels((char *)node->value);
5712 }
5713 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5714 deviceDesc->loadGains(node);
5715 }
5716 node = node->next;
5717 }
5718
5719 ALOGV("loadDevice() adding device name %s type %08x address %s",
5720 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5721
5722 mDeclaredDevices.add(deviceDesc);
5723
5724 return NO_ERROR;
5725}
5726
Eric Laurente0720872014-03-11 09:30:41 -07005727void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005728{
5729 const size_t SIZE = 256;
5730 char buffer[SIZE];
5731 String8 result;
5732
5733 snprintf(buffer, SIZE, " - name: %s\n", mName);
5734 result.append(buffer);
5735 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5736 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005737 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5738 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005739 write(fd, result.string(), result.size());
5740 if (mOutputProfiles.size()) {
5741 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5742 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005743 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005744 write(fd, buffer, strlen(buffer));
5745 mOutputProfiles[i]->dump(fd);
5746 }
5747 }
5748 if (mInputProfiles.size()) {
5749 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5750 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005751 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005752 write(fd, buffer, strlen(buffer));
5753 mInputProfiles[i]->dump(fd);
5754 }
5755 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005756 if (mDeclaredDevices.size()) {
5757 write(fd, " - devices:\n", strlen(" - devices:\n"));
5758 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5759 mDeclaredDevices[i]->dump(fd, 4, i);
5760 }
5761 }
Eric Laurente552edb2014-03-10 17:42:56 -07005762}
5763
Eric Laurent1c333e22014-05-20 10:48:17 -07005764// --- AudioPort class implementation
5765
Eric Laurenta121f902014-06-03 13:32:54 -07005766
5767AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5768 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07005769 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07005770{
5771 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5772 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5773}
5774
Eric Laurent1c333e22014-05-20 10:48:17 -07005775void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5776{
5777 port->role = mRole;
5778 port->type = mType;
5779 unsigned int i;
5780 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005781 if (mSamplingRates[i] != 0) {
5782 port->sample_rates[i] = mSamplingRates[i];
5783 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005784 }
5785 port->num_sample_rates = i;
5786 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005787 if (mChannelMasks[i] != 0) {
5788 port->channel_masks[i] = mChannelMasks[i];
5789 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005790 }
5791 port->num_channel_masks = i;
5792 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005793 if (mFormats[i] != 0) {
5794 port->formats[i] = mFormats[i];
5795 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005796 }
5797 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005798
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005799 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005800
5801 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5802 port->gains[i] = mGains[i]->mGain;
5803 }
5804 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005805}
5806
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005807void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5808 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5809 const uint32_t rate = port->mSamplingRates.itemAt(k);
5810 if (rate != 0) { // skip "dynamic" rates
5811 bool hasRate = false;
5812 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5813 if (rate == mSamplingRates.itemAt(l)) {
5814 hasRate = true;
5815 break;
5816 }
5817 }
5818 if (!hasRate) { // never import a sampling rate twice
5819 mSamplingRates.add(rate);
5820 }
5821 }
5822 }
5823 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5824 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5825 if (mask != 0) { // skip "dynamic" masks
5826 bool hasMask = false;
5827 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5828 if (mask == mChannelMasks.itemAt(l)) {
5829 hasMask = true;
5830 break;
5831 }
5832 }
5833 if (!hasMask) { // never import a channel mask twice
5834 mChannelMasks.add(mask);
5835 }
5836 }
5837 }
5838 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5839 const audio_format_t format = port->mFormats.itemAt(k);
5840 if (format != 0) { // skip "dynamic" formats
5841 bool hasFormat = false;
5842 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5843 if (format == mFormats.itemAt(l)) {
5844 hasFormat = true;
5845 break;
5846 }
5847 }
5848 if (!hasFormat) { // never import a channel mask twice
5849 mFormats.add(format);
5850 }
5851 }
5852 }
5853}
5854
5855void AudioPolicyManager::AudioPort::clearCapabilities() {
5856 mChannelMasks.clear();
5857 mFormats.clear();
5858 mSamplingRates.clear();
5859}
Eric Laurent1c333e22014-05-20 10:48:17 -07005860
5861void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5862{
5863 char *str = strtok(name, "|");
5864
5865 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5866 // rates should be read from the output stream after it is opened for the first time
5867 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5868 mSamplingRates.add(0);
5869 return;
5870 }
5871
5872 while (str != NULL) {
5873 uint32_t rate = atoi(str);
5874 if (rate != 0) {
5875 ALOGV("loadSamplingRates() adding rate %d", rate);
5876 mSamplingRates.add(rate);
5877 }
5878 str = strtok(NULL, "|");
5879 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005880}
5881
5882void AudioPolicyManager::AudioPort::loadFormats(char *name)
5883{
5884 char *str = strtok(name, "|");
5885
5886 // by convention, "0' in the first entry in mFormats indicates the supported formats
5887 // should be read from the output stream after it is opened for the first time
5888 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5889 mFormats.add(AUDIO_FORMAT_DEFAULT);
5890 return;
5891 }
5892
5893 while (str != NULL) {
5894 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5895 ARRAY_SIZE(sFormatNameToEnumTable),
5896 str);
5897 if (format != AUDIO_FORMAT_DEFAULT) {
5898 mFormats.add(format);
5899 }
5900 str = strtok(NULL, "|");
5901 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005902}
5903
5904void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5905{
5906 const char *str = strtok(name, "|");
5907
5908 ALOGV("loadInChannels() %s", name);
5909
5910 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5911 mChannelMasks.add(0);
5912 return;
5913 }
5914
5915 while (str != NULL) {
5916 audio_channel_mask_t channelMask =
5917 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5918 ARRAY_SIZE(sInChannelsNameToEnumTable),
5919 str);
5920 if (channelMask != 0) {
5921 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5922 mChannelMasks.add(channelMask);
5923 }
5924 str = strtok(NULL, "|");
5925 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005926}
5927
5928void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5929{
5930 const char *str = strtok(name, "|");
5931
5932 ALOGV("loadOutChannels() %s", name);
5933
5934 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5935 // masks should be read from the output stream after it is opened for the first time
5936 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5937 mChannelMasks.add(0);
5938 return;
5939 }
5940
5941 while (str != NULL) {
5942 audio_channel_mask_t channelMask =
5943 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5944 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5945 str);
5946 if (channelMask != 0) {
5947 mChannelMasks.add(channelMask);
5948 }
5949 str = strtok(NULL, "|");
5950 }
5951 return;
5952}
5953
Eric Laurent1afeecb2014-05-14 08:52:28 -07005954audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5955{
5956 const char *str = strtok(name, "|");
5957
5958 ALOGV("loadGainMode() %s", name);
5959 audio_gain_mode_t mode = 0;
5960 while (str != NULL) {
5961 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5962 ARRAY_SIZE(sGainModeNameToEnumTable),
5963 str);
5964 str = strtok(NULL, "|");
5965 }
5966 return mode;
5967}
5968
Eric Laurenta121f902014-06-03 13:32:54 -07005969void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005970{
5971 cnode *node = root->first_child;
5972
Eric Laurenta121f902014-06-03 13:32:54 -07005973 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005974
5975 while (node) {
5976 if (strcmp(node->name, GAIN_MODE) == 0) {
5977 gain->mGain.mode = loadGainMode((char *)node->value);
5978 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005979 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005980 gain->mGain.channel_mask =
5981 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5982 ARRAY_SIZE(sInChannelsNameToEnumTable),
5983 (char *)node->value);
5984 } else {
5985 gain->mGain.channel_mask =
5986 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5987 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5988 (char *)node->value);
5989 }
5990 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5991 gain->mGain.min_value = atoi((char *)node->value);
5992 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5993 gain->mGain.max_value = atoi((char *)node->value);
5994 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5995 gain->mGain.default_value = atoi((char *)node->value);
5996 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5997 gain->mGain.step_value = atoi((char *)node->value);
5998 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5999 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6000 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6001 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6002 }
6003 node = node->next;
6004 }
6005
6006 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6007 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6008
6009 if (gain->mGain.mode == 0) {
6010 return;
6011 }
6012 mGains.add(gain);
6013}
6014
6015void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6016{
6017 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006018 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006019 while (node) {
6020 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006021 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006022 node = node->next;
6023 }
6024}
6025
Glenn Kastencbd48022014-07-24 13:46:44 -07006026status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006027{
6028 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6029 if (mSamplingRates[i] == samplingRate) {
6030 return NO_ERROR;
6031 }
6032 }
6033 return BAD_VALUE;
6034}
6035
Glenn Kastencbd48022014-07-24 13:46:44 -07006036status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6037 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006038{
Glenn Kastencbd48022014-07-24 13:46:44 -07006039 // Search for the closest supported sampling rate that is above (preferred)
6040 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6041 // The sampling rates do not need to be sorted in ascending order.
6042 ssize_t maxBelow = -1;
6043 ssize_t minAbove = -1;
6044 uint32_t candidate;
6045 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6046 candidate = mSamplingRates[i];
6047 if (candidate == samplingRate) {
6048 if (updatedSamplingRate != NULL) {
6049 *updatedSamplingRate = candidate;
6050 }
6051 return NO_ERROR;
6052 }
6053 // candidate < desired
6054 if (candidate < samplingRate) {
6055 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6056 maxBelow = i;
6057 }
6058 // candidate > desired
6059 } else {
6060 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6061 minAbove = i;
6062 }
6063 }
6064 }
6065 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6066 // TODO Move these assumptions out.
6067 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6068 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6069 // due to approximation by an int32_t of the
6070 // phase increments
6071 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6072 if (minAbove >= 0) {
6073 candidate = mSamplingRates[minAbove];
6074 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6075 if (updatedSamplingRate != NULL) {
6076 *updatedSamplingRate = candidate;
6077 }
6078 return NO_ERROR;
6079 }
6080 }
6081 // But if we have to up-sample from a lower sampling rate, that's OK.
6082 if (maxBelow >= 0) {
6083 candidate = mSamplingRates[maxBelow];
6084 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6085 if (updatedSamplingRate != NULL) {
6086 *updatedSamplingRate = candidate;
6087 }
6088 return NO_ERROR;
6089 }
6090 }
6091 // leave updatedSamplingRate unmodified
6092 return BAD_VALUE;
6093}
6094
6095status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6096{
6097 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006098 if (mChannelMasks[i] == channelMask) {
6099 return NO_ERROR;
6100 }
6101 }
6102 return BAD_VALUE;
6103}
6104
Glenn Kastencbd48022014-07-24 13:46:44 -07006105status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6106 const
6107{
6108 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6109 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6110 // FIXME Does not handle multi-channel automatic conversions yet
6111 audio_channel_mask_t supported = mChannelMasks[i];
6112 if (supported == channelMask) {
6113 return NO_ERROR;
6114 }
6115 if (isRecordThread) {
6116 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6117 // FIXME Abstract this out to a table.
6118 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6119 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6120 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6121 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6122 return NO_ERROR;
6123 }
6124 }
6125 }
6126 return BAD_VALUE;
6127}
6128
Eric Laurenta121f902014-06-03 13:32:54 -07006129status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6130{
6131 for (size_t i = 0; i < mFormats.size(); i ++) {
6132 if (mFormats[i] == format) {
6133 return NO_ERROR;
6134 }
6135 }
6136 return BAD_VALUE;
6137}
6138
Eric Laurent1e693b52014-07-09 15:03:28 -07006139
6140uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6141{
6142 // special case for uninitialized dynamic profile
6143 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6144 return 0;
6145 }
6146
Eric Laurent828bcff2014-09-07 12:26:06 -07006147 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6148 // channel count / sampling rate combination chosen will be supported by the connected
6149 // sink
6150 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6151 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6152 uint32_t samplingRate = UINT_MAX;
6153 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6154 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6155 samplingRate = mSamplingRates[i];
6156 }
6157 }
6158 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6159 }
6160
Eric Laurent1e693b52014-07-09 15:03:28 -07006161 uint32_t samplingRate = 0;
6162 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6163
6164 // For mixed output and inputs, use max mixer sampling rates. Do not
6165 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006166 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006167 maxRate = UINT_MAX;
6168 }
6169 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6170 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6171 samplingRate = mSamplingRates[i];
6172 }
6173 }
6174 return samplingRate;
6175}
6176
6177audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6178{
6179 // special case for uninitialized dynamic profile
6180 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6181 return AUDIO_CHANNEL_NONE;
6182 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006183 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006184
6185 // For direct outputs, pick minimum channel count: this helps ensuring that the
6186 // channel count / sampling rate combination chosen will be supported by the connected
6187 // sink
6188 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6189 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6190 uint32_t channelCount = UINT_MAX;
6191 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6192 uint32_t cnlCount;
6193 if (mUseInChannelMask) {
6194 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6195 } else {
6196 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6197 }
6198 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6199 channelMask = mChannelMasks[i];
6200 channelCount = cnlCount;
6201 }
6202 }
6203 return channelMask;
6204 }
6205
Eric Laurent1e693b52014-07-09 15:03:28 -07006206 uint32_t channelCount = 0;
6207 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6208
6209 // For mixed output and inputs, use max mixer channel count. Do not
6210 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006211 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006212 maxCount = UINT_MAX;
6213 }
6214 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6215 uint32_t cnlCount;
6216 if (mUseInChannelMask) {
6217 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6218 } else {
6219 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6220 }
6221 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6222 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006223 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006224 }
6225 }
6226 return channelMask;
6227}
6228
Andy Hung9a605382014-07-28 16:16:31 -07006229/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006230const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6231 AUDIO_FORMAT_DEFAULT,
6232 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006233 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006234 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006235 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006236 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006237};
6238
6239int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6240 audio_format_t format2)
6241{
6242 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6243 // compressed format and better than any PCM format. This is by design of pickFormat()
6244 if (!audio_is_linear_pcm(format1)) {
6245 if (!audio_is_linear_pcm(format2)) {
6246 return 0;
6247 }
6248 return 1;
6249 }
6250 if (!audio_is_linear_pcm(format2)) {
6251 return -1;
6252 }
6253
6254 int index1 = -1, index2 = -1;
6255 for (size_t i = 0;
6256 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6257 i ++) {
6258 if (sPcmFormatCompareTable[i] == format1) {
6259 index1 = i;
6260 }
6261 if (sPcmFormatCompareTable[i] == format2) {
6262 index2 = i;
6263 }
6264 }
6265 // format1 not found => index1 < 0 => format2 > format1
6266 // format2 not found => index2 < 0 => format2 < format1
6267 return index1 - index2;
6268}
6269
6270audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6271{
6272 // special case for uninitialized dynamic profile
6273 if (mFormats.size() == 1 && mFormats[0] == 0) {
6274 return AUDIO_FORMAT_DEFAULT;
6275 }
6276
6277 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006278 audio_format_t bestFormat =
6279 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6280 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006281 // For mixed output and inputs, use best mixer output format. Do not
6282 // limit format otherwise
6283 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6284 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006285 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006286 bestFormat = AUDIO_FORMAT_INVALID;
6287 }
6288
6289 for (size_t i = 0; i < mFormats.size(); i ++) {
6290 if ((compareFormats(mFormats[i], format) > 0) &&
6291 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6292 format = mFormats[i];
6293 }
6294 }
6295 return format;
6296}
6297
Eric Laurenta121f902014-06-03 13:32:54 -07006298status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6299 int index) const
6300{
6301 if (index < 0 || (size_t)index >= mGains.size()) {
6302 return BAD_VALUE;
6303 }
6304 return mGains[index]->checkConfig(gainConfig);
6305}
6306
Eric Laurent1afeecb2014-05-14 08:52:28 -07006307void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6308{
6309 const size_t SIZE = 256;
6310 char buffer[SIZE];
6311 String8 result;
6312
6313 if (mName.size() != 0) {
6314 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6315 result.append(buffer);
6316 }
6317
6318 if (mSamplingRates.size() != 0) {
6319 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6320 result.append(buffer);
6321 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006322 if (i == 0 && mSamplingRates[i] == 0) {
6323 snprintf(buffer, SIZE, "Dynamic");
6324 } else {
6325 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6326 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006327 result.append(buffer);
6328 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6329 }
6330 result.append("\n");
6331 }
6332
6333 if (mChannelMasks.size() != 0) {
6334 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6335 result.append(buffer);
6336 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006337 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6338
6339 if (i == 0 && mChannelMasks[i] == 0) {
6340 snprintf(buffer, SIZE, "Dynamic");
6341 } else {
6342 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6343 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006344 result.append(buffer);
6345 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6346 }
6347 result.append("\n");
6348 }
6349
6350 if (mFormats.size() != 0) {
6351 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6352 result.append(buffer);
6353 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006354 const char *formatStr = enumToString(sFormatNameToEnumTable,
6355 ARRAY_SIZE(sFormatNameToEnumTable),
6356 mFormats[i]);
6357 if (i == 0 && strcmp(formatStr, "") == 0) {
6358 snprintf(buffer, SIZE, "Dynamic");
6359 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006360 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006361 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006362 result.append(buffer);
6363 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6364 }
6365 result.append("\n");
6366 }
6367 write(fd, result.string(), result.size());
6368 if (mGains.size() != 0) {
6369 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6370 write(fd, buffer, strlen(buffer) + 1);
6371 result.append(buffer);
6372 for (size_t i = 0; i < mGains.size(); i++) {
6373 mGains[i]->dump(fd, spaces + 2, i);
6374 }
6375 }
6376}
6377
6378// --- AudioGain class implementation
6379
Eric Laurenta121f902014-06-03 13:32:54 -07006380AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006381{
Eric Laurenta121f902014-06-03 13:32:54 -07006382 mIndex = index;
6383 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006384 memset(&mGain, 0, sizeof(struct audio_gain));
6385}
6386
Eric Laurenta121f902014-06-03 13:32:54 -07006387void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6388{
6389 config->index = mIndex;
6390 config->mode = mGain.mode;
6391 config->channel_mask = mGain.channel_mask;
6392 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6393 config->values[0] = mGain.default_value;
6394 } else {
6395 uint32_t numValues;
6396 if (mUseInChannelMask) {
6397 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6398 } else {
6399 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6400 }
6401 for (size_t i = 0; i < numValues; i++) {
6402 config->values[i] = mGain.default_value;
6403 }
6404 }
6405 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6406 config->ramp_duration_ms = mGain.min_ramp_ms;
6407 }
6408}
6409
6410status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6411{
6412 if ((config->mode & ~mGain.mode) != 0) {
6413 return BAD_VALUE;
6414 }
6415 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6416 if ((config->values[0] < mGain.min_value) ||
6417 (config->values[0] > mGain.max_value)) {
6418 return BAD_VALUE;
6419 }
6420 } else {
6421 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6422 return BAD_VALUE;
6423 }
6424 uint32_t numValues;
6425 if (mUseInChannelMask) {
6426 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6427 } else {
6428 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6429 }
6430 for (size_t i = 0; i < numValues; i++) {
6431 if ((config->values[i] < mGain.min_value) ||
6432 (config->values[i] > mGain.max_value)) {
6433 return BAD_VALUE;
6434 }
6435 }
6436 }
6437 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6438 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6439 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6440 return BAD_VALUE;
6441 }
6442 }
6443 return NO_ERROR;
6444}
6445
Eric Laurent1afeecb2014-05-14 08:52:28 -07006446void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6447{
6448 const size_t SIZE = 256;
6449 char buffer[SIZE];
6450 String8 result;
6451
6452 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6453 result.append(buffer);
6454 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6455 result.append(buffer);
6456 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6457 result.append(buffer);
6458 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6459 result.append(buffer);
6460 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6461 result.append(buffer);
6462 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6463 result.append(buffer);
6464 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6465 result.append(buffer);
6466 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6467 result.append(buffer);
6468 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6469 result.append(buffer);
6470
6471 write(fd, result.string(), result.size());
6472}
6473
Eric Laurent1f2f2232014-06-02 12:01:23 -07006474// --- AudioPortConfig class implementation
6475
6476AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6477{
6478 mSamplingRate = 0;
6479 mChannelMask = AUDIO_CHANNEL_NONE;
6480 mFormat = AUDIO_FORMAT_INVALID;
6481 mGain.index = -1;
6482}
6483
Eric Laurenta121f902014-06-03 13:32:54 -07006484status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6485 const struct audio_port_config *config,
6486 struct audio_port_config *backupConfig)
6487{
6488 struct audio_port_config localBackupConfig;
6489 status_t status = NO_ERROR;
6490
6491 localBackupConfig.config_mask = config->config_mask;
6492 toAudioPortConfig(&localBackupConfig);
6493
Marco Nelissen961ec212014-08-25 15:58:39 -07006494 sp<AudioPort> audioport = getAudioPort();
6495 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006496 status = NO_INIT;
6497 goto exit;
6498 }
6499 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006500 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006501 if (status != NO_ERROR) {
6502 goto exit;
6503 }
6504 mSamplingRate = config->sample_rate;
6505 }
6506 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006507 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006508 if (status != NO_ERROR) {
6509 goto exit;
6510 }
6511 mChannelMask = config->channel_mask;
6512 }
6513 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006514 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006515 if (status != NO_ERROR) {
6516 goto exit;
6517 }
6518 mFormat = config->format;
6519 }
6520 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006521 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006522 if (status != NO_ERROR) {
6523 goto exit;
6524 }
6525 mGain = config->gain;
6526 }
6527
6528exit:
6529 if (status != NO_ERROR) {
6530 applyAudioPortConfig(&localBackupConfig);
6531 }
6532 if (backupConfig != NULL) {
6533 *backupConfig = localBackupConfig;
6534 }
6535 return status;
6536}
6537
Eric Laurent1f2f2232014-06-02 12:01:23 -07006538void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6539 struct audio_port_config *dstConfig,
6540 const struct audio_port_config *srcConfig) const
6541{
6542 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6543 dstConfig->sample_rate = mSamplingRate;
6544 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6545 dstConfig->sample_rate = srcConfig->sample_rate;
6546 }
6547 } else {
6548 dstConfig->sample_rate = 0;
6549 }
6550 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6551 dstConfig->channel_mask = mChannelMask;
6552 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6553 dstConfig->channel_mask = srcConfig->channel_mask;
6554 }
6555 } else {
6556 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6557 }
6558 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6559 dstConfig->format = mFormat;
6560 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6561 dstConfig->format = srcConfig->format;
6562 }
6563 } else {
6564 dstConfig->format = AUDIO_FORMAT_INVALID;
6565 }
6566 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6567 dstConfig->gain = mGain;
6568 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6569 dstConfig->gain = srcConfig->gain;
6570 }
6571 } else {
6572 dstConfig->gain.index = -1;
6573 }
6574 if (dstConfig->gain.index != -1) {
6575 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6576 } else {
6577 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6578 }
6579}
6580
Eric Laurent1c333e22014-05-20 10:48:17 -07006581// --- IOProfile class implementation
6582
Eric Laurent1afeecb2014-05-14 08:52:28 -07006583AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006584 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006585 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006586{
6587}
6588
Eric Laurente0720872014-03-11 09:30:41 -07006589AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006590{
6591}
6592
6593// checks if the IO profile is compatible with specified parameters.
6594// Sampling rate, format and channel mask must be specified in order to
6595// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006596bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006597 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006598 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006599 audio_format_t format,
6600 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006601 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006602{
Glenn Kastencbd48022014-07-24 13:46:44 -07006603 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6604 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6605 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006606
Glenn Kastencbd48022014-07-24 13:46:44 -07006607 if ((mSupportedDevices.types() & device) != device) {
6608 return false;
6609 }
6610
6611 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006612 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006613 }
6614 uint32_t myUpdatedSamplingRate = samplingRate;
6615 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006616 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006617 }
6618 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6619 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006620 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006621 }
6622
6623 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6624 return false;
6625 }
6626
6627 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6628 checkExactChannelMask(channelMask) != NO_ERROR)) {
6629 return false;
6630 }
6631 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6632 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6633 return false;
6634 }
6635
6636 if (isPlaybackThread && (mFlags & flags) != flags) {
6637 return false;
6638 }
6639 // The only input flag that is allowed to be different is the fast flag.
6640 // An existing fast stream is compatible with a normal track request.
6641 // An existing normal stream is compatible with a fast track request,
6642 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006643 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006644 ~AUDIO_INPUT_FLAG_FAST)) {
6645 return false;
6646 }
6647
6648 if (updatedSamplingRate != NULL) {
6649 *updatedSamplingRate = myUpdatedSamplingRate;
6650 }
6651 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006652}
6653
Eric Laurente0720872014-03-11 09:30:41 -07006654void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006655{
6656 const size_t SIZE = 256;
6657 char buffer[SIZE];
6658 String8 result;
6659
Eric Laurent1afeecb2014-05-14 08:52:28 -07006660 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006661
Eric Laurente552edb2014-03-10 17:42:56 -07006662 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6663 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006664 snprintf(buffer, SIZE, " - devices:\n");
6665 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006666 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006667 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6668 mSupportedDevices[i]->dump(fd, 6, i);
6669 }
Eric Laurente552edb2014-03-10 17:42:56 -07006670}
6671
Eric Laurentd4692962014-05-05 18:13:44 -07006672void AudioPolicyManager::IOProfile::log()
6673{
6674 const size_t SIZE = 256;
6675 char buffer[SIZE];
6676 String8 result;
6677
6678 ALOGV(" - sampling rates: ");
6679 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6680 ALOGV(" %d", mSamplingRates[i]);
6681 }
6682
6683 ALOGV(" - channel masks: ");
6684 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6685 ALOGV(" 0x%04x", mChannelMasks[i]);
6686 }
6687
6688 ALOGV(" - formats: ");
6689 for (size_t i = 0; i < mFormats.size(); i++) {
6690 ALOGV(" 0x%08x", mFormats[i]);
6691 }
6692
6693 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6694 ALOGV(" - flags: 0x%04x\n", mFlags);
6695}
6696
6697
Eric Laurent3a4311c2014-03-17 12:00:47 -07006698// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006699
Eric Laurent1f2f2232014-06-02 12:01:23 -07006700
6701AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6702 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6703 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6704 AUDIO_PORT_ROLE_SOURCE,
6705 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006706 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006707{
Eric Laurenta121f902014-06-03 13:32:54 -07006708 if (mGains.size() > 0) {
6709 mGains[0]->getDefaultConfig(&mGain);
6710 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006711}
6712
Eric Laurent3a4311c2014-03-17 12:00:47 -07006713bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006714{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006715 // Devices are considered equal if they:
6716 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6717 // - have the same address or one device does not specify the address
6718 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006719 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006720 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006721 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006722 mChannelMask == other->mChannelMask);
6723}
6724
6725void AudioPolicyManager::DeviceVector::refreshTypes()
6726{
Eric Laurent1c333e22014-05-20 10:48:17 -07006727 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006728 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006729 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006730 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006731 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006732}
6733
6734ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6735{
6736 for(size_t i = 0; i < size(); i++) {
6737 if (item->equals(itemAt(i))) {
6738 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006739 }
6740 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006741 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006742}
6743
Eric Laurent3a4311c2014-03-17 12:00:47 -07006744ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006745{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006746 ssize_t ret = indexOf(item);
6747
6748 if (ret < 0) {
6749 ret = SortedVector::add(item);
6750 if (ret >= 0) {
6751 refreshTypes();
6752 }
6753 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006754 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006755 ret = -1;
6756 }
6757 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006758}
6759
Eric Laurent3a4311c2014-03-17 12:00:47 -07006760ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6761{
6762 size_t i;
6763 ssize_t ret = indexOf(item);
6764
6765 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006766 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006767 } else {
6768 ret = SortedVector::removeAt(ret);
6769 if (ret >= 0) {
6770 refreshTypes();
6771 }
6772 }
6773 return ret;
6774}
6775
6776void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6777{
6778 DeviceVector deviceList;
6779
6780 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6781 types &= ~role_bit;
6782
6783 while (types) {
6784 uint32_t i = 31 - __builtin_clz(types);
6785 uint32_t type = 1 << i;
6786 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006787 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006788 }
6789}
6790
Eric Laurent1afeecb2014-05-14 08:52:28 -07006791void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6792 const DeviceVector& declaredDevices)
6793{
6794 char *devName = strtok(name, "|");
6795 while (devName != NULL) {
6796 if (strlen(devName) != 0) {
6797 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6798 ARRAY_SIZE(sDeviceNameToEnumTable),
6799 devName);
6800 if (type != AUDIO_DEVICE_NONE) {
6801 add(new DeviceDescriptor(String8(""), type));
6802 } else {
6803 sp<DeviceDescriptor> deviceDesc =
6804 declaredDevices.getDeviceFromName(String8(devName));
6805 if (deviceDesc != 0) {
6806 add(deviceDesc);
6807 }
6808 }
6809 }
6810 devName = strtok(NULL, "|");
6811 }
6812}
6813
Eric Laurent1c333e22014-05-20 10:48:17 -07006814sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6815 audio_devices_t type, String8 address) const
6816{
6817 sp<DeviceDescriptor> device;
6818 for (size_t i = 0; i < size(); i++) {
6819 if (itemAt(i)->mDeviceType == type) {
6820 device = itemAt(i);
6821 if (itemAt(i)->mAddress = address) {
6822 break;
6823 }
6824 }
6825 }
6826 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6827 type, address.string(), device.get());
6828 return device;
6829}
6830
Eric Laurent6a94d692014-05-20 11:18:06 -07006831sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6832 audio_port_handle_t id) const
6833{
6834 sp<DeviceDescriptor> device;
6835 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006836 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006837 if (itemAt(i)->mId == id) {
6838 device = itemAt(i);
6839 break;
6840 }
6841 }
6842 return device;
6843}
6844
Eric Laurent1c333e22014-05-20 10:48:17 -07006845AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6846 audio_devices_t type) const
6847{
6848 DeviceVector devices;
6849 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6850 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6851 devices.add(itemAt(i));
6852 type &= ~itemAt(i)->mDeviceType;
6853 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6854 itemAt(i)->mDeviceType, itemAt(i).get());
6855 }
6856 }
6857 return devices;
6858}
6859
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006860AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6861 audio_devices_t type, String8 address) const
6862{
6863 DeviceVector devices;
6864 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6865 for (size_t i = 0; i < size(); i++) {
6866 //ALOGV(" at i=%d: device=%x, addr=%s",
6867 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6868 if (itemAt(i)->mDeviceType == type) {
6869 if (itemAt(i)->mAddress == address) {
6870 //ALOGV(" found matching address %s", address.string());
6871 devices.add(itemAt(i));
6872 }
6873 }
6874 }
6875 return devices;
6876}
6877
Eric Laurent1afeecb2014-05-14 08:52:28 -07006878sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6879 const String8& name) const
6880{
6881 sp<DeviceDescriptor> device;
6882 for (size_t i = 0; i < size(); i++) {
6883 if (itemAt(i)->mName == name) {
6884 device = itemAt(i);
6885 break;
6886 }
6887 }
6888 return device;
6889}
6890
Eric Laurent6a94d692014-05-20 11:18:06 -07006891void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6892 struct audio_port_config *dstConfig,
6893 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006894{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006895 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6896 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006897 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006898 }
6899
6900 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6901
Eric Laurent6a94d692014-05-20 11:18:06 -07006902 dstConfig->id = mId;
6903 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006904 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006905 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006906 dstConfig->ext.device.type = mDeviceType;
6907 dstConfig->ext.device.hw_module = mModule->mHandle;
6908 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006909}
6910
6911void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6912{
Eric Laurent83b88082014-06-20 18:31:16 -07006913 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006914 AudioPort::toAudioPort(port);
6915 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006916 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006917 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006918 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006919 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6920}
6921
Eric Laurent1afeecb2014-05-14 08:52:28 -07006922status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006923{
6924 const size_t SIZE = 256;
6925 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006926 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006927
Eric Laurent1afeecb2014-05-14 08:52:28 -07006928 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6929 result.append(buffer);
6930 if (mId != 0) {
6931 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6932 result.append(buffer);
6933 }
6934 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6935 enumToString(sDeviceNameToEnumTable,
6936 ARRAY_SIZE(sDeviceNameToEnumTable),
6937 mDeviceType));
6938 result.append(buffer);
6939 if (mAddress.size() != 0) {
6940 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6941 result.append(buffer);
6942 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006943 write(fd, result.string(), result.size());
6944 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006945
6946 return NO_ERROR;
6947}
6948
Eric Laurent4d416952014-08-10 14:07:09 -07006949status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6950{
6951 const size_t SIZE = 256;
6952 char buffer[SIZE];
6953 String8 result;
6954
6955
6956 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6957 result.append(buffer);
6958 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6959 result.append(buffer);
6960 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6961 result.append(buffer);
6962 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6963 result.append(buffer);
6964 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6965 result.append(buffer);
6966 for (size_t i = 0; i < mPatch.num_sources; i++) {
6967 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6968 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6969 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6970 ARRAY_SIZE(sDeviceNameToEnumTable),
6971 mPatch.sources[i].ext.device.type));
6972 } else {
6973 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6974 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6975 }
6976 result.append(buffer);
6977 }
6978 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6979 result.append(buffer);
6980 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6981 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
6982 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6983 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
6984 ARRAY_SIZE(sDeviceNameToEnumTable),
6985 mPatch.sinks[i].ext.device.type));
6986 } else {
6987 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6988 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
6989 }
6990 result.append(buffer);
6991 }
6992
6993 write(fd, result.string(), result.size());
6994 return NO_ERROR;
6995}
Eric Laurent3a4311c2014-03-17 12:00:47 -07006996
6997// --- audio_policy.conf file parsing
6998
Eric Laurent5dbe4712014-09-19 19:04:57 -07006999uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007000{
7001 uint32_t flag = 0;
7002
7003 // it is OK to cast name to non const here as we are not going to use it after
7004 // strtok() modifies it
7005 char *flagName = strtok(name, "|");
7006 while (flagName != NULL) {
7007 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007008 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7009 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007010 flagName);
7011 }
7012 flagName = strtok(NULL, "|");
7013 }
7014 //force direct flag if offload flag is set: offloading implies a direct output stream
7015 // and all common behaviors are driven by checking only the direct flag
7016 // this should normally be set appropriately in the policy configuration file
7017 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7018 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7019 }
7020
Eric Laurent5dbe4712014-09-19 19:04:57 -07007021 return flag;
7022}
7023
7024uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7025{
7026 uint32_t flag = 0;
7027
7028 // it is OK to cast name to non const here as we are not going to use it after
7029 // strtok() modifies it
7030 char *flagName = strtok(name, "|");
7031 while (flagName != NULL) {
7032 if (strlen(flagName) != 0) {
7033 flag |= stringToEnum(sInputFlagNameToEnumTable,
7034 ARRAY_SIZE(sInputFlagNameToEnumTable),
7035 flagName);
7036 }
7037 flagName = strtok(NULL, "|");
7038 }
7039 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007040}
7041
Eric Laurente0720872014-03-11 09:30:41 -07007042audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007043{
7044 uint32_t device = 0;
7045
7046 char *devName = strtok(name, "|");
7047 while (devName != NULL) {
7048 if (strlen(devName) != 0) {
7049 device |= stringToEnum(sDeviceNameToEnumTable,
7050 ARRAY_SIZE(sDeviceNameToEnumTable),
7051 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007052 }
Eric Laurente552edb2014-03-10 17:42:56 -07007053 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007054 }
Eric Laurente552edb2014-03-10 17:42:56 -07007055 return device;
7056}
7057
Eric Laurente0720872014-03-11 09:30:41 -07007058void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007059{
Eric Laurente552edb2014-03-10 17:42:56 -07007060 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007061 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007062 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007063
Eric Laurent1afeecb2014-05-14 08:52:28 -07007064 node = config_find(root, DEVICES_TAG);
7065 if (node != NULL) {
7066 node = node->first_child;
7067 while (node) {
7068 ALOGV("loadHwModule() loading device %s", node->name);
7069 status_t tmpStatus = module->loadDevice(node);
7070 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7071 status = tmpStatus;
7072 }
7073 node = node->next;
7074 }
7075 }
7076 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007077 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007078 node = node->first_child;
7079 while (node) {
7080 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007081 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007082 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7083 status = tmpStatus;
7084 }
7085 node = node->next;
7086 }
7087 }
7088 node = config_find(root, INPUTS_TAG);
7089 if (node != NULL) {
7090 node = node->first_child;
7091 while (node) {
7092 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007093 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007094 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7095 status = tmpStatus;
7096 }
7097 node = node->next;
7098 }
7099 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007100 loadGlobalConfig(root, module);
7101
Eric Laurente552edb2014-03-10 17:42:56 -07007102 if (status == NO_ERROR) {
7103 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007104 }
7105}
7106
Eric Laurente0720872014-03-11 09:30:41 -07007107void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007108{
7109 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7110 if (node == NULL) {
7111 return;
7112 }
7113
7114 node = node->first_child;
7115 while (node) {
7116 ALOGV("loadHwModules() loading module %s", node->name);
7117 loadHwModule(node);
7118 node = node->next;
7119 }
7120}
7121
Eric Laurent1f2f2232014-06-02 12:01:23 -07007122void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007123{
7124 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007125
Eric Laurente552edb2014-03-10 17:42:56 -07007126 if (node == NULL) {
7127 return;
7128 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007129 DeviceVector declaredDevices;
7130 if (module != NULL) {
7131 declaredDevices = module->mDeclaredDevices;
7132 }
7133
Eric Laurente552edb2014-03-10 17:42:56 -07007134 node = node->first_child;
7135 while (node) {
7136 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007137 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7138 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007139 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7140 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007141 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007142 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007143 ARRAY_SIZE(sDeviceNameToEnumTable),
7144 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007145 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007146 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007147 } else {
7148 ALOGW("loadGlobalConfig() default device not specified");
7149 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007150 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007151 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007152 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7153 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007154 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007155 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7156 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7157 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007158 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7159 uint32_t major, minor;
7160 sscanf((char *)node->value, "%u.%u", &major, &minor);
7161 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7162 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7163 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007164 }
7165 node = node->next;
7166 }
7167}
7168
Eric Laurente0720872014-03-11 09:30:41 -07007169status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007170{
7171 cnode *root;
7172 char *data;
7173
7174 data = (char *)load_file(path, NULL);
7175 if (data == NULL) {
7176 return -ENODEV;
7177 }
7178 root = config_node("", "");
7179 config_load(root, data);
7180
Eric Laurente552edb2014-03-10 17:42:56 -07007181 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007182 // legacy audio_policy.conf files have one global_configuration section
7183 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007184 config_free(root);
7185 free(root);
7186 free(data);
7187
7188 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7189
7190 return NO_ERROR;
7191}
7192
Eric Laurente0720872014-03-11 09:30:41 -07007193void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007194{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007195 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007196 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007197 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7198 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007199 mAvailableOutputDevices.add(mDefaultOutputDevice);
7200 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007201
7202 module = new HwModule("primary");
7203
Eric Laurent1afeecb2014-05-14 08:52:28 -07007204 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007205 profile->mSamplingRates.add(44100);
7206 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7207 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007208 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007209 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7210 module->mOutputProfiles.add(profile);
7211
Eric Laurent1afeecb2014-05-14 08:52:28 -07007212 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007213 profile->mSamplingRates.add(8000);
7214 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7215 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007216 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007217 module->mInputProfiles.add(profile);
7218
7219 mHwModules.add(module);
7220}
7221
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007222audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7223{
7224 // flags to stream type mapping
7225 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7226 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7227 }
7228 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7229 return AUDIO_STREAM_BLUETOOTH_SCO;
7230 }
7231
7232 // usage to stream type mapping
7233 switch (attr->usage) {
7234 case AUDIO_USAGE_MEDIA:
7235 case AUDIO_USAGE_GAME:
7236 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7237 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7238 return AUDIO_STREAM_MUSIC;
7239 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7240 return AUDIO_STREAM_SYSTEM;
7241 case AUDIO_USAGE_VOICE_COMMUNICATION:
7242 return AUDIO_STREAM_VOICE_CALL;
7243
7244 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7245 return AUDIO_STREAM_DTMF;
7246
7247 case AUDIO_USAGE_ALARM:
7248 return AUDIO_STREAM_ALARM;
7249 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7250 return AUDIO_STREAM_RING;
7251
7252 case AUDIO_USAGE_NOTIFICATION:
7253 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7254 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7255 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7256 case AUDIO_USAGE_NOTIFICATION_EVENT:
7257 return AUDIO_STREAM_NOTIFICATION;
7258
7259 case AUDIO_USAGE_UNKNOWN:
7260 default:
7261 return AUDIO_STREAM_MUSIC;
7262 }
7263}
Eric Laurente552edb2014-03-10 17:42:56 -07007264}; // namespace android