blob: d7cf88ee72b765d366ff638855b55383e57fad3e [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
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070041
François Gaffie2110e042015-03-24 08:41:51 +010042#include <AudioPolicyManagerInterface.h>
43#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080047#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070049#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070051#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
Eric Laurente552edb2014-03-10 17:42:56 -070077// ----------------------------------------------------------------------------
78// AudioPolicyInterface implementation
79// ----------------------------------------------------------------------------
80
Eric Laurente0720872014-03-11 09:30:41 -070081status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080082 audio_policy_dev_state_t state,
83 const char *device_address,
84 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070085{
jiabina7b43792018-02-15 16:04:46 -080086 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
87 nextAudioPortGeneration();
88 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080089}
90
François Gaffie11d30102018-11-02 16:09:09 +010091void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
92 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +020093{
François Gaffie11d30102018-11-02 16:09:09 +010094 AudioParameter param(device->address());
François Gaffie44481e72016-04-20 07:49:57 +020095 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070096 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +010097 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +020098 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
99}
100
François Gaffie11d30102018-11-02 16:09:09 +0100101status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800102 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800103 const char *device_address,
104 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800105{
Paul McLeane743a472015-01-28 11:07:31 -0800106 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
François Gaffie11d30102018-11-02 16:09:09 +0100107 deviceType, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700108
109 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100110 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700111
François Gaffie11d30102018-11-02 16:09:09 +0100112 sp<DeviceDescriptor> device =
Francois Gaffie716e1432019-01-14 16:58:59 +0100113 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name,
114 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
115 if (device == 0) {
116 return INVALID_OPERATION;
117 }
Paul McLeane743a472015-01-28 11:07:31 -0800118
Eric Laurente552edb2014-03-10 17:42:56 -0700119 // handle output devices
François Gaffie11d30102018-11-02 16:09:09 +0100120 if (audio_is_output_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700121 SortedVector <audio_io_handle_t> outputs;
122
François Gaffie11d30102018-11-02 16:09:09 +0100123 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700124
Eric Laurente552edb2014-03-10 17:42:56 -0700125 // save a copy of the opened output descriptors before any output is opened or closed
126 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
127 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700128 switch (state)
129 {
130 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800131 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700132 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100133 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700134 return INVALID_OPERATION;
135 }
François Gaffie11d30102018-11-02 16:09:09 +0100136 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700137
Eric Laurente552edb2014-03-10 17:42:56 -0700138 // register new device as available
Francois Gaffie716e1432019-01-14 16:58:59 +0100139 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700140 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700141 }
142
François Gaffie44481e72016-04-20 07:49:57 +0200143 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
144 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100145 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200146
François Gaffie11d30102018-11-02 16:09:09 +0100147 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
148 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200149
Francois Gaffie716e1432019-01-14 16:58:59 +0100150 mHwModules.cleanUpForDevice(device);
151
François Gaffie11d30102018-11-02 16:09:09 +0100152 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700153 return INVALID_OPERATION;
154 }
François Gaffie2110e042015-03-24 08:41:51 +0100155 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100156 mEngine->setDeviceConnectionState(device, state);
François Gaffie2110e042015-03-24 08:41:51 +0100157
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700158 // outputs should never be empty here
159 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
160 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100161 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800162
Eric Laurent3ae5f312015-02-03 17:12:08 -0800163 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700164 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700165 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700166 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100167 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700168 return INVALID_OPERATION;
169 }
170
François Gaffie11d30102018-11-02 16:09:09 +0100171 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700172
Paul McLeane743a472015-01-28 11:07:31 -0800173 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100174 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700175
Eric Laurente552edb2014-03-10 17:42:56 -0700176 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100177 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700178
François Gaffie11d30102018-11-02 16:09:09 +0100179 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100180
181 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100182 mEngine->setDeviceConnectionState(device, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700183 } break;
184
185 default:
François Gaffie11d30102018-11-02 16:09:09 +0100186 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700187 return BAD_VALUE;
188 }
189
Mikhail Naganov37977152018-07-11 15:54:44 -0700190 checkForDeviceAndOutputChanges([&]() {
191 // outputs must be closed after checkOutputForAllStrategies() is executed
192 if (!outputs.isEmpty()) {
193 for (audio_io_handle_t output : outputs) {
194 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100195 // close unused outputs after device disconnection or direct outputs that have
196 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700197 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
198 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
199 (desc->mDirectOpenCount == 0))) {
200 closeOutput(output);
201 }
Eric Laurente552edb2014-03-10 17:42:56 -0700202 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700203 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
204 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700205 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700206 return false;
207 });
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurent87ffa392015-05-22 10:32:38 -0700209 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100210 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
211 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700212 }
François Gaffie11d30102018-11-02 16:09:09 +0100213 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700214 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700215 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
216 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100217 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700218 // do not force device change on duplicated output because if device is 0, it will
219 // also force a device 0 for the two outputs it is duplicated to which may override
220 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100221 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100222 && !desc->isDuplicated()
François Gaffie11d30102018-11-02 16:09:09 +0100223 && (!device_distinguishes_on_address(deviceType)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700224 // always force when disconnecting (a non-duplicated device)
225 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100226 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700227 }
Eric Laurente552edb2014-03-10 17:42:56 -0700228 }
229
Eric Laurentd60560a2015-04-10 11:31:20 -0700230 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100231 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700232 }
233
Eric Laurent72aa32f2014-05-30 18:51:48 -0700234 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700235 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700236 } // end if is output device
237
Eric Laurente552edb2014-03-10 17:42:56 -0700238 // handle input devices
François Gaffie11d30102018-11-02 16:09:09 +0100239 if (audio_is_input_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700240 SortedVector <audio_io_handle_t> inputs;
241
François Gaffie11d30102018-11-02 16:09:09 +0100242 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700243 switch (state)
244 {
245 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700246 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700247 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100248 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700249 return INVALID_OPERATION;
250 }
François Gaffie44481e72016-04-20 07:49:57 +0200251 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
252 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100253 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200254
François Gaffie11d30102018-11-02 16:09:09 +0100255 if (checkInputsForDevice(device, state, inputs) != NO_ERROR) {
256 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100257
258 mHwModules.cleanUpForDevice(device);
259
Eric Laurentd4692962014-05-05 18:13:44 -0700260 return INVALID_OPERATION;
261 }
262
Francois Gaffie716e1432019-01-14 16:58:59 +0100263 if (mAvailableInputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 return NO_MEMORY;
265 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800266
François Gaffie2110e042015-03-24 08:41:51 +0100267 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100268 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700269 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700270
271 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700272 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700273 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100274 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700275 return INVALID_OPERATION;
276 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700277
François Gaffie11d30102018-11-02 16:09:09 +0100278 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700279
280 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100281 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700282
François Gaffie11d30102018-11-02 16:09:09 +0100283 checkInputsForDevice(device, state, inputs);
284 mAvailableInputDevices.remove(device);
Paul McLean5c477aa2014-08-20 16:47:57 -0700285
François Gaffie2110e042015-03-24 08:41:51 +0100286 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100287 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700288 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700289
290 default:
François Gaffie11d30102018-11-02 16:09:09 +0100291 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700292 return BAD_VALUE;
293 }
294
Eric Laurentd4692962014-05-05 18:13:44 -0700295 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700296 // As the input device list can impact the output device selection, update
297 // getDeviceForStrategy() cache
298 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700299
Eric Laurent87ffa392015-05-22 10:32:38 -0700300 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100301 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
302 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700303 }
304
Eric Laurentd60560a2015-04-10 11:31:20 -0700305 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100306 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700307 }
308
Eric Laurentb52c1522014-05-20 11:27:36 -0700309 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700310 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700311 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700312
François Gaffie11d30102018-11-02 16:09:09 +0100313 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700314 return BAD_VALUE;
315}
316
Eric Laurente0720872014-03-11 09:30:41 -0700317audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100318 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700319{
Eric Laurent634b7142016-04-20 13:48:02 -0700320 sp<DeviceDescriptor> devDesc =
Francois Gaffie716e1432019-01-14 16:58:59 +0100321 mHwModules.getDeviceDescriptor(device, device_address, "", false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700322 (strlen(device_address) != 0)/*matchAddress*/);
323
324 if (devDesc == 0) {
325 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
326 device, device_address);
327 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
328 }
François Gaffie53615e22015-03-19 09:24:12 +0100329
Eric Laurent3a4311c2014-03-17 12:00:47 -0700330 DeviceVector *deviceVector;
331
Eric Laurente552edb2014-03-10 17:42:56 -0700332 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700333 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700334 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700335 deviceVector = &mAvailableInputDevices;
336 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100337 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700338 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700339 }
Eric Laurent634b7142016-04-20 13:48:02 -0700340
341 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
342 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800343}
344
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800345status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
346 const char *device_address,
347 const char *device_name)
348{
349 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700350 String8 reply;
351 AudioParameter param;
352 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800353
354 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
355 device, device_address, device_name);
356
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800357 // connect/disconnect only 1 device at a time
358 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
359
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800360 // Check if the device is currently connected
361 sp<DeviceDescriptor> devDesc =
362 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Francois Gaffie716e1432019-01-14 16:58:59 +0100363 if (devDesc == 0 || mAvailableOutputDevices.indexOf(devDesc) < 0) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800364 // Nothing to do: device is not connected
365 return NO_ERROR;
366 }
367
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700368 // For offloaded A2DP, Hw modules may have the capability to
369 // configure codecs. Check if any of the loaded hw modules
370 // supports this.
371 // If supported, send a set parameter to configure A2DP codecs
372 // and return. No need to toggle device state.
373 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
374 reply = mpClientInterface->getParameters(
375 AUDIO_IO_HANDLE_NONE,
376 String8(AudioParameter::keyReconfigA2dpSupported));
377 AudioParameter repliedParameters(reply);
378 repliedParameters.getInt(
379 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
380 if (isReconfigA2dpSupported) {
381 const String8 key(AudioParameter::keyReconfigA2dp);
382 param.add(key, String8("true"));
383 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
384 return NO_ERROR;
385 }
386 }
387
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800388 // Toggle the device state: UNAVAILABLE -> AVAILABLE
389 // This will force reading again the device configuration
390 status = setDeviceConnectionState(device,
391 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
392 device_address, device_name);
393 if (status != NO_ERROR) {
394 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
395 status);
396 return status;
397 }
398
399 status = setDeviceConnectionState(device,
400 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
401 device_address, device_name);
402 if (status != NO_ERROR) {
403 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
404 status);
405 return status;
406 }
407
408 return NO_ERROR;
409}
410
François Gaffie11d30102018-11-02 16:09:09 +0100411uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700412{
413 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700414 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700415
François Gaffie11d30102018-11-02 16:09:09 +0100416 if(!hasPrimaryOutput() || mPrimaryOutput->devices().types() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700417 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700418 }
François Gaffie11d30102018-11-02 16:09:09 +0100419 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
420
Francois Gaffie716e1432019-01-14 16:58:59 +0100421 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
422 auto txDevice = getDeviceAndMixForAttributes(attr);
François Gaffie11d30102018-11-02 16:09:09 +0100423 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
424 rxDevices.toString().c_str(), txDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700425
426 // release existing RX patch if any
427 if (mCallRxPatch != 0) {
428 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
429 mCallRxPatch.clear();
430 }
431 // release TX patch if any
432 if (mCallTxPatch != 0) {
433 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
434 mCallTxPatch.clear();
435 }
436
437 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
438 // via setOutputDevice() on primary output.
439 // Otherwise, create two audio patches for TX and RX path.
François Gaffie11d30102018-11-02 16:09:09 +0100440 if (availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) {
441 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700442 // If the TX device is also on the primary HW module, setOutputDevice() will take care
443 // of it due to legacy implementation. If not, create a patch.
François Gaffie11d30102018-11-02 16:09:09 +0100444 if (!availablePrimaryModuleInputDevices().contains(txDevice)) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700445 createTxPatch = true;
446 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700447 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100448 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700449 createTxPatch = true;
450 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700451 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800452 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
453 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700454
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800455 return muteWaitMs;
456}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700457
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800458sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100459 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700460 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700461
François Gaffie11d30102018-11-02 16:09:09 +0100462 if (device == nullptr) {
463 return nullptr;
464 }
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800465 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100466 patchBuilder.addSink(device).
467 addSource(mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800468 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100469 patchBuilder.addSource(device).
470 addSink(mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800471 }
472
François Gaffie11d30102018-11-02 16:09:09 +0100473 // @TODO: still ignoring the address, or not dealing platform with mutliple telephonydevices
474 const sp<DeviceDescriptor> outputDevice = isRx ?
475 device : mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX);
476 SortedVector<audio_io_handle_t> outputs =
477 getOutputsForDevices(DeviceVector(outputDevice), mOutputs);
478 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800479 // request to reuse existing output stream if one is already opened to reach the target device
480 if (output != AUDIO_IO_HANDLE_NONE) {
481 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100482 ALOG_ASSERT(!outputDesc->isDuplicated(), "%s() %s device output %d is duplicated", __func__,
483 outputDevice->toString().c_str(), output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700484 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800485 }
486
487 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700488 // terminate active capture if on the same HW module as the call TX source device
489 // FIXME: would be better to refine to only inputs whose profile connects to the
490 // call TX device but this information is not in the audio patch and logic here must be
491 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800492 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100493 if (activeDesc->hasSameHwModuleAs(device)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700494 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700495 }
496 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700497 }
Eric Laurentdc462862016-07-19 12:29:53 -0700498
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800499 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700500 status_t status = mpClientInterface->createAudioPatch(
501 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800502 ALOGW_IF(status != NO_ERROR,
503 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
504 sp<AudioPatch> audioPatch;
505 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700506 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800507 audioPatch->mAfPatchHandle = afPatchHandle;
508 audioPatch->mUid = mUidCached;
509 }
510 return audioPatch;
511}
512
Mikhail Naganovdc769682018-05-04 15:34:08 -0700513sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100514 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700515 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800516 ALOG_ASSERT(!deviceList.isEmpty(),
517 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700518 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700519}
520
Mikhail Naganov100f0122018-11-29 11:22:16 -0800521audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
522 const DeviceVector& devices, const char *moduleId) const {
523 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
524 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
525}
526
527bool AudioPolicyManager::isDeviceOfModule(
528 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
529 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
530 if (module != 0) {
531 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
532 .indexOf(devDesc) != NAME_NOT_FOUND
533 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
534 .indexOf(devDesc) != NAME_NOT_FOUND;
535 }
536 return false;
537}
538
Eric Laurente0720872014-03-11 09:30:41 -0700539void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700540{
541 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100542 // store previous phone state for management of sonification strategy below
543 int oldState = mEngine->getPhoneState();
544
545 if (mEngine->setPhoneState(state) != NO_ERROR) {
546 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700547 return;
548 }
François Gaffie2110e042015-03-24 08:41:51 +0100549 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700550 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700551 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700552 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800553 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700554 }
555
François Gaffie2110e042015-03-24 08:41:51 +0100556 /**
557 * Switching to or from incall state or switching between telephony and VoIP lead to force
558 * routing command.
559 */
560 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
561 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700562
563 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700564 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700565
Eric Laurente552edb2014-03-10 17:42:56 -0700566 int delayMs = 0;
567 if (isStateInCall(state)) {
568 nsecs_t sysTime = systemTime();
569 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700570 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700571 // mute media and sonification strategies and delay device switch by the largest
572 // latency of any output where either strategy is active.
573 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100574 if ((isStrategyActive(desc, STRATEGY_MEDIA,
575 SONIFICATION_HEADSET_MUSIC_DELAY,
576 sysTime) ||
577 isStrategyActive(desc, STRATEGY_SONIFICATION,
578 SONIFICATION_HEADSET_MUSIC_DELAY,
579 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700580 (delayMs < (int)desc->latency()*2)) {
581 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700582 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700583 setStrategyMute(STRATEGY_MEDIA, true, desc);
584 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700585 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700586 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
587 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700588 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
589 }
590 }
591
Eric Laurent87ffa392015-05-22 10:32:38 -0700592 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100593 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700594 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100595 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700596 // force routing command to audio hardware when ending call
597 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100598 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
599 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700600 }
Eric Laurente552edb2014-03-10 17:42:56 -0700601
Eric Laurent87ffa392015-05-22 10:32:38 -0700602 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100603 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700604 } else if (oldState == AUDIO_MODE_IN_CALL) {
605 if (mCallRxPatch != 0) {
606 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
607 mCallRxPatch.clear();
608 }
609 if (mCallTxPatch != 0) {
610 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
611 mCallTxPatch.clear();
612 }
François Gaffie11d30102018-11-02 16:09:09 +0100613 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700614 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100615 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700616 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700617 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700618
619 // reevaluate routing on all outputs in case tracks have been started during the call
620 for (size_t i = 0; i < mOutputs.size(); i++) {
621 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100622 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700623 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100624 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700625 }
626 }
627
Eric Laurente552edb2014-03-10 17:42:56 -0700628 if (isStateInCall(state)) {
629 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700630 // force reevaluating accessibility routing when call starts
631 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700632 }
633
634 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700635 if (state == AUDIO_MODE_RINGTONE &&
636 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700637 mLimitRingtoneVolume = true;
638 } else {
639 mLimitRingtoneVolume = false;
640 }
641}
642
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700643audio_mode_t AudioPolicyManager::getPhoneState() {
644 return mEngine->getPhoneState();
645}
646
Eric Laurente0720872014-03-11 09:30:41 -0700647void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100648 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700649{
François Gaffie2110e042015-03-24 08:41:51 +0100650 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700651 if (config == mEngine->getForceUse(usage)) {
652 return;
653 }
Eric Laurente552edb2014-03-10 17:42:56 -0700654
François Gaffie2110e042015-03-24 08:41:51 +0100655 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
656 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
657 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700658 }
François Gaffie2110e042015-03-24 08:41:51 +0100659 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
660 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
661 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700662
663 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700664 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800665
Eric Laurentdc462862016-07-19 12:29:53 -0700666 //FIXME: workaround for truncated touch sounds
667 // to be removed when the problem is handled by system UI
668 uint32_t delayMs = 0;
669 uint32_t waitMs = 0;
670 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
671 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
672 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700673 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100674 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
675 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700676 }
Eric Laurente552edb2014-03-10 17:42:56 -0700677 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700678 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100679 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -0700680 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100681 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700682 }
François Gaffie11d30102018-11-02 16:09:09 +0100683 if (forceVolumeReeval && !newDevices.isEmpty()) {
684 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700685 }
686 }
687
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800688 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100689 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700690 // Force new input selection if the new device can not be reached via current input
Francois Gaffie716e1432019-01-14 16:58:59 +0100691 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800692 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700693 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800694 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700695 }
Eric Laurente552edb2014-03-10 17:42:56 -0700696 }
Eric Laurente552edb2014-03-10 17:42:56 -0700697}
698
Eric Laurente0720872014-03-11 09:30:41 -0700699void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700700{
701 ALOGV("setSystemProperty() property %s, value %s", property, value);
702}
703
Michael Chana94fbb22018-04-24 14:31:19 +1000704// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
705// search to profiles for direct outputs.
706sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100707 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000708 uint32_t samplingRate,
709 audio_format_t format,
710 audio_channel_mask_t channelMask,
711 audio_output_flags_t flags,
712 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700713{
Michael Chana94fbb22018-04-24 14:31:19 +1000714 if (directOnly) {
715 // only retain flags that will drive the direct output profile selection
716 // if explicitly requested
717 static const uint32_t kRelevantFlags =
718 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
719 AUDIO_OUTPUT_FLAG_VOIP_RX);
720 flags =
721 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
722 }
Eric Laurent861a6282015-05-18 15:40:16 -0700723
724 sp<IOProfile> profile;
725
Mikhail Naganovd4120142017-12-06 15:49:22 -0800726 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800727 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100728 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700729 samplingRate, NULL /*updatedSamplingRate*/,
730 format, NULL /*updatedFormat*/,
731 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700732 flags)) {
733 continue;
734 }
735 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100736 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700737 continue;
738 }
Michael Chana94fbb22018-04-24 14:31:19 +1000739 if (!directOnly) return curProfile;
740 // when searching for direct outputs, if several profiles are compatible, give priority
741 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100742 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700743 continue;
744 }
745 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100746 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700747 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700748 }
Eric Laurente552edb2014-03-10 17:42:56 -0700749 }
750 }
Eric Laurent861a6282015-05-18 15:40:16 -0700751 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700752}
753
Eric Laurentf4e63452017-11-06 19:31:46 +0000754audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700755{
Eric Laurent3b73df72014-03-11 09:06:29 -0700756 routing_strategy strategy = getStrategy(stream);
François Gaffie11d30102018-11-02 16:09:09 +0100757 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800758
759 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
760 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
761 // format, flags, etc. This may result in some discrepancy for functions that utilize
762 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
763 // and AudioSystem::getOutputSamplingRate().
764
François Gaffie11d30102018-11-02 16:09:09 +0100765 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
766 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700767
François Gaffie11d30102018-11-02 16:09:09 +0100768 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
769 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000770 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700771}
772
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700773status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
774 const audio_attributes_t *srcAttr,
775 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700776{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700777 if (srcAttr != NULL) {
778 if (!isValidAttributes(srcAttr)) {
779 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
780 __func__,
781 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
782 srcAttr->tags);
783 return BAD_VALUE;
784 }
785 *dstAttr = *srcAttr;
786 } else {
787 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
788 ALOGE("%s: invalid stream type", __func__);
789 return BAD_VALUE;
790 }
791 stream_type_to_audio_attributes(srcStream, dstAttr);
792 }
793 return NO_ERROR;
794}
795
796status_t AudioPolicyManager::getOutputForAttrInt(audio_attributes_t *resultAttr,
797 audio_io_handle_t *output,
798 audio_session_t session,
799 const audio_attributes_t *attr,
800 audio_stream_type_t *stream,
801 uid_t uid,
802 const audio_config_t *config,
803 audio_output_flags_t *flags,
804 audio_port_handle_t *selectedDeviceId)
805{
François Gaffie11d30102018-11-02 16:09:09 +0100806 DeviceVector devices;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700807 routing_strategy strategy;
François Gaffie11d30102018-11-02 16:09:09 +0100808 audio_devices_t deviceType = AUDIO_DEVICE_NONE;
Francois Gaffie716e1432019-01-14 16:58:59 +0100809 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100810 DeviceVector msdDevices = getMsdAudioOutDevices();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700811
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700812 status_t status = getAudioAttributes(resultAttr, attr, *stream);
813 if (status != NO_ERROR) {
814 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700815 }
816
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700817 ALOGV("%s usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700818 " session %d selectedDeviceId %d",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700819 __func__,
820 resultAttr->usage, resultAttr->content_type, resultAttr->tags, resultAttr->flags,
Francois Gaffie716e1432019-01-14 16:58:59 +0100821 session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700822
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700823 *stream = streamTypefromAttributesInt(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700824
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700825 strategy = getStrategyForAttr(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700826
Scott Randolph7b1fd232018-06-18 15:33:03 -0700827 // First check for explicit routing (eg. setPreferredDevice)
Francois Gaffie716e1432019-01-14 16:58:59 +0100828 sp<DeviceDescriptor> requestedDevice = mAvailableOutputDevices.getDeviceFromId(requestedPortId);
829 if (requestedDevice != nullptr) {
830 deviceType = requestedDevice->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700831 } else {
832 // If no explict route, is there a matching dynamic policy that applies?
833 sp<SwAudioOutputDescriptor> desc;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700834 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, desc) == NO_ERROR) {
Scott Randolph7b1fd232018-06-18 15:33:03 -0700835 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
836 if (!audio_has_proportional_frames(config->format)) {
837 return BAD_VALUE;
838 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700839 *stream = streamTypefromAttributesInt(resultAttr);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700840 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700841 AudioMix *mix = desc->mPolicyMix;
842 sp<DeviceDescriptor> deviceDesc =
843 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
844 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700845 ALOGV("%s returns output %d", __func__, *output);
846 return NO_ERROR;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700847 }
848
849 // Virtual sources must always be dynamicaly or explicitly routed
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700850 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
851 ALOGW("%s no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE", __func__);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700852 return BAD_VALUE;
853 }
François Gaffie11d30102018-11-02 16:09:09 +0100854 deviceType = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700855 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700856
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700857 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200858 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700859 }
860
Nadav Barb2f18162018-07-18 13:01:53 +0300861 // Set incall music only if device was explicitly set, and fallback to the device which is
862 // chosen by the engine if not.
863 // FIXME: provide a more generic approach which is not device specific and move this back
864 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200865 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
François Gaffie11d30102018-11-02 16:09:09 +0100866 if (deviceType == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700867 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300868 audio_is_linear_pcm(config->format) &&
869 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +0100870 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300871 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
872 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700873 // Get the devce type directly from the engine to bypass preferred route logic
François Gaffie11d30102018-11-02 16:09:09 +0100874 deviceType = mEngine->getDeviceForStrategy(strategy);
Nadav Barb2f18162018-07-18 13:01:53 +0300875 }
876 }
877
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700878 ALOGV("%s device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800879 "flags %#x",
François Gaffie11d30102018-11-02 16:09:09 +0100880 __func__,
881 deviceType, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700882
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100883 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +0100884 if (!msdDevices.isEmpty()) {
885 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
886 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(deviceType);
887 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(deviceDesc) == NO_ERROR) {
888 ALOGV("%s() Using MSD devices %s instead of device %s",
889 __func__, msdDevices.toString().c_str(), deviceDesc->toString().c_str());
890 deviceType = msdDevices.types();
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100891 } else {
892 *output = AUDIO_IO_HANDLE_NONE;
893 }
894 }
François Gaffie11d30102018-11-02 16:09:09 +0100895 devices = mAvailableOutputDevices.getDevicesFromTypeMask(deviceType);
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100896 if (*output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +0100897 *output = getOutputForDevices(devices, session, *stream, config, flags);
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100898 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800899 if (*output == AUDIO_IO_HANDLE_NONE) {
900 return INVALID_OPERATION;
901 }
Paul McLeanaa981192015-03-21 09:55:15 -0700902
François Gaffie11d30102018-11-02 16:09:09 +0100903 *selectedDeviceId = getFirstDeviceId(devices);
Eric Laurent2ac76942017-06-22 17:17:09 -0700904
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700905 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
906
907 return NO_ERROR;
908}
909
910status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
911 audio_io_handle_t *output,
912 audio_session_t session,
913 audio_stream_type_t *stream,
914 uid_t uid,
915 const audio_config_t *config,
916 audio_output_flags_t *flags,
917 audio_port_handle_t *selectedDeviceId,
918 audio_port_handle_t *portId)
919{
920 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
921 if (*portId != AUDIO_PORT_HANDLE_NONE) {
922 return INVALID_OPERATION;
923 }
Francois Gaffie716e1432019-01-14 16:58:59 +0100924 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700925 audio_attributes_t resultAttr;
926 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
927 config, flags, selectedDeviceId);
928 if (status != NO_ERROR) {
929 return status;
930 }
931
Eric Laurent8fc147b2018-07-22 19:13:55 -0700932 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
933 .format = config->format,
934 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700935 *portId = AudioPort::getNextUniqueId();
936
Eric Laurent8fc147b2018-07-22 19:13:55 -0700937 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700938 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffie716e1432019-01-14 16:58:59 +0100939 requestedPortId, *stream,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700940 getStrategyForAttr(&resultAttr),
Eric Laurent97ac8712018-07-27 18:59:02 -0700941 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700942 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700943 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700944
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700945 ALOGV("%s returns output %d selectedDeviceId %d for port ID %d",
Francois Gaffie716e1432019-01-14 16:58:59 +0100946 __func__, *output, requestedPortId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700947
Eric Laurente83b55d2014-11-14 10:06:21 -0800948 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700949}
950
François Gaffie11d30102018-11-02 16:09:09 +0100951audio_io_handle_t AudioPolicyManager::getOutputForDevices(
952 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -0800953 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700954 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800955 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200956 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700957{
Andy Hungc88b0642018-04-27 15:42:35 -0700958 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700959 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700960
Eric Laurente552edb2014-03-10 17:42:56 -0700961 // open a direct output if required by specified parameters
962 //force direct flag if offload flag is set: offloading implies a direct output stream
963 // and all common behaviors are driven by checking only the direct flag
964 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200965 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
966 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700967 }
Nadav Bar766fb022018-01-07 12:18:03 +0200968 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
969 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700970 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800971 // only allow deep buffering for music stream type
972 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200973 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700974 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200975 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700976 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
977 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200978 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800979 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700980 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200981 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700982 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200983 audio_is_linear_pcm(config->format) &&
984 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200985 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700986 AUDIO_OUTPUT_FLAG_DIRECT);
987 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700988 }
Eric Laurente552edb2014-03-10 17:42:56 -0700989
Nadav Bar766fb022018-01-07 12:18:03 +0200990
Eric Laurentb732cf52014-09-24 19:08:21 -0700991 sp<IOProfile> profile;
992
993 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700994 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200995 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800996 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
997 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700998 goto non_direct_output;
999 }
1000
Andy Hung2ddee192015-12-18 17:34:44 -08001001 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1002 // This prevents creating an offloaded track and tearing it down immediately after start
1003 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001004 // FIXME: We should check the audio session here but we do not have it in this context.
1005 // This may prevent offloading in rare situations where effects are left active by apps
1006 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001007
Nadav Bar766fb022018-01-07 12:18:03 +02001008 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001009 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001010 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001011 config->sample_rate,
1012 config->format,
1013 config->channel_mask,
1014 (audio_output_flags_t)*flags,
1015 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001016 }
1017
Eric Laurent1c333e22014-05-20 10:48:17 -07001018 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001019 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1020 for (size_t i = 0; i < mOutputs.size(); i++) {
1021 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1022 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1023 // reuse direct output if currently open by the same client
1024 // and configured with same parameters
1025 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001026 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001027 (config->channel_mask == desc->mChannelMask) &&
1028 (session == desc->mDirectClientSession)) {
1029 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001030 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001031 mOutputs.keyAt(i), session);
1032 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001033 }
1034 }
1035 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001036
1037 if (!profile->canOpenNewIo()) {
1038 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001039 }
Eric Laurent861a6282015-05-18 15:40:16 -07001040
Eric Laurent3974e3b2017-12-07 17:58:43 -08001041 sp<SwAudioOutputDescriptor> outputDesc =
1042 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001043
François Gaffie11d30102018-11-02 16:09:09 +01001044 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001045
Dean Wheatley3023b382018-08-09 07:42:40 +10001046 // MSD patch may be using the only output stream that can service this request. Release
1047 // MSD patch to prioritize this request over any active output on MSD.
1048 AudioPatchCollection msdPatches = getMsdPatches();
1049 for (size_t i = 0; i < msdPatches.size(); i++) {
1050 const auto& patch = msdPatches[i];
1051 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1052 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1053 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
François Gaffie11d30102018-11-02 16:09:09 +01001054 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001055 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1056 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1057 releaseAudioPatch(patch->mHandle, mUidCached);
1058 break;
1059 }
1060 }
1061 }
1062
François Gaffie11d30102018-11-02 16:09:09 +01001063 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001064
1065 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001066 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001067 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001068 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001069 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
François Gaffie11d30102018-11-02 16:09:09 +01001070 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1071 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
Eric Laurentfe231122017-11-17 17:48:06 -08001072 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1073 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001074 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001075 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001076 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001077 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001078 if (audio_is_linear_pcm(config->format) &&
1079 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001080 goto non_direct_output;
1081 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001082 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001083 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001084 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001085 outputDesc->mDirectClientSession = session;
1086
Eric Laurente552edb2014-03-10 17:42:56 -07001087 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001088 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001089 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001090 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001091 return output;
1092 }
1093
Eric Laurentb732cf52014-09-24 19:08:21 -07001094non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001095
1096 // A request for HW A/V sync cannot fallback to a mixed output because time
1097 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001098 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001099 return AUDIO_IO_HANDLE_NONE;
1100 }
1101
Eric Laurente552edb2014-03-10 17:42:56 -07001102 // ignoring channel mask due to downmix capability in mixer
1103
1104 // open a non direct output
1105
1106 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001107 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001108 // get which output is suitable for the specified stream. The actual
1109 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001110 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001111
Eric Laurent8838a382014-09-08 16:44:28 -07001112 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001113 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001114 output = selectOutput(outputs, *flags, config->format,
1115 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001116 }
François Gaffie11d30102018-11-02 16:09:09 +01001117 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001118 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001119 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001120
Eric Laurente552edb2014-03-10 17:42:56 -07001121 return output;
1122}
1123
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001124sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001125 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1126 mAvailableInputDevices);
1127 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1128}
1129
1130DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1131 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1132 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001133}
1134
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001135const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1136 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001137 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1138 if (msdModule != 0) {
1139 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1140 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1141 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1142 const struct audio_port_config *source = &patch->mPatch.sources[j];
1143 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1144 source->ext.device.hw_module == msdModule->getHandle()) {
1145 msdPatches.addAudioPatch(patch->mHandle, patch);
1146 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001147 }
1148 }
1149 }
1150 return msdPatches;
1151}
1152
François Gaffie11d30102018-11-02 16:09:09 +01001153status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001154 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1155{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001156 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001157 if (msdModule == nullptr) {
1158 ALOGE("%s() unable to get MSD module", __func__);
1159 return NO_INIT;
1160 }
1161 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1162 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001163 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001164 return NO_INIT;
1165 }
1166 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1167 if (inputProfiles.isEmpty()) {
1168 ALOGE("%s() no input profiles for MSD module", __func__);
1169 return NO_INIT;
1170 }
1171 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1172 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001173 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001174 return NO_INIT;
1175 }
1176 AudioProfileVector msdProfiles;
1177 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1178 for (const auto &inProfile : inputProfiles) {
1179 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1180 msdProfiles.appendVector(inProfile->getAudioProfiles());
1181 }
1182 }
1183 AudioProfileVector deviceProfiles;
1184 for (const auto &outProfile : outputProfiles) {
1185 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1186 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1187 }
1188 }
1189 struct audio_config_base bestSinkConfig;
1190 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1191 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1192 &bestSinkConfig);
1193 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001194 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1195 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001196 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001197 }
1198 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1199 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1200 sinkConfig->format = bestSinkConfig.format;
1201 // For encoded streams force direct flag to prevent downstream mixing.
1202 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1203 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1204 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1205 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1206 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1207 sourceConfig->format = bestSinkConfig.format;
1208 // Copy input stream directly without any processing (e.g. resampling).
1209 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1210 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1211 if (hwAvSync) {
1212 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1213 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1214 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1215 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1216 }
1217 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1218 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1219 sinkConfig->config_mask |= config_mask;
1220 sourceConfig->config_mask |= config_mask;
1221 return NO_ERROR;
1222}
1223
François Gaffie11d30102018-11-02 16:09:09 +01001224PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001225{
1226 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001227 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001228 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1229 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1230 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1231 // For now, we just forcefully try with HwAvSync first.
1232 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1233 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1234 getBestMsdAudioProfileFor(
1235 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1236 if (res == NO_ERROR) {
1237 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1238 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1239 }
1240 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1241 " supporting PCM format conversion.", __func__);
1242 return patchBuilder;
1243}
1244
François Gaffie11d30102018-11-02 16:09:09 +01001245status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1246 sp<DeviceDescriptor> device = outputDevice;
1247 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001248 // Use media strategy for unspecified output device. This should only
1249 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1250 // therefore invalidate explicit routing requests.
François Gaffie11d30102018-11-02 16:09:09 +01001251 DeviceVector devices = getDevicesForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1252 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1253 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001254 }
François Gaffie11d30102018-11-02 16:09:09 +01001255 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1256 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001257 const struct audio_patch* patch = patchBuilder.patch();
1258 const AudioPatchCollection msdPatches = getMsdPatches();
1259 if (!msdPatches.isEmpty()) {
1260 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1261 "The current MSD prototype only supports one output patch");
1262 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1263 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1264 return NO_ERROR;
1265 }
1266 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1267 }
1268 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1269 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1270 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1271 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001272 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1273 device->toString().c_str(), patch->sources[0].format,
1274 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001275 return status;
1276}
1277
Eric Laurente0720872014-03-11 09:30:41 -07001278audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001279 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001280 audio_format_t format,
1281 audio_channel_mask_t channelMask,
1282 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001283{
1284 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001285 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001286 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001287 // 1: the output supporting haptic playback when requesting haptic playback
1288 // 2: the output with the highest number of requested policy flags
1289 // 3: the output with the bit depth the closest to the requested one
1290 // 4: the primary output
1291 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001292
1293 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001294 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001295 }
1296 if (outputs.size() == 1) {
1297 return outputs[0];
1298 }
1299
1300 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001301 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1302 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001303 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1304 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1305 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001306 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1307 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001308
Eric Laurente78b6762018-12-19 16:29:01 -08001309 // Flags which must be present on both the request and the selected output
1310 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1311 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1312
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001313 for (audio_io_handle_t output : outputs) {
1314 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001315 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001316 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1317 continue;
1318 }
jiabin40573322018-11-08 12:08:02 -08001319 // If haptic channel is specified, use the haptic output if present.
1320 // When using haptic output, same audio format and sample rate are required.
1321 if (hapticChannelCount > 0) {
1322 // If haptic channel is specified, use the first output that
1323 // support haptic playback.
1324 if (audio_channel_count_from_out_mask(
1325 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1326 && format == outputDesc->mFormat
1327 && samplingRate == outputDesc->mSamplingRate) {
1328 return output;
1329 }
1330 } else {
1331 // When haptic channel is not specified, skip haptic output.
1332 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1333 continue;
1334 }
1335 }
Eric Laurente78b6762018-12-19 16:29:01 -08001336 if ((kMandatedFlags & flags) !=
1337 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1338 continue;
1339 }
jiabin40573322018-11-08 12:08:02 -08001340
Eric Laurent8838a382014-09-08 16:44:28 -07001341 // if a valid format is specified, skip output if not compatible
1342 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001343 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001344 continue;
1345 }
Eric Laurente6930022016-02-11 10:20:40 -08001346 if (AudioPort::isBetterFormatMatch(
1347 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001348 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001349 bestFormat = outputDesc->mFormat;
1350 }
Eric Laurent8838a382014-09-08 16:44:28 -07001351 }
1352
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001353 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001354 if (commonFlags >= maxCommonFlags) {
1355 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001356 if (format != AUDIO_FORMAT_INVALID
1357 && AudioPort::isBetterFormatMatch(
1358 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001359 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001360 bestFormatForFlags = outputDesc->mFormat;
1361 }
1362 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001363 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001364 maxCommonFlags = commonFlags;
1365 bestFormatForFlags = outputDesc->mFormat;
1366 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001367 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001368 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001369 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001370 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001371 }
1372 }
1373 }
1374
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001375 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001376 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001377 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001378 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001379 return outputForFormat;
1380 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001381 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001382 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001383 }
1384
1385 return outputs[0];
1386}
1387
Eric Laurent8fc147b2018-07-22 19:13:55 -07001388status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001389{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001390 ALOGV("%s portId %d", __FUNCTION__, portId);
1391
1392 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1393 if (outputDesc == 0) {
1394 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001395 return BAD_VALUE;
1396 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001397 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001398
Eric Laurent8fc147b2018-07-22 19:13:55 -07001399 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001400 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001401
Eric Laurent733ce942017-12-07 12:18:25 -08001402 status_t status = outputDesc->start();
1403 if (status != NO_ERROR) {
1404 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001405 }
1406
Eric Laurent97ac8712018-07-27 18:59:02 -07001407 uint32_t delayMs;
1408 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001409
1410 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001411 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001412 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001413 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001414 if (delayMs != 0) {
1415 usleep(delayMs * 1000);
1416 }
1417
1418 return status;
1419}
1420
Eric Laurent97ac8712018-07-27 18:59:02 -07001421status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1422 const sp<TrackClientDescriptor>& client,
1423 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001424{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001425 // cannot start playback of STREAM_TTS if any other output is being used
1426 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001427
1428 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001429 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001430 if (stream == AUDIO_STREAM_TTS) {
1431 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001432 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001433 return INVALID_OPERATION;
1434 } else {
1435 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1436 }
1437 } else {
1438 // some playback other than beacon starts
1439 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1440 }
1441
Eric Laurent77305a62016-07-25 16:39:22 -07001442 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001443 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001444 bool force = !outputDesc->isActive() &&
1445 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001446
François Gaffie11d30102018-11-02 16:09:09 +01001447 DeviceVector devices;
Eric Laurent97ac8712018-07-27 18:59:02 -07001448 AudioMix *policyMix = NULL;
1449 const char *address = NULL;
1450 if (outputDesc->mPolicyMix != NULL) {
1451 policyMix = outputDesc->mPolicyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001452 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001453 address = policyMix->mDeviceAddress.string();
1454 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
François Gaffie11d30102018-11-02 16:09:09 +01001455 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001456 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001457 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07001458 }
François Gaffie11d30102018-11-02 16:09:09 +01001459 devices.add(mAvailableOutputDevices.getDevice(newDeviceType, String8(address)));
Eric Laurent97ac8712018-07-27 18:59:02 -07001460 }
1461
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001462 // requiresMuteCheck is false when we can bypass mute strategy.
1463 // It covers a common case when there is no materially active audio
1464 // and muting would result in unnecessary delay and dropped audio.
1465 const uint32_t outputLatencyMs = outputDesc->latency();
1466 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1467
Eric Laurente552edb2014-03-10 17:42:56 -07001468 // increment usage count for this stream on the requested output:
1469 // NOTE that the usage count is the same for duplicated output and hardware output which is
1470 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001471 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001472
1473 if (client->hasPreferredDevice(true)) {
François Gaffie11d30102018-11-02 16:09:09 +01001474 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1475 if (devices != outputDesc->devices()) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001476 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1477 }
1478 }
Eric Laurente552edb2014-03-10 17:42:56 -07001479
Eric Laurent36829f92017-04-07 19:04:42 -07001480 if (stream == AUDIO_STREAM_MUSIC) {
1481 selectOutputForMusicEffects();
1482 }
1483
François Gaffie11d30102018-11-02 16:09:09 +01001484 if (outputDesc->streamActiveCount(stream) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001485 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001486 if (devices.isEmpty()) {
1487 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001488 }
Eric Laurent36829f92017-04-07 19:04:42 -07001489
Eric Laurente552edb2014-03-10 17:42:56 -07001490 routing_strategy strategy = getStrategy(stream);
1491 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001492 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1493 (beaconMuteLatency > 0);
1494 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001495 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001496 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001497 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001498 // An output has a shared device if
1499 // - managed by the same hw module
1500 // - supports the currently selected device
1501 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001502 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001503
Eric Laurent77305a62016-07-25 16:39:22 -07001504 // force a device change if any other output is:
1505 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001506 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001507 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001508 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001509 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001510 // change the device currently selected by the other output.
1511 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001512 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001513 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001514 force = true;
1515 }
1516 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001517 // a notification so that audio focus effect can propagate, or that a mute/unmute
1518 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001519 const uint32_t latencyMs = desc->latency();
1520 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1521
1522 if (shouldWait && isActive && (waitMs < latencyMs)) {
1523 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001524 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001525
1526 // Require mute check if another output is on a shared device
1527 // and currently active to have proper drain and avoid pops.
1528 // Note restoring AudioTracks onto this output needs to invoke
1529 // a volume ramp if there is no mute.
1530 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001531 }
1532 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001533
1534 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001535 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001536
Eric Laurente552edb2014-03-10 17:42:56 -07001537 // apply volume rules for current stream and device if necessary
1538 checkAndSetVolume(stream,
François Gaffie11d30102018-11-02 16:09:09 +01001539 mVolumeCurves->getVolumeIndex(stream, outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001540 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001541 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001542
1543 // update the outputs if starting an output with a stream that can affect notification
1544 // routing
1545 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001546
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001547 // force reevaluating accessibility routing when ringtone or alarm starts
1548 if (strategy == STRATEGY_SONIFICATION) {
1549 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1550 }
Eric Laurentdc462862016-07-19 12:29:53 -07001551
1552 if (waitMs > muteWaitMs) {
1553 *delayMs = waitMs - muteWaitMs;
1554 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001555
1556 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1557 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1558 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1559 // change occurs after the MixerThread starts and causes a stream volume
1560 // glitch.
1561 //
1562 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001563 }
Eric Laurentdc462862016-07-19 12:29:53 -07001564
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001565 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1566 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1567 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1568 }
1569
Eric Laurent97ac8712018-07-27 18:59:02 -07001570 // Automatically enable the remote submix input when output is started on a re routing mix
1571 // of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001572 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001573 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1574 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1575 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1576 address,
1577 "remote-submix");
1578 }
1579
Eric Laurente552edb2014-03-10 17:42:56 -07001580 return NO_ERROR;
1581}
1582
Eric Laurent8fc147b2018-07-22 19:13:55 -07001583status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001584{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001585 ALOGV("%s portId %d", __FUNCTION__, portId);
1586
1587 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1588 if (outputDesc == 0) {
1589 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001590 return BAD_VALUE;
1591 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001592 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001593
Eric Laurent97ac8712018-07-27 18:59:02 -07001594 ALOGV("stopOutput() output %d, stream %d, session %d",
1595 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001596
Eric Laurent97ac8712018-07-27 18:59:02 -07001597 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001598
Eric Laurent733ce942017-12-07 12:18:25 -08001599 if (status == NO_ERROR ) {
1600 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001601 }
1602 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001603}
1604
Eric Laurent97ac8712018-07-27 18:59:02 -07001605status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1606 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001607{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001608 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001609 audio_stream_type_t stream = client->stream();
1610
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001611 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1612
Eric Laurent592dd7b2018-08-05 18:58:48 -07001613 if (outputDesc->streamActiveCount(stream) > 0) {
1614 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001615 // Automatically disable the remote submix input when output is stopped on a
1616 // re routing mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001617 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001618 outputDesc->mPolicyMix != NULL &&
1619 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1620 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1621 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1622 outputDesc->mPolicyMix->mDeviceAddress,
1623 "remote-submix");
1624 }
1625 }
1626 bool forceDeviceUpdate = false;
1627 if (client->hasPreferredDevice(true)) {
1628 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1629 forceDeviceUpdate = true;
1630 }
1631
Eric Laurente552edb2014-03-10 17:42:56 -07001632 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001633 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001634
Eric Laurente552edb2014-03-10 17:42:56 -07001635 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001636 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001637 outputDesc->mStopTime[stream] = systemTime();
François Gaffie11d30102018-11-02 16:09:09 +01001638 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001639 // delay the device switch by twice the latency because stopOutput() is executed when
1640 // the track stop() command is received and at that time the audio track buffer can
1641 // still contain data that needs to be drained. The latency only covers the audio HAL
1642 // and kernel buffers. Also the latency does not always include additional delay in the
1643 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001644 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001645
1646 // force restoring the device selection on other active outputs if it differs from the
1647 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001648 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001649 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001650 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001651 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001652 desc->isActive() &&
1653 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001654 (newDevices != desc->devices())) {
1655 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1656 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001657
François Gaffie11d30102018-11-02 16:09:09 +01001658 setOutputDevices(desc, newDevices2, force, delayMs);
1659
Eric Laurent57de36c2016-09-28 16:59:11 -07001660 // re-apply device specific volume if not done by setOutputDevice()
1661 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001662 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001663 }
Eric Laurente552edb2014-03-10 17:42:56 -07001664 }
1665 }
1666 // update the outputs if stopping one with a stream that can affect notification routing
1667 handleNotificationRoutingForStream(stream);
1668 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001669
1670 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1671 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1672 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1673 }
1674
Eric Laurent36829f92017-04-07 19:04:42 -07001675 if (stream == AUDIO_STREAM_MUSIC) {
1676 selectOutputForMusicEffects();
1677 }
Eric Laurente552edb2014-03-10 17:42:56 -07001678 return NO_ERROR;
1679 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001680 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001681 return INVALID_OPERATION;
1682 }
1683}
1684
Eric Laurent8fc147b2018-07-22 19:13:55 -07001685void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001686{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001687 ALOGV("%s portId %d", __FUNCTION__, portId);
1688
1689 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1690 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001691 // If an output descriptor is closed due to a device routing change,
1692 // then there are race conditions with releaseOutput from tracks
1693 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1694 // destroyed shortly thereafter.
1695 //
1696 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001697 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001698 return;
1699 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001700
1701 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001702
Eric Laurent8fc147b2018-07-22 19:13:55 -07001703 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1704 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001705 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001706 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001707 return;
1708 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001709 if (--outputDesc->mDirectOpenCount == 0) {
1710 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001711 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001712 }
1713 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001714 // stopOutput() needs to be successfully called before releaseOutput()
1715 // otherwise there may be inaccurate stream reference counts.
1716 // This is checked in outputDesc->removeClient below.
1717 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001718}
1719
Eric Laurentcaf7f482014-11-25 17:50:47 -08001720status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1721 audio_io_handle_t *input,
1722 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001723 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001724 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001725 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001726 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001727 input_type_t *inputType,
1728 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001729{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001730 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001731 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001732 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001733
Eric Laurentad2e7b92017-09-14 20:06:42 -07001734 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001735 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001736 audio_attributes_t attributes = *attr;
Eric Laurentc722f302014-12-10 11:21:49 -08001737 AudioMix *policyMix = NULL;
François Gaffie11d30102018-11-02 16:09:09 +01001738 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001739 sp<AudioInputDescriptor> inputDesc;
1740 sp<RecordClientDescriptor> clientDesc;
1741 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001742 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001743
1744 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1745 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1746 return INVALID_OPERATION;
1747 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001748
Francois Gaffie716e1432019-01-14 16:58:59 +01001749 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1750 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001751 }
1752
Paul McLean466dc8e2015-04-17 13:15:36 -06001753 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001754 sp<DeviceDescriptor> explicitRoutingDevice =
1755 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001756
Eric Laurentad2e7b92017-09-14 20:06:42 -07001757 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1758 // possible
1759 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1760 *input != AUDIO_IO_HANDLE_NONE) {
1761 ssize_t index = mInputs.indexOfKey(*input);
1762 if (index < 0) {
1763 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1764 status = BAD_VALUE;
1765 goto error;
1766 }
1767 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001768 RecordClientVector clients = inputDesc->getClientsForSession(session);
1769 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001770 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1771 status = BAD_VALUE;
1772 goto error;
1773 }
1774 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1775 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001776 // corresponds to a new client and is only permitted from the same UID.
1777 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001778 if (clients.size() > 1) {
1779 for (const auto& client : clients) {
1780 // The client map is ordered by key values (portId) and portIds are allocated
1781 // incrementaly. So the first client in this list is the one opened by audio flinger
1782 // when the mmap stream is created and should be ignored as it does not correspond
1783 // to an actual client
1784 if (client == *clients.cbegin()) {
1785 continue;
1786 }
1787 if (uid != client->uid() && !client->isSilenced()) {
1788 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1789 uid, client->portId(), client->uid());
1790 status = INVALID_OPERATION;
1791 goto error;
1792 }
Eric Laurent331679c2018-04-16 17:03:16 -07001793 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001794 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001795 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001796 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001797
Eric Laurent8f42ea12018-08-08 09:08:25 -07001798 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001799 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001800 }
1801
1802 *input = AUDIO_IO_HANDLE_NONE;
1803 *inputType = API_INPUT_INVALID;
1804
Francois Gaffie716e1432019-01-14 16:58:59 +01001805 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001806
Francois Gaffie716e1432019-01-14 16:58:59 +01001807 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1808 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1809 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001810 if (status != NO_ERROR) {
1811 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001812 }
1813 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
François Gaffie11d30102018-11-02 16:09:09 +01001814 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1815 String8(attr->tags + strlen("addr=")));
Eric Laurent275e8e92014-11-30 15:14:47 -08001816 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001817 if (explicitRoutingDevice != nullptr) {
1818 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07001819 } else {
Francois Gaffie716e1432019-01-14 16:58:59 +01001820 device = getDeviceAndMixForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07001821 }
François Gaffie11d30102018-11-02 16:09:09 +01001822 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001823 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001824 status = BAD_VALUE;
1825 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001826 }
François Gaffie11d30102018-11-02 16:09:09 +01001827 if (policyMix != nullptr) {
1828 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
1829 // there is an external policy, but this input is attached to a mix of recorders,
1830 // meaning it receives audio injected into the framework, so the recorder doesn't
1831 // know about it and is therefore considered "legacy"
1832 *inputType = API_INPUT_LEGACY;
1833 } else if (audio_is_remote_submix_device(device->type())) {
1834 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX, String8("0"));
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001835 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01001836 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07001837 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001838 } else {
1839 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001840 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001841
Eric Laurent599c7582015-12-07 18:05:55 -08001842 }
1843
Francois Gaffie716e1432019-01-14 16:58:59 +01001844 *input = getInputForDevice(device, session, attributes.source,
Eric Laurentfe231122017-11-17 17:48:06 -08001845 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001846 policyMix);
1847 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001848 status = INVALID_OPERATION;
1849 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001850 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001851
Eric Laurent8f42ea12018-08-08 09:08:25 -07001852exit:
1853
François Gaffie11d30102018-11-02 16:09:09 +01001854 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
1855 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001856
Francois Gaffie716e1432019-01-14 16:58:59 +01001857 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07001858 mSoundTriggerSessions.indexOfKey(session) > 0;
1859 *portId = AudioPort::getNextUniqueId();
1860
François Gaffie11d30102018-11-02 16:09:09 +01001861 clientDesc = new RecordClientDescriptor(*portId, uid, session, *attr, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01001862 requestedDeviceId, attributes.source, flags,
1863 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001864 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001865 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001866
1867 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1868 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001869
Eric Laurent599c7582015-12-07 18:05:55 -08001870 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001871
1872error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001873 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001874}
1875
1876
François Gaffie11d30102018-11-02 16:09:09 +01001877audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08001878 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001879 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001880 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001881 audio_input_flags_t flags,
1882 AudioMix *policyMix)
1883{
1884 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1885 audio_source_t halInputSource = inputSource;
1886 bool isSoundTrigger = false;
1887
1888 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1889 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1890 if (index >= 0) {
1891 input = mSoundTriggerSessions.valueFor(session);
1892 isSoundTrigger = true;
1893 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1894 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1895 } else {
1896 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001897 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001898 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001899 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001900 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001901 }
1902
Andy Hungf129b032015-04-07 13:45:50 -07001903 // find a compatible input profile (not necessarily identical in parameters)
1904 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001905 // sampling rate and flags may be updated by getInputProfile
1906 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1907 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001908 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001909 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001910 audio_input_flags_t profileFlags = flags;
1911 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001912 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01001913 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07001914 profileFlags);
1915 if (profile != 0) {
1916 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001917 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1918 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001919 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1920 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1921 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01001922 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
1923 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
1924 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001925 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001926 }
Eric Laurente552edb2014-03-10 17:42:56 -07001927 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001928 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001929 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001930 if (samplingRate == 0) {
1931 samplingRate = profileSamplingRate;
1932 }
Eric Laurente552edb2014-03-10 17:42:56 -07001933
Eric Laurent322b4d22015-04-03 15:57:54 -07001934 if (profile->getModuleHandle() == 0) {
1935 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001936 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001937 }
1938
Eric Laurent3974e3b2017-12-07 17:58:43 -08001939 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001940 for (size_t i = 0; i < mInputs.size(); ) {
1941 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
1942 if (desc->mProfile != profile) {
1943 continue;
1944 }
1945 // if sound trigger, reuse input if used by other sound trigger on same session
1946 // else
1947 // reuse input if active client app is not in IDLE state
1948 //
1949 RecordClientVector clients = desc->clientsList();
1950 bool doClose = false;
1951 for (const auto& client : clients) {
1952 if (isSoundTrigger != client->isSoundTrigger()) {
1953 continue;
1954 }
1955 if (client->isSoundTrigger()) {
1956 if (session == client->session()) {
1957 return desc->mIoHandle;
1958 }
1959 continue;
1960 }
1961 if (client->active() && client->appState() != APP_STATE_IDLE) {
1962 return desc->mIoHandle;
1963 }
1964 doClose = true;
1965 }
1966 if (doClose) {
1967 closeInput(desc->mIoHandle);
1968 } else {
1969 i++;
1970 }
1971 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001972 }
1973
Eric Laurentfe231122017-11-17 17:48:06 -08001974 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001975
Eric Laurentfe231122017-11-17 17:48:06 -08001976 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1977 lConfig.sample_rate = profileSamplingRate;
1978 lConfig.channel_mask = profileChannelMask;
1979 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001980
François Gaffie11d30102018-11-02 16:09:09 +01001981 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001982
1983 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001984 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001985 (profileSamplingRate != lConfig.sample_rate) ||
1986 !audio_formats_match(profileFormat, lConfig.format) ||
1987 (profileChannelMask != lConfig.channel_mask)) {
1988 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001989 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001990 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001991 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001992 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001993 }
Eric Laurent599c7582015-12-07 18:05:55 -08001994 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001995 }
1996
Eric Laurentc722f302014-12-10 11:21:49 -08001997 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001998
Eric Laurent599c7582015-12-07 18:05:55 -08001999 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002000 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002001
Eric Laurent599c7582015-12-07 18:05:55 -08002002 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002003}
2004
Eric Laurent4eb58f12018-12-07 16:41:02 -08002005status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002006{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002007 ALOGV("%s portId %d", __FUNCTION__, portId);
2008
2009 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2010 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002011 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002012 return BAD_VALUE;
2013 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002014 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002015 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002016 if (client->active()) {
2017 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2018 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002019 }
2020
Eric Laurent8f42ea12018-08-08 09:08:25 -07002021 audio_session_t session = client->session();
2022
Eric Laurent4eb58f12018-12-07 16:41:02 -08002023 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002024
Eric Laurent4eb58f12018-12-07 16:41:02 -08002025 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002026
Eric Laurent4eb58f12018-12-07 16:41:02 -08002027 status_t status = inputDesc->start();
2028 if (status != NO_ERROR) {
2029 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002030 }
Eric Laurente552edb2014-03-10 17:42:56 -07002031
Eric Laurent4eb58f12018-12-07 16:41:02 -08002032 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002033 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002034 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002035
Eric Laurent8f42ea12018-08-08 09:08:25 -07002036 // indicate active capture to sound trigger service if starting capture from a mic on
2037 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002038 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002039 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002040
Eric Laurent8f42ea12018-08-08 09:08:25 -07002041 if (inputDesc->activeCount() == 1) {
2042 // if input maps to a dynamic policy with an activity listener, notify of state change
2043 if ((inputDesc->mPolicyMix != NULL)
2044 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2045 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2046 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002047 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002048
François Gaffie11d30102018-11-02 16:09:09 +01002049 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2050 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002051 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2052 SoundTrigger::setCaptureState(true);
2053 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002054
Eric Laurent8f42ea12018-08-08 09:08:25 -07002055 // automatically enable the remote submix output when input is started if not
2056 // used by a policy mix of type MIX_TYPE_RECORDERS
2057 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002058 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002059 String8 address = String8("");
2060 if (inputDesc->mPolicyMix == NULL) {
2061 address = String8("0");
2062 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2063 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002064 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002065 if (address != "") {
2066 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2067 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2068 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002069 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002070 }
Eric Laurente552edb2014-03-10 17:42:56 -07002071 }
2072
Eric Laurent8f42ea12018-08-08 09:08:25 -07002073 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002074
Eric Laurente552edb2014-03-10 17:42:56 -07002075 return NO_ERROR;
2076}
2077
Eric Laurent8fc147b2018-07-22 19:13:55 -07002078status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002079{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002080 ALOGV("%s portId %d", __FUNCTION__, portId);
2081
2082 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2083 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002084 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002085 return BAD_VALUE;
2086 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002087 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002088 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002089 if (!client->active()) {
2090 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002091 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002092 }
2093
Eric Laurent8f42ea12018-08-08 09:08:25 -07002094 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002095
Eric Laurent8f42ea12018-08-08 09:08:25 -07002096 inputDesc->stop();
2097 if (inputDesc->isActive()) {
2098 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2099 } else {
2100 // if input maps to a dynamic policy with an activity listener, notify of state change
2101 if ((inputDesc->mPolicyMix != NULL)
2102 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2103 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2104 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002105 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002106
2107 // automatically disable the remote submix output when input is stopped if not
2108 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002109 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002110 String8 address = String8("");
2111 if (inputDesc->mPolicyMix == NULL) {
2112 address = String8("0");
2113 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2114 address = inputDesc->mPolicyMix->mDeviceAddress;
2115 }
2116 if (address != "") {
2117 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2118 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2119 address, "remote-submix");
2120 }
2121 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002122 resetInputDevice(input);
2123
2124 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2125 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002126 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2127 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002128 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2129 SoundTrigger::setCaptureState(false);
2130 }
2131 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002132 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002133 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002134}
2135
Eric Laurent8fc147b2018-07-22 19:13:55 -07002136void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002137{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002138 ALOGV("%s portId %d", __FUNCTION__, portId);
2139
2140 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2141 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002142 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002143 return;
2144 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002145 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002146 audio_io_handle_t input = inputDesc->mIoHandle;
2147
Eric Laurent8f42ea12018-08-08 09:08:25 -07002148 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002149
Andy Hung39efb7a2018-09-26 15:39:28 -07002150 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002151
Andy Hung39efb7a2018-09-26 15:39:28 -07002152 if (inputDesc->getClientCount() > 0) {
2153 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002154 return;
2155 }
2156
Eric Laurent05b90f82014-08-27 15:32:29 -07002157 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002158 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002159 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002160}
2161
Eric Laurent8f42ea12018-08-08 09:08:25 -07002162void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002163{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002164 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002165
2166 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002167 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002168 }
2169}
2170
Eric Laurent8f42ea12018-08-08 09:08:25 -07002171void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2172{
2173 stopInput(portId);
2174 releaseInput(portId);
2175}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002176
Eric Laurentd4692962014-05-05 18:13:44 -07002177void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002178 bool patchRemoved = false;
2179
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002180 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002181 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002182 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002183 if (patch_index >= 0) {
2184 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002185 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002186 mAudioPatches.removeItemsAt(patch_index);
2187 patchRemoved = true;
2188 }
Eric Laurentfe231122017-11-17 17:48:06 -08002189 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002190 }
2191 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002192 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002193 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002194
2195 if (patchRemoved) {
2196 mpClientInterface->onAudioPatchListUpdate();
2197 }
Eric Laurentd4692962014-05-05 18:13:44 -07002198}
2199
Eric Laurente0720872014-03-11 09:30:41 -07002200void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002201 int indexMin,
2202 int indexMax)
2203{
2204 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002205 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002206
2207 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002208 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2209 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002210 continue;
2211 }
2212 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002213 }
Eric Laurente552edb2014-03-10 17:42:56 -07002214}
2215
Eric Laurente0720872014-03-11 09:30:41 -07002216status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002217 int index,
2218 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002219{
2220
Nadav Bar7c605f62017-12-25 00:01:52 +02002221 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2222 // app that has MODIFY_PHONE_STATE permission.
2223 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2224 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002225 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002226 return BAD_VALUE;
2227 }
2228 if (!audio_is_output_device(device)) {
2229 return BAD_VALUE;
2230 }
2231
2232 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002233 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002234
Eric Laurent1fd372e2016-04-06 14:23:53 -07002235 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002236 stream, device, index);
2237
Eric Laurent28d09f02016-03-08 10:43:05 -08002238 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002239 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2240 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002241 continue;
2242 }
2243 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2244 }
Eric Laurente552edb2014-03-10 17:42:56 -07002245
Eric Laurent1fd372e2016-04-06 14:23:53 -07002246 // update volume on all outputs and streams matching the following:
2247 // - The requested stream (or a stream matching for volume control) is active on the output
2248 // - The device (or devices) selected by the strategy corresponding to this stream includes
2249 // the requested device
2250 // - For non default requested device, currently selected device on the output is either the
2251 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002252 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2253 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002254 status_t status = NO_ERROR;
2255 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002256 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01002257 audio_devices_t curDevice = desc->devices().types();
Eric Laurent794fde22016-03-11 09:50:45 -08002258 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002259 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002260 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002261 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002262 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002263 continue;
2264 }
Eric Laurent794fde22016-03-11 09:50:45 -08002265 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002266 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2267 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002268 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2269 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002270 continue;
2271 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002272 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002273 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002274 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002275 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002276 } else {
2277 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002278 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002279 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002280 // rescale index before applying to curStream as ranges may be different for
2281 // stream and curStream
2282 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002283 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002284 //FIXME: workaround for truncated touch sounds
2285 // delayed volume change for system stream to be removed when the problem is
2286 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002287 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002288 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002289 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002290 if (volStatus != NO_ERROR) {
2291 status = volStatus;
2292 }
2293 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002294 }
Eric Laurente552edb2014-03-10 17:42:56 -07002295 }
2296 return status;
2297}
2298
Eric Laurente0720872014-03-11 09:30:41 -07002299status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002300 int *index,
2301 audio_devices_t device)
2302{
2303 if (index == NULL) {
2304 return BAD_VALUE;
2305 }
2306 if (!audio_is_output_device(device)) {
2307 return BAD_VALUE;
2308 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002309 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002310 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002311 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002312 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2313 }
François Gaffiedfd74092015-03-19 12:10:59 +01002314 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002315
François Gaffied1ab2bd2015-12-02 18:20:06 +01002316 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002317 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2318 return NO_ERROR;
2319}
2320
Eric Laurent36829f92017-04-07 19:04:42 -07002321audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002322{
2323 // select one output among several suitable for global effects.
2324 // The priority is as follows:
2325 // 1: An offloaded output. If the effect ends up not being offloadable,
2326 // AudioFlinger will invalidate the track and the offloaded output
2327 // will be closed causing the effect to be moved to a PCM output.
2328 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002329 // 3: The primary output
2330 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002331
Eric Laurent3b73df72014-03-11 09:06:29 -07002332 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
François Gaffie11d30102018-11-02 16:09:09 +01002333 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
2334 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002335
Eric Laurent36829f92017-04-07 19:04:42 -07002336 if (outputs.size() == 0) {
2337 return AUDIO_IO_HANDLE_NONE;
2338 }
Eric Laurente552edb2014-03-10 17:42:56 -07002339
Eric Laurent36829f92017-04-07 19:04:42 -07002340 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2341 bool activeOnly = true;
2342
2343 while (output == AUDIO_IO_HANDLE_NONE) {
2344 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2345 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2346 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2347
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002348 for (audio_io_handle_t output : outputs) {
2349 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002350 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2351 continue;
2352 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002353 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2354 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002355 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002356 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002357 }
2358 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002359 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002360 }
2361 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002362 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002363 }
2364 }
2365 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2366 output = outputOffloaded;
2367 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2368 output = outputDeepBuffer;
2369 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2370 output = outputPrimary;
2371 } else {
2372 output = outputs[0];
2373 }
2374 activeOnly = false;
2375 }
2376
2377 if (output != mMusicEffectOutput) {
2378 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2379 mMusicEffectOutput = output;
2380 }
2381
2382 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002383 return output;
2384}
2385
Eric Laurent36829f92017-04-07 19:04:42 -07002386audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2387{
2388 return selectOutputForMusicEffects();
2389}
2390
Eric Laurente0720872014-03-11 09:30:41 -07002391status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002392 audio_io_handle_t io,
2393 uint32_t strategy,
2394 int session,
2395 int id)
2396{
2397 ssize_t index = mOutputs.indexOfKey(io);
2398 if (index < 0) {
2399 index = mInputs.indexOfKey(io);
2400 if (index < 0) {
2401 ALOGW("registerEffect() unknown io %d", io);
2402 return INVALID_OPERATION;
2403 }
2404 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002405 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002406}
2407
Eric Laurentc241b0d2018-11-28 09:08:49 -08002408status_t AudioPolicyManager::unregisterEffect(int id)
2409{
2410 if (mEffects.getEffect(id) == nullptr) {
2411 return INVALID_OPERATION;
2412 }
2413
2414 if (mEffects.isEffectEnabled(id)) {
2415 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2416 setEffectEnabled(id, false);
2417 }
2418 return mEffects.unregisterEffect(id);
2419}
2420
2421status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2422{
2423 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2424 if (effect == nullptr) {
2425 return INVALID_OPERATION;
2426 }
2427
2428 status_t status = mEffects.setEffectEnabled(id, enabled);
2429 if (status == NO_ERROR) {
2430 mInputs.trackEffectEnabled(effect, enabled);
2431 }
2432 return status;
2433}
2434
Eric Laurentc75307b2015-03-17 15:29:32 -07002435bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2436{
Eric Laurent28d09f02016-03-08 10:43:05 -08002437 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002438 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2439 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002440 continue;
2441 }
2442 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2443 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002444 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002445}
2446
2447bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2448{
2449 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2450}
2451
Eric Laurente0720872014-03-11 09:30:41 -07002452bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002453{
2454 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002455 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002456 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002457 return true;
2458 }
2459 }
2460 return false;
2461}
2462
Eric Laurent275e8e92014-11-30 15:14:47 -08002463// Register a list of custom mixes with their attributes and format.
2464// When a mix is registered, corresponding input and output profiles are
2465// added to the remote submix hw module. The profile contains only the
2466// parameters (sampling rate, format...) specified by the mix.
2467// The corresponding input remote submix device is also connected.
2468//
2469// When a remote submix device is connected, the address is checked to select the
2470// appropriate profile and the corresponding input or output stream is opened.
2471//
2472// When capture starts, getInputForAttr() will:
2473// - 1 look for a mix matching the address passed in attribtutes tags if any
2474// - 2 if none found, getDeviceForInputSource() will:
2475// - 2.1 look for a mix matching the attributes source
2476// - 2.2 if none found, default to device selection by policy rules
2477// At this time, the corresponding output remote submix device is also connected
2478// and active playback use cases can be transferred to this mix if needed when reconnecting
2479// after AudioTracks are invalidated
2480//
2481// When playback starts, getOutputForAttr() will:
2482// - 1 look for a mix matching the address passed in attribtutes tags if any
2483// - 2 if none found, look for a mix matching the attributes usage
2484// - 3 if none found, default to device and output selection by policy rules.
2485
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002486status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002487{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002488 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2489 status_t res = NO_ERROR;
2490
2491 sp<HwModule> rSubmixModule;
2492 // examine each mix's route type
2493 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002494 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002495 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002496 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002497 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002498 break;
2499 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002500 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002501 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002502 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002503 rSubmixModule = mHwModules.getModuleFromName(
2504 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2505 if (rSubmixModule == 0) {
2506 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2507 i);
2508 res = INVALID_OPERATION;
2509 break;
2510 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002511 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002512
Eric Laurent97ac8712018-07-27 18:59:02 -07002513 String8 address = mix.mDeviceAddress;
2514 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2515 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2516 } else {
2517 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2518 }
François Gaffie036e1e92015-03-19 10:16:24 +01002519
Eric Laurent97ac8712018-07-27 18:59:02 -07002520 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002521 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 res = INVALID_OPERATION;
2523 break;
2524 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002525 audio_config_t outputConfig = mix.mFormat;
2526 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002527 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2528 // stereo and let audio flinger do the channel conversion if needed.
2529 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2530 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2531 rSubmixModule->addOutputProfile(address, &outputConfig,
2532 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2533 rSubmixModule->addInputProfile(address, &inputConfig,
2534 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002535
Eric Laurent97ac8712018-07-27 18:59:02 -07002536 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002537 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2538 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2539 address.string(), "remote-submix");
2540 } else {
2541 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2542 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2543 address.string(), "remote-submix");
2544 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002545 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2546 String8 address = mix.mDeviceAddress;
2547 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002548 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2549 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002550
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002551 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002552 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2553 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2554 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2555 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2556 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2557 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002558 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2559 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002560 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002561 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002562 } else {
2563 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002564 }
2565 break;
2566 }
2567 }
2568
2569 if (res != NO_ERROR) {
2570 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002571 i, device, address.string());
2572 res = INVALID_OPERATION;
2573 break;
2574 } else if (!foundOutput) {
2575 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2576 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002577 res = INVALID_OPERATION;
2578 break;
2579 }
Eric Laurentc722f302014-12-10 11:21:49 -08002580 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002581 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002582 if (res != NO_ERROR) {
2583 unregisterPolicyMixes(mixes);
2584 }
2585 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002586}
2587
2588status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2589{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002590 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002591 status_t res = NO_ERROR;
2592 sp<HwModule> rSubmixModule;
2593 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002594 for (const auto& mix : mixes) {
2595 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002596
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002597 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002598 rSubmixModule = mHwModules.getModuleFromName(
2599 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2600 if (rSubmixModule == 0) {
2601 res = INVALID_OPERATION;
2602 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002603 }
2604 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002605
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002606 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002607
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002608 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2609 res = INVALID_OPERATION;
2610 continue;
2611 }
2612
2613 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2614 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2615 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2616 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2617 address.string(), "remote-submix");
2618 }
2619 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2620 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2621 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2622 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2623 address.string(), "remote-submix");
2624 }
2625 rSubmixModule->removeOutputProfile(address);
2626 rSubmixModule->removeInputProfile(address);
2627
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002628 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2629 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002630 res = INVALID_OPERATION;
2631 continue;
2632 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002633 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002634 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002635 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002636}
2637
Mikhail Naganov100f0122018-11-29 11:22:16 -08002638void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2639{
2640 size_t i = 0;
2641 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2642 for (const auto& fmt : mManualSurroundFormats) {
2643 if (i++ != 0) dst->append(", ");
2644 std::string sfmt;
2645 FormatConverter::toString(fmt, sfmt);
2646 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2647 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2648 }
2649}
2650
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002651status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2652 const Vector<AudioDeviceTypeAddr>& devices) {
2653 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2654 // uid/device affinity is only for output devices
2655 for (size_t i = 0; i < devices.size(); i++) {
2656 if (!audio_is_output_device(devices[i].mType)) {
2657 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2658 devices[i].mType);
2659 return BAD_VALUE;
2660 }
2661 }
2662 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2663 if (res == NO_ERROR) {
2664 // reevaluate outputs for all given devices
2665 for (size_t i = 0; i < devices.size(); i++) {
2666 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
2667 devices[i].mType, devices[i].mAddress, String8());
2668 SortedVector<audio_io_handle_t> outputs;
2669 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002670 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002671 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2672 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2673 return INVALID_OPERATION;
2674 }
2675 }
2676 }
2677 return res;
2678}
2679
2680status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2681 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2682 Vector<AudioDeviceTypeAddr> devices;
2683 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2684 if (res == NO_ERROR) {
2685 // reevaluate outputs for all found devices
2686 for (size_t i = 0; i < devices.size(); i++) {
2687 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
2688 devices[i].mType, devices[i].mAddress, String8());
2689 SortedVector<audio_io_handle_t> outputs;
2690 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002691 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002692 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2693 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2694 return INVALID_OPERATION;
2695 }
2696 }
2697 }
2698
2699 return res;
2700}
2701
Andy Hungc29d82b2018-10-05 12:23:17 -07002702void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002703{
Andy Hungc29d82b2018-10-05 12:23:17 -07002704 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2705 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002706 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002707 std::string stateLiteral;
2708 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002709 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002710 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2711 "communications", "media", "record", "dock", "system",
2712 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2713 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2714 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002715 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2716 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2717 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2718 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2719 dst->append(" (MANUAL: ");
2720 dumpManualSurroundFormats(dst);
2721 dst->append(")");
2722 }
2723 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002724 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002725 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2726 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2727 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2728 mAvailableOutputDevices.dump(dst, String8("Available output"));
2729 mAvailableInputDevices.dump(dst, String8("Available input"));
2730 mHwModulesAll.dump(dst);
2731 mOutputs.dump(dst);
2732 mInputs.dump(dst);
2733 mVolumeCurves->dump(dst);
2734 mEffects.dump(dst);
2735 mAudioPatches.dump(dst);
2736 mPolicyMixes.dump(dst);
2737 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002738}
2739
2740status_t AudioPolicyManager::dump(int fd)
2741{
2742 String8 result;
2743 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002744 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002745 return NO_ERROR;
2746}
2747
2748// This function checks for the parameters which can be offloaded.
2749// This can be enhanced depending on the capability of the DSP and policy
2750// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002751bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002752{
2753 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002754 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002755 offloadInfo.sample_rate, offloadInfo.channel_mask,
2756 offloadInfo.format,
2757 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2758 offloadInfo.has_video);
2759
Andy Hung2ddee192015-12-18 17:34:44 -08002760 if (mMasterMono) {
2761 return false; // no offloading if mono is set.
2762 }
2763
Eric Laurente552edb2014-03-10 17:42:56 -07002764 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002765 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2766 ALOGV("offload disabled by audio.offload.disable");
2767 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002768 }
2769
2770 // Check if stream type is music, then only allow offload as of now.
2771 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2772 {
2773 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2774 return false;
2775 }
2776
2777 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002778 const bool allowOffloadWithVideo =
2779 property_get_bool("audio.offload.video", false /* default_value */);
2780 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002781 ALOGV("isOffloadSupported: has_video == true, returning false");
2782 return false;
2783 }
2784
2785 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002786 const int min_duration_secs = property_get_int32(
2787 "audio.offload.min.duration.secs", -1 /* default_value */);
2788 if (min_duration_secs >= 0) {
2789 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2790 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2791 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002792 return false;
2793 }
2794 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2795 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2796 return false;
2797 }
2798
2799 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2800 // creating an offloaded track and tearing it down immediately after start when audioflinger
2801 // detects there is an active non offloadable effect.
2802 // FIXME: We should check the audio session here but we do not have it in this context.
2803 // This may prevent offloading in rare situations where effects are left active by apps
2804 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002805 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002806 return false;
2807 }
2808
2809 // See if there is a profile to support this.
2810 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01002811 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002812 offloadInfo.sample_rate,
2813 offloadInfo.format,
2814 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002815 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2816 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002817 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2818 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002819}
2820
Michael Chana94fbb22018-04-24 14:31:19 +10002821bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2822 const audio_attributes_t& attributes) {
2823 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2824 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01002825 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10002826 config.sample_rate,
2827 config.format,
2828 config.channel_mask,
2829 output_flags,
2830 true /* directOnly */);
2831 ALOGV("%s() profile %sfound with name: %s, "
2832 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2833 __FUNCTION__, profile != 0 ? "" : "NOT ",
2834 (profile != 0 ? profile->getTagName().string() : "null"),
2835 config.sample_rate, config.format, config.channel_mask, output_flags);
2836 return (profile != 0);
2837}
2838
Eric Laurent6a94d692014-05-20 11:18:06 -07002839status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2840 audio_port_type_t type,
2841 unsigned int *num_ports,
2842 struct audio_port *ports,
2843 unsigned int *generation)
2844{
2845 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2846 generation == NULL) {
2847 return BAD_VALUE;
2848 }
2849 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2850 if (ports == NULL) {
2851 *num_ports = 0;
2852 }
2853
2854 size_t portsWritten = 0;
2855 size_t portsMax = *num_ports;
2856 *num_ports = 0;
2857 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002858 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2859 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002860 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002861 for (const auto& dev : mAvailableOutputDevices) {
2862 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002863 continue;
2864 }
2865 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002866 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002867 }
2868 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002869 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002870 }
2871 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002872 for (const auto& dev : mAvailableInputDevices) {
2873 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002874 continue;
2875 }
2876 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002877 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002878 }
2879 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002880 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002881 }
2882 }
2883 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2884 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2885 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2886 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2887 }
2888 *num_ports += mInputs.size();
2889 }
2890 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002891 size_t numOutputs = 0;
2892 for (size_t i = 0; i < mOutputs.size(); i++) {
2893 if (!mOutputs[i]->isDuplicated()) {
2894 numOutputs++;
2895 if (portsWritten < portsMax) {
2896 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2897 }
2898 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002899 }
Eric Laurent84c70242014-06-23 08:46:27 -07002900 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002901 }
2902 }
2903 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002904 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002905 return NO_ERROR;
2906}
2907
Eric Laurent99fcae42018-05-17 16:59:18 -07002908status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002909{
Eric Laurent99fcae42018-05-17 16:59:18 -07002910 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2911 return BAD_VALUE;
2912 }
2913 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2914 if (dev != 0) {
2915 dev->toAudioPort(port);
2916 return NO_ERROR;
2917 }
2918 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2919 if (dev != 0) {
2920 dev->toAudioPort(port);
2921 return NO_ERROR;
2922 }
2923 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2924 if (out != 0) {
2925 out->toAudioPort(port);
2926 return NO_ERROR;
2927 }
2928 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2929 if (in != 0) {
2930 in->toAudioPort(port);
2931 return NO_ERROR;
2932 }
2933 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002934}
2935
Eric Laurent6a94d692014-05-20 11:18:06 -07002936status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2937 audio_patch_handle_t *handle,
2938 uid_t uid)
2939{
2940 ALOGV("createAudioPatch()");
2941
2942 if (handle == NULL || patch == NULL) {
2943 return BAD_VALUE;
2944 }
2945 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2946
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002947 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002948 return BAD_VALUE;
2949 }
2950 // only one source per audio patch supported for now
2951 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002952 return INVALID_OPERATION;
2953 }
Eric Laurent874c42872014-08-08 15:13:39 -07002954
2955 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002956 return INVALID_OPERATION;
2957 }
Eric Laurent874c42872014-08-08 15:13:39 -07002958 for (size_t i = 0; i < patch->num_sinks; i++) {
2959 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2960 return INVALID_OPERATION;
2961 }
2962 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002963
2964 sp<AudioPatch> patchDesc;
2965 ssize_t index = mAudioPatches.indexOfKey(*handle);
2966
Eric Laurent6a94d692014-05-20 11:18:06 -07002967 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2968 patch->sources[0].role,
2969 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002970#if LOG_NDEBUG == 0
2971 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002972 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002973 patch->sinks[i].role,
2974 patch->sinks[i].type);
2975 }
2976#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002977
2978 if (index >= 0) {
2979 patchDesc = mAudioPatches.valueAt(index);
2980 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2981 mUidCached, patchDesc->mUid, uid);
2982 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2983 return INVALID_OPERATION;
2984 }
2985 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002986 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002987 }
2988
2989 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002990 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002991 if (outputDesc == NULL) {
2992 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2993 return BAD_VALUE;
2994 }
Eric Laurent84c70242014-06-23 08:46:27 -07002995 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2996 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002997 if (patchDesc != 0) {
2998 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2999 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3000 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3001 return BAD_VALUE;
3002 }
3003 }
Eric Laurent874c42872014-08-08 15:13:39 -07003004 DeviceVector devices;
3005 for (size_t i = 0; i < patch->num_sinks; i++) {
3006 // Only support mix to devices connection
3007 // TODO add support for mix to mix connection
3008 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3009 ALOGV("createAudioPatch() source mix but sink is not a device");
3010 return INVALID_OPERATION;
3011 }
3012 sp<DeviceDescriptor> devDesc =
3013 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3014 if (devDesc == 0) {
3015 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3016 return BAD_VALUE;
3017 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003018
François Gaffie11d30102018-11-02 16:09:09 +01003019 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003020 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003021 NULL, // updatedSamplingRate
3022 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003023 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003024 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003025 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003026 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003027 ALOGV("createAudioPatch() profile not supported for device %08x",
3028 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003029 return INVALID_OPERATION;
3030 }
3031 devices.add(devDesc);
3032 }
3033 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003034 return INVALID_OPERATION;
3035 }
Eric Laurent874c42872014-08-08 15:13:39 -07003036
Eric Laurent6a94d692014-05-20 11:18:06 -07003037 // TODO: reconfigure output format and channels here
3038 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003039 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003040 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003041 index = mAudioPatches.indexOfKey(*handle);
3042 if (index >= 0) {
3043 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3044 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3045 }
3046 patchDesc = mAudioPatches.valueAt(index);
3047 patchDesc->mUid = uid;
3048 ALOGV("createAudioPatch() success");
3049 } else {
3050 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3051 return INVALID_OPERATION;
3052 }
3053 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3054 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3055 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003056 // only one sink supported when connecting an input device to a mix
3057 if (patch->num_sinks > 1) {
3058 return INVALID_OPERATION;
3059 }
François Gaffie53615e22015-03-19 09:24:12 +01003060 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003061 if (inputDesc == NULL) {
3062 return BAD_VALUE;
3063 }
3064 if (patchDesc != 0) {
3065 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3066 return BAD_VALUE;
3067 }
3068 }
François Gaffie11d30102018-11-02 16:09:09 +01003069 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003070 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003071 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003072 return BAD_VALUE;
3073 }
3074
François Gaffie11d30102018-11-02 16:09:09 +01003075 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003076 patch->sinks[0].sample_rate,
3077 NULL, /*updatedSampleRate*/
3078 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003079 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003080 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003081 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003082 // FIXME for the parameter type,
3083 // and the NONE
3084 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003085 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003086 return INVALID_OPERATION;
3087 }
3088 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003089 ALOGV("%s() setting device %s on output %d", __func__,
3090 device->toString().c_str(), inputDesc->mIoHandle);
3091 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003092 index = mAudioPatches.indexOfKey(*handle);
3093 if (index >= 0) {
3094 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3095 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3096 }
3097 patchDesc = mAudioPatches.valueAt(index);
3098 patchDesc->mUid = uid;
3099 ALOGV("createAudioPatch() success");
3100 } else {
3101 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3102 return INVALID_OPERATION;
3103 }
3104 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3105 // device to device connection
3106 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003107 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003108 return BAD_VALUE;
3109 }
3110 }
François Gaffie11d30102018-11-02 16:09:09 +01003111 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003112 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003113 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003114 return BAD_VALUE;
3115 }
Eric Laurent874c42872014-08-08 15:13:39 -07003116
Eric Laurent6a94d692014-05-20 11:18:06 -07003117 //update source and sink with our own data as the data passed in the patch may
3118 // be incomplete.
3119 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003120 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003121
Eric Laurent874c42872014-08-08 15:13:39 -07003122 for (size_t i = 0; i < patch->num_sinks; i++) {
3123 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3124 ALOGV("createAudioPatch() source device but one sink is not a device");
3125 return INVALID_OPERATION;
3126 }
3127
François Gaffie11d30102018-11-02 16:09:09 +01003128 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003129 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003130 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003131 return BAD_VALUE;
3132 }
François Gaffie11d30102018-11-02 16:09:09 +01003133 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003134
Eric Laurent3bcf8592015-04-03 12:13:24 -07003135 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003136 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003137 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003138 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003139 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3140 (srcDevice->getModuleVersionMajor() < 3) ||
3141 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003142 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003143 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003144 return INVALID_OPERATION;
3145 }
Eric Laurent874c42872014-08-08 15:13:39 -07003146 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003147 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003148 // if the sink device is reachable via an opened output stream, request to go via
3149 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003150 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003151 if (output != AUDIO_IO_HANDLE_NONE) {
3152 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3153 if (outputDesc->isDuplicated()) {
3154 return INVALID_OPERATION;
3155 }
3156 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003157 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003158 newPatch.num_sources = 2;
3159 }
Eric Laurent83b88082014-06-20 18:31:16 -07003160 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003161 }
3162 // TODO: check from routing capabilities in config file and other conflicting patches
3163
Mikhail Naganovdc769682018-05-04 15:34:08 -07003164 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3165 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003166 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3167 status);
3168 return INVALID_OPERATION;
3169 }
3170 } else {
3171 return BAD_VALUE;
3172 }
3173 } else {
3174 return BAD_VALUE;
3175 }
3176 return NO_ERROR;
3177}
3178
3179status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3180 uid_t uid)
3181{
3182 ALOGV("releaseAudioPatch() patch %d", handle);
3183
3184 ssize_t index = mAudioPatches.indexOfKey(handle);
3185
3186 if (index < 0) {
3187 return BAD_VALUE;
3188 }
3189 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3190 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3191 mUidCached, patchDesc->mUid, uid);
3192 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3193 return INVALID_OPERATION;
3194 }
3195
3196 struct audio_patch *patch = &patchDesc->mPatch;
3197 patchDesc->mUid = mUidCached;
3198 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003199 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003200 if (outputDesc == NULL) {
3201 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3202 return BAD_VALUE;
3203 }
3204
François Gaffie11d30102018-11-02 16:09:09 +01003205 setOutputDevices(outputDesc,
3206 getNewOutputDevices(outputDesc, true /*fromCache*/),
3207 true,
3208 0,
3209 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003210 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3211 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003212 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003213 if (inputDesc == NULL) {
3214 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3215 return BAD_VALUE;
3216 }
3217 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003218 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003219 true,
3220 NULL);
3221 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003222 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3223 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3224 status, patchDesc->mAfPatchHandle);
3225 removeAudioPatch(patchDesc->mHandle);
3226 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003227 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003228 } else {
3229 return BAD_VALUE;
3230 }
3231 } else {
3232 return BAD_VALUE;
3233 }
3234 return NO_ERROR;
3235}
3236
3237status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3238 struct audio_patch *patches,
3239 unsigned int *generation)
3240{
François Gaffie53615e22015-03-19 09:24:12 +01003241 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003242 return BAD_VALUE;
3243 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003244 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003245 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003246}
3247
Eric Laurente1715a42014-05-20 11:30:42 -07003248status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003249{
Eric Laurente1715a42014-05-20 11:30:42 -07003250 ALOGV("setAudioPortConfig()");
3251
3252 if (config == NULL) {
3253 return BAD_VALUE;
3254 }
3255 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3256 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003257 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3258 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003259 }
3260
Eric Laurenta121f902014-06-03 13:32:54 -07003261 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003262 if (config->type == AUDIO_PORT_TYPE_MIX) {
3263 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003264 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003265 if (outputDesc == NULL) {
3266 return BAD_VALUE;
3267 }
Eric Laurent84c70242014-06-23 08:46:27 -07003268 ALOG_ASSERT(!outputDesc->isDuplicated(),
3269 "setAudioPortConfig() called on duplicated output %d",
3270 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003271 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003272 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003273 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003274 if (inputDesc == NULL) {
3275 return BAD_VALUE;
3276 }
Eric Laurenta121f902014-06-03 13:32:54 -07003277 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003278 } else {
3279 return BAD_VALUE;
3280 }
3281 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3282 sp<DeviceDescriptor> deviceDesc;
3283 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3284 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3285 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3286 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3287 } else {
3288 return BAD_VALUE;
3289 }
3290 if (deviceDesc == NULL) {
3291 return BAD_VALUE;
3292 }
Eric Laurenta121f902014-06-03 13:32:54 -07003293 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003294 } else {
3295 return BAD_VALUE;
3296 }
3297
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003298 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003299 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3300 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003301 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003302 audioPortConfig->toAudioPortConfig(&newConfig, config);
3303 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003304 }
Eric Laurenta121f902014-06-03 13:32:54 -07003305 if (status != NO_ERROR) {
3306 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003307 }
Eric Laurente1715a42014-05-20 11:30:42 -07003308
3309 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003310}
3311
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003312void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3313{
Eric Laurentd60560a2015-04-10 11:31:20 -07003314 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003315 clearAudioPatches(uid);
3316 clearSessionRoutes(uid);
3317}
3318
Eric Laurent6a94d692014-05-20 11:18:06 -07003319void AudioPolicyManager::clearAudioPatches(uid_t uid)
3320{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003321 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003322 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3323 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003324 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003325 }
3326 }
3327}
3328
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003329void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3330 audio_io_handle_t ouptutToSkip)
3331{
François Gaffie11d30102018-11-02 16:09:09 +01003332 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
3333 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003334 for (size_t j = 0; j < mOutputs.size(); j++) {
3335 if (mOutputs.keyAt(j) == ouptutToSkip) {
3336 continue;
3337 }
3338 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3339 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3340 continue;
3341 }
3342 // If the default device for this strategy is on another output mix,
3343 // invalidate all tracks in this strategy to force re connection.
3344 // Otherwise select new device on the output mix.
3345 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003346 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003347 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3348 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3349 }
3350 }
3351 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003352 setOutputDevices(
3353 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003354 }
3355 }
3356}
3357
3358void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3359{
3360 // remove output routes associated with this uid
3361 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003362 for (size_t i = 0; i < mOutputs.size(); i++) {
3363 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003364 for (const auto& client : outputDesc->getClientIterable()) {
3365 if (client->hasPreferredDevice() && client->uid() == uid) {
3366 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3367 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003368 }
3369 }
3370 }
3371 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003372 for (const auto& strategy : affectedStrategies) {
3373 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003374 }
3375
3376 // remove input routes associated with this uid
3377 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003378 for (size_t i = 0; i < mInputs.size(); i++) {
3379 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003380 for (const auto& client : inputDesc->getClientIterable()) {
3381 if (client->hasPreferredDevice() && client->uid() == uid) {
3382 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3383 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003384 }
3385 }
3386 }
3387 // reroute inputs if necessary
3388 SortedVector<audio_io_handle_t> inputsToClose;
3389 for (size_t i = 0; i < mInputs.size(); i++) {
3390 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003391 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003392 inputsToClose.add(inputDesc->mIoHandle);
3393 }
3394 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003395 for (const auto& input : inputsToClose) {
3396 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003397 }
3398}
3399
Eric Laurentd60560a2015-04-10 11:31:20 -07003400void AudioPolicyManager::clearAudioSources(uid_t uid)
3401{
3402 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003403 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3404 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003405 stopAudioSource(mAudioSources.keyAt(i));
3406 }
3407 }
3408}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003409
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003410status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3411 audio_io_handle_t *ioHandle,
3412 audio_devices_t *device)
3413{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003414 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3415 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003416 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
3417 *device = getDeviceAndMixForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003418
François Gaffiedf372692015-03-19 10:43:27 +01003419 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003420}
3421
Eric Laurentd60560a2015-04-10 11:31:20 -07003422status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003423 const audio_attributes_t *attributes,
3424 audio_port_handle_t *portId,
3425 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003426{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003427 ALOGV("%s", __FUNCTION__);
3428 *portId = AUDIO_PORT_HANDLE_NONE;
3429
3430 if (source == NULL || attributes == NULL || portId == NULL) {
3431 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3432 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003433 return BAD_VALUE;
3434 }
3435
Eric Laurentd60560a2015-04-10 11:31:20 -07003436 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3437 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003438 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3439 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003440 return INVALID_OPERATION;
3441 }
3442
François Gaffie11d30102018-11-02 16:09:09 +01003443 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003444 mAvailableInputDevices.getDevice(source->ext.device.type,
François Gaffie11d30102018-11-02 16:09:09 +01003445 String8(source->ext.device.address));
3446 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003447 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003448 return BAD_VALUE;
3449 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003450
3451 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003452
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003453 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003454 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003455
3456 sp<SourceClientDescriptor> sourceDesc =
François Gaffie11d30102018-11-02 16:09:09 +01003457 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
Eric Laurent97ac8712018-07-27 18:59:02 -07003458 streamTypefromAttributesInt(attributes),
3459 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003460
3461 status_t status = connectAudioSource(sourceDesc);
3462 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003463 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003464 }
3465 return status;
3466}
3467
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003468status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003469{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003470 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003471
3472 // make sure we only have one patch per source.
3473 disconnectAudioSource(sourceDesc);
3474
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003475 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003476 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003477 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003478 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003479
François Gaffie11d30102018-11-02 16:09:09 +01003480 DeviceVector sinkDevices = getDevicesForStrategy(strategy, true);
3481 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for strategy");
3482 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3483 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3484 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003485
3486 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003487
François Gaffie11d30102018-11-02 16:09:09 +01003488 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3489 srcDevice->getModuleVersionMajor() >= 3 &&
3490 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3491 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003492 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003493 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003494 // create patch between src device and output device
3495 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003496 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003497 audio_attributes_t resultAttr;
3498 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3499 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3500 config.sample_rate = sourceDesc->config().sample_rate;
3501 config.channel_mask = sourceDesc->config().channel_mask;
3502 config.format = sourceDesc->config().format;
3503 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3504 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3505 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3506 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003507 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003508 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003509 return INVALID_OPERATION;
3510 }
3511 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3512 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003513 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003514 return INVALID_OPERATION;
3515 }
Eric Laurent733ce942017-12-07 12:18:25 -08003516 status_t status = outputDesc->start();
3517 if (status != NO_ERROR) {
3518 return status;
3519 }
3520
Eric Laurentd60560a2015-04-10 11:31:20 -07003521 // create a special patch with no sink and two sources:
3522 // - the second source indicates to PatchPanel through which output mix this patch should
3523 // be connected as well as the stream type for volume control
3524 // - the sink is defined by whatever output device is currently selected for the output
3525 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003526 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003527 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003528 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003529 &afPatchHandle,
3530 0);
3531 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3532 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003533 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003534 if (status != NO_ERROR) {
3535 ALOGW("%s patch panel could not connect device patch, error %d",
3536 __FUNCTION__, status);
3537 return INVALID_OPERATION;
3538 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003539
3540 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3541 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3542 return INVALID_OPERATION;
3543 }
3544 outputDesc->addClient(sourceDesc);
3545
Eric Laurentd60560a2015-04-10 11:31:20 -07003546 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003547 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003548
3549 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003550 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003551 return status;
3552 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003553 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003554 if (delayMs != 0) {
3555 usleep(delayMs * 1000);
3556 }
3557 }
3558
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003559 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3560 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003561
3562 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003563}
3564
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003565status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003566{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003567 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3568 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003569 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003570 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003571 return BAD_VALUE;
3572 }
3573 status_t status = disconnectAudioSource(sourceDesc);
3574
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003575 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003576 return status;
3577}
3578
Andy Hung2ddee192015-12-18 17:34:44 -08003579status_t AudioPolicyManager::setMasterMono(bool mono)
3580{
3581 if (mMasterMono == mono) {
3582 return NO_ERROR;
3583 }
3584 mMasterMono = mono;
3585 // if enabling mono we close all offloaded devices, which will invalidate the
3586 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3587 // for recreating the new AudioTrack as non-offloaded PCM.
3588 //
3589 // If disabling mono, we leave all tracks as is: we don't know which clients
3590 // and tracks are able to be recreated as offloaded. The next "song" should
3591 // play back offloaded.
3592 if (mMasterMono) {
3593 Vector<audio_io_handle_t> offloaded;
3594 for (size_t i = 0; i < mOutputs.size(); ++i) {
3595 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3596 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3597 offloaded.push(desc->mIoHandle);
3598 }
3599 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003600 for (const auto& handle : offloaded) {
3601 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003602 }
3603 }
3604 // update master mono for all remaining outputs
3605 for (size_t i = 0; i < mOutputs.size(); ++i) {
3606 updateMono(mOutputs.keyAt(i));
3607 }
3608 return NO_ERROR;
3609}
3610
3611status_t AudioPolicyManager::getMasterMono(bool *mono)
3612{
3613 *mono = mMasterMono;
3614 return NO_ERROR;
3615}
3616
Eric Laurentac9cef52017-06-09 15:46:26 -07003617float AudioPolicyManager::getStreamVolumeDB(
3618 audio_stream_type_t stream, int index, audio_devices_t device)
3619{
3620 return computeVolume(stream, index, device);
3621}
3622
jiabin81772902018-04-02 17:52:27 -07003623status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3624 audio_format_t *surroundFormats,
3625 bool *surroundFormatsEnabled,
3626 bool reported)
3627{
3628 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3629 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3630 return BAD_VALUE;
3631 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003632 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3633 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003634
3635 size_t formatsWritten = 0;
3636 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003637 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003638 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003639 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003640 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003641 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3642 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3643 FormatVector supportedFormats =
3644 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3645 for (size_t j = 0; j < supportedFormats.size(); j++) {
3646 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3647 formats.insert(supportedFormats[j]);
3648 } else {
3649 for (const auto& pair : mConfig.getSurroundFormats()) {
3650 if (pair.second.count(supportedFormats[j]) != 0) {
3651 formats.insert(pair.first);
3652 break;
3653 }
3654 }
3655 }
3656 }
jiabin81772902018-04-02 17:52:27 -07003657 }
3658 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003659 for (const auto& pair : mConfig.getSurroundFormats()) {
3660 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003661 }
3662 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003663 *numSurroundFormats = formats.size();
3664 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3665 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003666 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003667 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003668 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003669 bool formatEnabled = true;
3670 switch (forceUse) {
3671 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3672 formatEnabled = mManualSurroundFormats.count(format) != 0;
3673 break;
3674 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3675 formatEnabled = false;
3676 break;
3677 default: // AUTO or ALWAYS => true
3678 break;
jiabin81772902018-04-02 17:52:27 -07003679 }
3680 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3681 }
jiabin81772902018-04-02 17:52:27 -07003682 }
3683 return NO_ERROR;
3684}
3685
3686status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3687{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003688 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003689 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3690 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003691 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003692 return BAD_VALUE;
3693 }
3694
Mikhail Naganov100f0122018-11-29 11:22:16 -08003695 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3696 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003697 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003698 return INVALID_OPERATION;
3699 }
3700
Mikhail Naganov100f0122018-11-29 11:22:16 -08003701 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003702 return NO_ERROR;
3703 }
3704
Mikhail Naganov100f0122018-11-29 11:22:16 -08003705 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003706 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003707 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003708 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003709 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003710 }
3711 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003712 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003713 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003714 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003715 }
3716 }
3717
3718 sp<SwAudioOutputDescriptor> outputDesc;
3719 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003720 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003721 AUDIO_DEVICE_OUT_HDMI);
3722 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3723 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003724 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003725 String8 name = hdmiOutputDevices[i]->getName();
3726 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3727 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3728 address.c_str(),
3729 name.c_str());
3730 if (status != NO_ERROR) {
3731 continue;
3732 }
3733 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3734 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3735 address.c_str(),
3736 name.c_str());
3737 profileUpdated |= (status == NO_ERROR);
3738 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003739 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003740 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003741 AUDIO_DEVICE_IN_HDMI);
3742 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3743 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003744 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003745 String8 name = hdmiInputDevices[i]->getName();
3746 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3747 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3748 address.c_str(),
3749 name.c_str());
3750 if (status != NO_ERROR) {
3751 continue;
3752 }
3753 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3754 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3755 address.c_str(),
3756 name.c_str());
3757 profileUpdated |= (status == NO_ERROR);
3758 }
3759
jiabin81772902018-04-02 17:52:27 -07003760 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003761 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003762 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003763 }
3764
3765 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3766}
3767
Eric Laurentf32108e2018-10-04 17:22:04 -07003768void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003769{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003770 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003771
Eric Laurenta9f86652018-11-28 17:23:11 -08003772 for (size_t i = 0; i < mInputs.size(); i++) {
3773 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3774 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003775 for (const auto& client : clients) {
3776 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003777 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003778 }
3779 }
3780 }
3781}
3782
jiabin6012f912018-11-02 17:06:30 -07003783bool AudioPolicyManager::isHapticPlaybackSupported()
3784{
3785 for (const auto& hwModule : mHwModules) {
3786 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3787 for (const auto &outProfile : outputProfiles) {
3788 struct audio_port audioPort;
3789 outProfile->toAudioPort(&audioPort);
3790 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3791 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3792 return true;
3793 }
3794 }
3795 }
3796 }
3797 return false;
3798}
3799
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003800status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003801{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003802 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003803
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003804 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003805 if (patchDesc == 0) {
3806 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003807 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003808 return BAD_VALUE;
3809 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003810 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003811
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003812 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003813 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003814 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003815 if (status == NO_ERROR) {
3816 swOutputDesc->stop();
3817 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003818 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3819 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003820 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003821 if (hwOutputDesc != 0) {
3822 // release patch between src device and output device
3823 // close Hwoutput and remove from mHwOutputs
3824 } else {
3825 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3826 }
3827 }
3828 return NO_ERROR;
3829}
3830
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003831sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003832 audio_io_handle_t output, routing_strategy strategy)
3833{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003834 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003835 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003836 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3837 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003838 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003839 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003840 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3841 source = sourceDesc;
3842 break;
3843 }
3844 }
3845 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003846}
3847
Eric Laurente552edb2014-03-10 17:42:56 -07003848// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003849// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003850// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003851uint32_t AudioPolicyManager::nextAudioPortGeneration()
3852{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003853 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003854}
3855
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003856// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3857static const char *kConfigLocationList[] =
3858 {"/odm/etc", "/vendor/etc", "/system/etc"};
3859static const int kConfigLocationListSize =
3860 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3861
3862static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3863 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003864 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003865 status_t ret;
3866
Petri Gyntherf497f292018-04-17 18:46:10 -07003867 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3868 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3869 // A2DP offload supported but disabled: try to use special XML file
3870 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3871 }
3872 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3873
3874 for (const char* fileName : fileNames) {
3875 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003876 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3877 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003878 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003879 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003880 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003881 return ret;
3882 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003883 }
3884 }
3885 return ret;
3886}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003887
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003888AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3889 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003890 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003891 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003892 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003893 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003894 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003895 mVolumeCurves(new VolumeCurvesCollection()),
3896 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003897 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003898 mAudioPortGeneration(1),
3899 mBeaconMuteRefCount(0),
3900 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003901 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003902 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003903 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08003904 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07003905{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003906}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003907
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003908AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3909 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3910{
3911 loadConfig();
3912 initialize();
3913}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003914
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003915// This check is to catch any legacy platform updating to Q without having
3916// switched to XML since its deprecation on O.
3917// TODO: after Q release, remove this check and flag as XML is now the only
3918// option and all legacy platform should have transitioned to XML.
3919#ifndef USE_XML_AUDIO_POLICY_CONF
3920#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003921#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003922
3923void AudioPolicyManager::loadConfig() {
3924 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003925 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003926 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003927 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003928}
3929
3930status_t AudioPolicyManager::initialize() {
3931 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003932
3933 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003934 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3935 if (!engineInstance) {
3936 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003937 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003938 }
3939 // Retrieve the Policy Manager Interface
3940 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3941 if (mEngine == NULL) {
3942 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003943 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003944 }
3945 mEngine->setObserver(this);
3946 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003947 if (status != NO_ERROR) {
3948 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3949 return status;
3950 }
François Gaffie2110e042015-03-24 08:41:51 +01003951
Eric Laurent3a4311c2014-03-17 12:00:47 -07003952 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003953 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08003954 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003955 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003956 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3957 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003958 continue;
3959 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003960 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003961 // open all output streams needed to access attached devices
3962 // except for direct output streams that are only opened when they are actually
3963 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003964 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003965 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003966 if (!outProfile->canOpenNewIo()) {
3967 ALOGE("Invalid Output profile max open count %u for profile %s",
3968 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3969 continue;
3970 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003971 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003972 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003973 continue;
3974 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003975 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003976 mTtsOutputAvailable = true;
3977 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003978
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003979 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003980 continue;
3981 }
François Gaffie11d30102018-11-02 16:09:09 +01003982 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3983 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
3984 sp<DeviceDescriptor> supportedDevice = 0;
3985 if (supportedDevices.contains(mDefaultOutputDevice)) {
3986 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07003987 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003988 // choose first device present in profile's SupportedDevices also part of
3989 // mAvailableOutputDevices.
3990 if (availProfileDevices.isEmpty()) {
3991 continue;
3992 }
3993 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07003994 }
François Gaffie11d30102018-11-02 16:09:09 +01003995 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003996 continue;
3997 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003998 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3999 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004000 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004001 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4002 AUDIO_STREAM_DEFAULT,
4003 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004004 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004005 ALOGW("Cannot open output stream for devices %s on hw module %s",
4006 supportedDevice->toString().c_str(), hwModule->getName());
4007 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004008 }
François Gaffie11d30102018-11-02 16:09:09 +01004009 for (const auto &device : availProfileDevices) {
4010 // give a valid ID to an attached device once confirmed it is reachable
4011 if (!device->isAttached()) {
4012 device->attach(hwModule);
4013 }
4014 }
4015 if (mPrimaryOutput == 0 &&
4016 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4017 mPrimaryOutput = outputDesc;
4018 }
4019 addOutput(output, outputDesc);
4020 setOutputDevices(outputDesc,
4021 DeviceVector(supportedDevice),
4022 true,
4023 0,
4024 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004025 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004026 // open input streams needed to access attached devices to validate
4027 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004028 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004029 if (!inProfile->canOpenNewIo()) {
4030 ALOGE("Invalid Input profile max open count %u for profile %s",
4031 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4032 continue;
4033 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004034 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004035 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004036 continue;
4037 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004038 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004039 // available input devices
4040 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4041 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4042 if (availProfileDevices.isEmpty()) {
4043 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004044 continue;
4045 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004046 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004047 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004048
Eric Laurentd78f1532014-09-16 16:38:20 -07004049 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004050 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004051 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004052 AUDIO_SOURCE_MIC,
4053 AUDIO_INPUT_FLAG_NONE,
4054 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004055 if (status != NO_ERROR) {
4056 ALOGW("Cannot open input stream for device %s on hw module %s",
4057 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004058 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004059 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004060 }
François Gaffie11d30102018-11-02 16:09:09 +01004061 for (const auto &device : availProfileDevices) {
4062 // give a valid ID to an attached device once confirmed it is reachable
4063 if (!device->isAttached()) {
4064 device->attach(hwModule);
4065 device->importAudioPort(inProfile, true);
4066 }
4067 }
4068 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004069 }
4070 }
4071 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004072 auto checkAndSetAvailable = [this](auto& devices) {
4073 for (const auto &device : devices) {
4074 if (!device->isAttached()) {
4075 ALOGW("device %s is unreachable", device->toString().c_str());
4076 devices.remove(device);
4077 continue;
4078 }
4079 // Device is now validated and can be appended to the available devices of the engine
4080 mEngine->setDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004081 }
François Gaffie11d30102018-11-02 16:09:09 +01004082 };
4083 checkAndSetAvailable(mAvailableOutputDevices);
4084 checkAndSetAvailable(mAvailableInputDevices);
4085
Eric Laurent3a4311c2014-03-17 12:00:47 -07004086 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004087 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4088 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4089 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004090 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004091 }
jiabin9ff780e2018-03-19 18:19:52 -07004092 // If microphones address is empty, set it according to device type
4093 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004094 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004095 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004096 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004097 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004098 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004099 }
4100 }
4101 }
Eric Laurente552edb2014-03-10 17:42:56 -07004102
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004103 if (mPrimaryOutput == 0) {
4104 ALOGE("Failed to open primary output");
4105 status = NO_INIT;
4106 }
Eric Laurente552edb2014-03-10 17:42:56 -07004107
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004108 // Silence ALOGV statements
4109 property_set("log.tag." LOG_TAG, "D");
4110
Eric Laurente552edb2014-03-10 17:42:56 -07004111 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004112 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004113}
4114
Eric Laurente0720872014-03-11 09:30:41 -07004115AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004116{
Eric Laurente552edb2014-03-10 17:42:56 -07004117 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004118 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004119 }
4120 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004121 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004122 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004123 mAvailableOutputDevices.clear();
4124 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004125 mOutputs.clear();
4126 mInputs.clear();
4127 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004128 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004129 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004130}
4131
Eric Laurente0720872014-03-11 09:30:41 -07004132status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004133{
Eric Laurent87ffa392015-05-22 10:32:38 -07004134 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004135}
4136
Eric Laurente552edb2014-03-10 17:42:56 -07004137// ---
4138
Eric Laurent98e38192018-02-15 18:31:53 -08004139void AudioPolicyManager::addOutput(audio_io_handle_t output,
4140 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004141{
Eric Laurent1c333e22014-05-20 10:48:17 -07004142 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004143 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004144 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004145 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004146 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004147}
4148
François Gaffie53615e22015-03-19 09:24:12 +01004149void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4150{
4151 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004152 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004153}
4154
Eric Laurent98e38192018-02-15 18:31:53 -08004155void AudioPolicyManager::addInput(audio_io_handle_t input,
4156 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004157{
Eric Laurent1c333e22014-05-20 10:48:17 -07004158 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004159 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004160}
Eric Laurente552edb2014-03-10 17:42:56 -07004161
François Gaffie11d30102018-11-02 16:09:09 +01004162status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004163 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004164 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004165{
François Gaffie11d30102018-11-02 16:09:09 +01004166 audio_devices_t deviceType = device->type();
4167 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004168 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004169
François Gaffie11d30102018-11-02 16:09:09 +01004170 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004171 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004172 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004173 }
Eric Laurente552edb2014-03-10 17:42:56 -07004174
Eric Laurent3b73df72014-03-11 09:06:29 -07004175 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004176 // first list already open outputs that can be routed to this device
4177 for (size_t i = 0; i < mOutputs.size(); i++) {
4178 desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01004179 if (!desc->isDuplicated() && desc->supportsDevice(device)) {
4180 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4181 mOutputs.keyAt(i), device->toString().c_str());
4182 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004183 }
4184 }
4185 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004186 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004187 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004188 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4189 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004190 if (profile->supportsDevice(device)) {
4191 profiles.add(profile);
4192 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4193 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004194 }
4195 }
4196 }
4197
Eric Laurent7b279bb2015-12-14 10:18:23 -08004198 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004199
Eric Laurente552edb2014-03-10 17:42:56 -07004200 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004201 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004202 return BAD_VALUE;
4203 }
4204
4205 // open outputs for matching profiles if needed. Direct outputs are also opened to
4206 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4207 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004208 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004209
4210 // nothing to do if one output is already opened for this profile
4211 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004212 for (j = 0; j < outputs.size(); j++) {
4213 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004214 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004215 // matching profile: save the sample rates, format and channel masks supported
4216 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004217 if (audio_device_is_digital(deviceType)) {
4218 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004219 }
Eric Laurente552edb2014-03-10 17:42:56 -07004220 break;
4221 }
4222 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004223 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004224 continue;
4225 }
4226
Eric Laurent3974e3b2017-12-07 17:58:43 -08004227 if (!profile->canOpenNewIo()) {
4228 ALOGW("Max Output number %u already opened for this profile %s",
4229 profile->maxOpenCount, profile->getTagName().c_str());
4230 continue;
4231 }
4232
Eric Laurent83efe1c2017-07-09 16:51:08 -07004233 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004234 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004235 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004236 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004237 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004238 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004239
Eric Laurentfe231122017-11-17 17:48:06 -08004240 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004241 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004242 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004243 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004244 mpClientInterface->setParameters(output, String8(param));
4245 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004246 }
François Gaffie11d30102018-11-02 16:09:09 +01004247 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004248 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004249 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004250 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004251 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004252 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004253 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004254 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004255 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4256 profile->pickAudioProfile(
4257 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004258 config.offload_info.sample_rate = config.sample_rate;
4259 config.offload_info.channel_mask = config.channel_mask;
4260 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004261
François Gaffie11d30102018-11-02 16:09:09 +01004262 status_t status = desc->open(&config, DeviceVector(device),
4263 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004264 AUDIO_OUTPUT_FLAG_NONE, &output);
4265 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004266 output = AUDIO_IO_HANDLE_NONE;
4267 }
Eric Laurentd4692962014-05-05 18:13:44 -07004268 }
4269
Eric Laurentcf2c0212014-07-25 16:20:43 -07004270 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004271 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004272 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004273 sp<AudioPolicyMix> policyMix;
4274 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004275 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4276 address.string());
4277 }
François Gaffie036e1e92015-03-19 10:16:24 +01004278 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004279 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004280
Eric Laurent87ffa392015-05-22 10:32:38 -07004281 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4282 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004283 // no duplicated output for direct outputs and
4284 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004285 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004286
Eric Laurentd4692962014-05-05 18:13:44 -07004287 //TODO: configure audio effect output stage here
4288
4289 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004290 sp<SwAudioOutputDescriptor> dupOutputDesc =
4291 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4292 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4293 &duplicatedOutput);
4294 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004295 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004296 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004297 } else {
4298 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004299 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004300 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004301 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004302 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004303 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004304 }
Eric Laurente552edb2014-03-10 17:42:56 -07004305 }
4306 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004307 } else {
4308 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004309 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004310 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004311 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004312 profiles.removeAt(profile_index);
4313 profile_index--;
4314 } else {
4315 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004316 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004317 if (audio_device_is_digital(deviceType)) {
4318 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004319 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004320
François Gaffie11d30102018-11-02 16:09:09 +01004321 if (device_distinguishes_on_address(deviceType)) {
4322 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4323 device->toString().c_str());
4324 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4325 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004326 }
Eric Laurente552edb2014-03-10 17:42:56 -07004327 ALOGV("checkOutputsForDevice(): adding output %d", output);
4328 }
4329 }
4330
4331 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004332 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004333 return BAD_VALUE;
4334 }
Eric Laurentd4692962014-05-05 18:13:44 -07004335 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004336 // check if one opened output is not needed any more after disconnecting one device
4337 for (size_t i = 0; i < mOutputs.size(); i++) {
4338 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004339 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004340 // exact match on device
Francois Gaffie716e1432019-01-14 16:58:59 +01004341 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01004342 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004343 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004344 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4345 mOutputs.keyAt(i));
4346 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004347 }
Eric Laurente552edb2014-03-10 17:42:56 -07004348 }
4349 }
Eric Laurentd4692962014-05-05 18:13:44 -07004350 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004351 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004352 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4353 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004354 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004355 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004356 "clearing direct output profile %zu on module %s",
4357 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004358 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004359 }
4360 }
4361 }
4362 }
4363 return NO_ERROR;
4364}
4365
François Gaffie11d30102018-11-02 16:09:09 +01004366status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004367 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004368 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004369{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004370 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004371
François Gaffie11d30102018-11-02 16:09:09 +01004372 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004373 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004374 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004375 }
4376
Eric Laurentd4692962014-05-05 18:13:44 -07004377 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4378 // first list already open inputs that can be routed to this device
4379 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4380 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004381 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004382 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4383 inputs.add(mInputs.keyAt(input_index));
4384 }
4385 }
4386
4387 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004388 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004389 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004390 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004391 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004392 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004393 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004394
François Gaffie11d30102018-11-02 16:09:09 +01004395 if (profile->supportsDevice(device)) {
4396 profiles.add(profile);
4397 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4398 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004399 }
4400 }
4401 }
4402
4403 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004404 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004405 return BAD_VALUE;
4406 }
4407
4408 // open inputs for matching profiles if needed. Direct inputs are also opened to
4409 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4410 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4411
Eric Laurent1c333e22014-05-20 10:48:17 -07004412 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004413
Eric Laurentd4692962014-05-05 18:13:44 -07004414 // nothing to do if one input is already opened for this profile
4415 size_t input_index;
4416 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4417 desc = mInputs.valueAt(input_index);
4418 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004419 if (audio_device_is_digital(device->type())) {
4420 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004421 }
Eric Laurentd4692962014-05-05 18:13:44 -07004422 break;
4423 }
4424 }
4425 if (input_index != mInputs.size()) {
4426 continue;
4427 }
4428
Eric Laurent3974e3b2017-12-07 17:58:43 -08004429 if (!profile->canOpenNewIo()) {
4430 ALOGW("Max Input number %u already opened for this profile %s",
4431 profile->maxOpenCount, profile->getTagName().c_str());
4432 continue;
4433 }
4434
Eric Laurentfe231122017-11-17 17:48:06 -08004435 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004436 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004437 status_t status = desc->open(nullptr,
4438 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004439 AUDIO_SOURCE_MIC,
4440 AUDIO_INPUT_FLAG_NONE,
4441 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004442
Eric Laurentcf2c0212014-07-25 16:20:43 -07004443 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004444 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004445 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004446 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004447 mpClientInterface->setParameters(input, String8(param));
4448 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004449 }
François Gaffie11d30102018-11-02 16:09:09 +01004450 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004451 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004452 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004453 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004454 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004455 }
4456
4457 if (input != 0) {
4458 addInput(input, desc);
4459 }
4460 } // endif input != 0
4461
Eric Laurentcf2c0212014-07-25 16:20:43 -07004462 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004463 ALOGW("%s could not open input for device %s", __func__,
4464 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004465 profiles.removeAt(profile_index);
4466 profile_index--;
4467 } else {
4468 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004469 if (audio_device_is_digital(device->type())) {
4470 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004471 }
Eric Laurentd4692962014-05-05 18:13:44 -07004472 ALOGV("checkInputsForDevice(): adding input %d", input);
4473 }
4474 } // end scan profiles
4475
4476 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004477 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004478 return BAD_VALUE;
4479 }
4480 } else {
4481 // Disconnect
4482 // check if one opened input is not needed any more after disconnecting one device
4483 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4484 desc = mInputs.valueAt(input_index);
Francois Gaffie716e1432019-01-14 16:58:59 +01004485 if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004486 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4487 mInputs.keyAt(input_index));
4488 inputs.add(mInputs.keyAt(input_index));
4489 }
4490 }
4491 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004492 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004493 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004494 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004495 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004496 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004497 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004498 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4499 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004500 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004501 }
4502 }
4503 }
4504 } // end disconnect
4505
4506 return NO_ERROR;
4507}
4508
4509
Eric Laurente0720872014-03-11 09:30:41 -07004510void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004511{
4512 ALOGV("closeOutput(%d)", output);
4513
Eric Laurentc75307b2015-03-17 15:29:32 -07004514 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004515 if (outputDesc == NULL) {
4516 ALOGW("closeOutput() unknown output %d", output);
4517 return;
4518 }
François Gaffie036e1e92015-03-19 10:16:24 +01004519 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004520
Eric Laurente552edb2014-03-10 17:42:56 -07004521 // look for duplicated outputs connected to the output being removed.
4522 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004523 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004524 if (dupOutputDesc->isDuplicated() &&
4525 (dupOutputDesc->mOutput1 == outputDesc ||
4526 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004527 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004528 if (dupOutputDesc->mOutput1 == outputDesc) {
4529 outputDesc2 = dupOutputDesc->mOutput2;
4530 } else {
4531 outputDesc2 = dupOutputDesc->mOutput1;
4532 }
4533 // As all active tracks on duplicated output will be deleted,
4534 // and as they were also referenced on the other output, the reference
4535 // count for their stream type must be adjusted accordingly on
4536 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004537 const bool wasActive = outputDesc2->isActive();
4538 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4539 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004540 }
Eric Laurent733ce942017-12-07 12:18:25 -08004541 // stop() will be a no op if the output is still active but is needed in case all
4542 // active streams refcounts where cleared above
4543 if (wasActive) {
4544 outputDesc2->stop();
4545 }
Eric Laurente552edb2014-03-10 17:42:56 -07004546 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4547 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4548
4549 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004550 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004551 }
4552 }
4553
Eric Laurent05b90f82014-08-27 15:32:29 -07004554 nextAudioPortGeneration();
4555
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004556 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004557 if (index >= 0) {
4558 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004559 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004560 mAudioPatches.removeItemsAt(index);
4561 mpClientInterface->onAudioPatchListUpdate();
4562 }
4563
Eric Laurentfe231122017-11-17 17:48:06 -08004564 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004565
François Gaffie53615e22015-03-19 09:24:12 +01004566 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004567 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004568
4569 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4570 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004571 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004572 bool directOutputOpen = false;
4573 for (size_t i = 0; i < mOutputs.size(); i++) {
4574 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4575 directOutputOpen = true;
4576 break;
4577 }
4578 }
4579 if (!directOutputOpen) {
4580 ALOGV("no direct outputs open, reset MSD patch");
4581 setMsdPatch();
4582 }
4583 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004584}
4585
4586void AudioPolicyManager::closeInput(audio_io_handle_t input)
4587{
4588 ALOGV("closeInput(%d)", input);
4589
4590 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4591 if (inputDesc == NULL) {
4592 ALOGW("closeInput() unknown input %d", input);
4593 return;
4594 }
4595
Eric Laurent6a94d692014-05-20 11:18:06 -07004596 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004597
François Gaffie11d30102018-11-02 16:09:09 +01004598 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004599 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004600 if (index >= 0) {
4601 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004602 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004603 mAudioPatches.removeItemsAt(index);
4604 mpClientInterface->onAudioPatchListUpdate();
4605 }
4606
Eric Laurentfe231122017-11-17 17:48:06 -08004607 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004608 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004609
François Gaffie11d30102018-11-02 16:09:09 +01004610 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4611 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004612 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4613 SoundTrigger::setCaptureState(false);
4614 }
Eric Laurente552edb2014-03-10 17:42:56 -07004615}
4616
François Gaffie11d30102018-11-02 16:09:09 +01004617SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4618 const DeviceVector &devices,
4619 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004620{
4621 SortedVector<audio_io_handle_t> outputs;
4622
François Gaffie11d30102018-11-02 16:09:09 +01004623 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004624 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004625 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004626 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004627 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Francois Gaffie716e1432019-01-14 16:58:59 +01004628 if (openOutputs.valueAt(i)->supportsAllDevices(devices)) {
François Gaffie11d30102018-11-02 16:09:09 +01004629 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004630 outputs.add(openOutputs.keyAt(i));
4631 }
4632 }
4633 return outputs;
4634}
4635
Mikhail Naganov37977152018-07-11 15:54:44 -07004636void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4637{
4638 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4639 // output is suspended before any tracks are moved to it
4640 checkA2dpSuspend();
4641 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004642 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004643 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004644 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004645 setMsdPatch();
4646 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004647}
4648
Eric Laurente0720872014-03-11 09:30:41 -07004649void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004650{
François Gaffie11d30102018-11-02 16:09:09 +01004651 DeviceVector oldDevices = getDevicesForStrategy(strategy, true /*fromCache*/);
4652 DeviceVector newDevices = getDevicesForStrategy(strategy, false /*fromCache*/);
4653 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4654 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004655
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004656 // also take into account external policy-related changes: add all outputs which are
4657 // associated with policies in the "before" and "after" output vectors
4658 ALOGVV("checkOutputForStrategy(): policy related outputs");
4659 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004660 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004661 if (desc != 0 && desc->mPolicyMix != NULL) {
4662 srcOutputs.add(desc->mIoHandle);
4663 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4664 }
4665 }
4666 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004667 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004668 if (desc != 0 && desc->mPolicyMix != NULL) {
4669 dstOutputs.add(desc->mIoHandle);
4670 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4671 }
4672 }
4673
Francois Gaffie716e1432019-01-14 16:58:59 +01004674 if (!dstOutputs.isEmpty() && srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004675 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4676 // audio from invalidated tracks will be rendered when unmuting
4677 uint32_t maxLatency = 0;
4678 for (audio_io_handle_t srcOut : srcOutputs) {
4679 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4680 if (desc != 0 && maxLatency < desc->latency()) {
4681 maxLatency = desc->latency();
4682 }
4683 }
François Gaffie11d30102018-11-02 16:09:09 +01004684 ALOGV("%s: strategy %d, moving from output %s to output %s", __func__, strategy,
4685 (srcOutputs.isEmpty()? "none" : std::to_string(srcOutputs[0]).c_str()),
4686 (dstOutputs.isEmpty()? "none" : std::to_string(dstOutputs[0]).c_str()));
Eric Laurente552edb2014-03-10 17:42:56 -07004687 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004688 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004689 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4690 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004691 setStrategyMute(strategy, true, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004692 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
4693 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004694 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004695 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004696 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004697 if (source != 0){
4698 connectAudioSource(source);
4699 }
Eric Laurente552edb2014-03-10 17:42:56 -07004700 }
4701
4702 // Move effects associated to this strategy from previous output to new output
4703 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004704 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004705 }
4706 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004707 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004708 if (getStrategy((audio_stream_type_t)i) == strategy) {
4709 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004710 }
4711 }
4712 }
4713}
4714
Eric Laurente0720872014-03-11 09:30:41 -07004715void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004716{
François Gaffie2110e042015-03-24 08:41:51 +01004717 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004718 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004719 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004720 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004721 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004722 checkOutputForStrategy(STRATEGY_SONIFICATION);
4723 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004724 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004725 checkOutputForStrategy(STRATEGY_MEDIA);
4726 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004727 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004728}
4729
Eric Laurente0720872014-03-11 09:30:41 -07004730void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004731{
François Gaffie53615e22015-03-19 09:24:12 +01004732 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004733 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004734 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004735 return;
4736 }
4737
Eric Laurent3a4311c2014-03-17 12:00:47 -07004738 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004739 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4740 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4741 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004742
4743 // if suspended, restore A2DP output if:
4744 // ((SCO device is NOT connected) ||
4745 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4746 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004747 //
Eric Laurentf732e072016-08-03 19:30:28 -07004748 // if not suspended, suspend A2DP output if:
4749 // (SCO device is connected) &&
4750 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4751 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004752 //
4753 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004754 if (!isScoConnected ||
4755 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4756 AUDIO_POLICY_FORCE_BT_SCO) &&
4757 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4758 AUDIO_POLICY_FORCE_BT_SCO) &&
4759 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004760 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004761
4762 mpClientInterface->restoreOutput(a2dpOutput);
4763 mA2dpSuspended = false;
4764 }
4765 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004766 if (isScoConnected &&
4767 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4768 AUDIO_POLICY_FORCE_BT_SCO) ||
4769 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4770 AUDIO_POLICY_FORCE_BT_SCO) ||
4771 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004772 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004773
4774 mpClientInterface->suspendOutput(a2dpOutput);
4775 mA2dpSuspended = true;
4776 }
4777 }
4778}
4779
Eric Laurent97ac8712018-07-27 18:59:02 -07004780template <class IoDescriptor, class Filter>
4781sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4782 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4783{
4784 auto activeClients = desc->clientsList(true /*activeOnly*/);
4785 auto activeClientsWithRoute =
4786 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4787 active = activeClients.size() > 0;
4788 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4789 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4790 }
4791 return nullptr;
4792}
4793
4794template <class IoCollection, class Filter>
4795sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4796 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4797{
4798 sp<DeviceDescriptor> device;
4799 for (size_t i = 0; i < ioCollection.size(); i++) {
4800 auto desc = ioCollection.valueAt(i);
4801 bool active;
4802 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4803 if (active && curDevice == nullptr) {
4804 return nullptr;
4805 } else if (curDevice != nullptr) {
4806 device = curDevice;
4807 }
4808 }
4809 return device;
4810}
4811
François Gaffie11d30102018-11-02 16:09:09 +01004812DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
4813 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004814{
François Gaffie11d30102018-11-02 16:09:09 +01004815 DeviceVector devices;
4816
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004817 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004818 if (index >= 0) {
4819 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4820 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004821 ALOGV("%s device %s forced by patch %d", __func__,
4822 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
4823 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07004824 }
4825 }
4826
Eric Laurent97ac8712018-07-27 18:59:02 -07004827 // Honor explicit routing requests only if no client using default routing is active on this
4828 // input: a specific app can not force routing for other apps by setting a preferred device.
4829 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01004830 sp<DeviceDescriptor> device =
Eric Laurent97ac8712018-07-27 18:59:02 -07004831 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01004832 if (device != nullptr) {
4833 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07004834 }
4835
Eric Laurente552edb2014-03-10 17:42:56 -07004836 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004837 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004838 // use device for strategy enforced audible
4839 // 2: we are in call or the strategy phone is active on the output:
4840 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004841 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004842 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004843 // 4: the strategy for enforced audible is active but not enforced on the output:
4844 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004845 // 5: the strategy accessibility is active on the output:
4846 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004847 // 6: the strategy "respectful" sonification is active on the output:
4848 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004849 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004850 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004851 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004852 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004853 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004854 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004855
4856 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4857 // with a refined rule considering mutually exclusive devices (using same backend)
4858 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004859 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004860 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffie11d30102018-11-02 16:09:09 +01004861 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004862 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004863 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
François Gaffie11d30102018-11-02 16:09:09 +01004864 devices = getDevicesForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004865 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
François Gaffie11d30102018-11-02 16:09:09 +01004866 devices = getDevicesForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004867 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
François Gaffie11d30102018-11-02 16:09:09 +01004868 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004869 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
François Gaffie11d30102018-11-02 16:09:09 +01004870 devices = getDevicesForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004871 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
François Gaffie11d30102018-11-02 16:09:09 +01004872 devices = getDevicesForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004873 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
François Gaffie11d30102018-11-02 16:09:09 +01004874 devices = getDevicesForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004875 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
François Gaffie11d30102018-11-02 16:09:09 +01004876 devices = getDevicesForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004877 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
François Gaffie11d30102018-11-02 16:09:09 +01004878 devices = getDevicesForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004879 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
François Gaffie11d30102018-11-02 16:09:09 +01004880 devices = getDevicesForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004881 }
4882
François Gaffie11d30102018-11-02 16:09:09 +01004883 ALOGV("getNewOutputDevice() selected devices %s", devices.toString().c_str());
4884 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07004885}
4886
François Gaffie11d30102018-11-02 16:09:09 +01004887sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
4888 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004889{
François Gaffie11d30102018-11-02 16:09:09 +01004890 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07004891
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004892 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004893 if (index >= 0) {
4894 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4895 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004896 ALOGV("getNewInputDevice() device %s forced by patch %d",
4897 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
4898 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 }
4900 }
4901
Eric Laurent97ac8712018-07-27 18:59:02 -07004902 // Honor explicit routing requests only if no client using default routing is active on this
4903 // input: a specific app can not force routing for other apps by setting a preferred device.
4904 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01004905 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4906 if (device != nullptr) {
4907 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07004908 }
4909
Eric Laurentdc95a252018-04-12 12:46:56 -07004910 // If we are not in call and no client is active on this input, this methods returns
4911 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01004912 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
4913 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4914 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07004915 }
Francois Gaffie716e1432019-01-14 16:58:59 +01004916 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
4917 device = getDeviceAndMixForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08004918 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004919
Eric Laurente552edb2014-03-10 17:42:56 -07004920 return device;
4921}
4922
Eric Laurent794fde22016-03-11 09:50:45 -08004923bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4924 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004925 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004926}
4927
Eric Laurente0720872014-03-11 09:30:41 -07004928uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004929 return (uint32_t)getStrategy(stream);
4930}
4931
Eric Laurente0720872014-03-11 09:30:41 -07004932audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004933 // By checking the range of stream before calling getStrategy, we avoid
4934 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4935 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004936 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004937 return AUDIO_DEVICE_NONE;
4938 }
François Gaffie11d30102018-11-02 16:09:09 +01004939 DeviceVector activeDevices;
4940 DeviceVector devices;
Eric Laurent794fde22016-03-11 09:50:45 -08004941 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4942 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004943 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004944 }
Eric Laurent794fde22016-03-11 09:50:45 -08004945 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
François Gaffie11d30102018-11-02 16:09:09 +01004946 DeviceVector curDevices =
4947 getDevicesForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
4948 devices.merge(curDevices);
4949 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004950 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004951 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
François Gaffie11d30102018-11-02 16:09:09 +01004952 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08004953 }
4954 }
Eric Laurente552edb2014-03-10 17:42:56 -07004955 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004956
Eric Laurentb0688d62018-08-14 15:49:18 -07004957 // Favor devices selected on active streams if any to report correct device in case of
4958 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01004959 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004960 devices = activeDevices;
4961 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004962 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4963 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01004964 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
4965 if (!speakerSafeDevices.isEmpty()) {
4966 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
4967 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004968 }
François Gaffie11d30102018-11-02 16:09:09 +01004969 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004970}
4971
François Gaffie2110e042015-03-24 08:41:51 +01004972routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4973{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004974 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004975 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004976}
4977
Eric Laurent97ac8712018-07-27 18:59:02 -07004978routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004979 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004980 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004981 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004982 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004983 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004984 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004985 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004986 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004987 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004988}
4989
Eric Laurente0720872014-03-11 09:30:41 -07004990void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004991 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004992 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004993 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4994 updateDevicesAndOutputs();
4995 break;
4996 default:
4997 break;
4998 }
4999}
5000
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005001uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005002
5003 // skip beacon mute management if a dedicated TTS output is available
5004 if (mTtsOutputAvailable) {
5005 return 0;
5006 }
5007
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005008 switch(event) {
5009 case STARTING_OUTPUT:
5010 mBeaconMuteRefCount++;
5011 break;
5012 case STOPPING_OUTPUT:
5013 if (mBeaconMuteRefCount > 0) {
5014 mBeaconMuteRefCount--;
5015 }
5016 break;
5017 case STARTING_BEACON:
5018 mBeaconPlayingRefCount++;
5019 break;
5020 case STOPPING_BEACON:
5021 if (mBeaconPlayingRefCount > 0) {
5022 mBeaconPlayingRefCount--;
5023 }
5024 break;
5025 }
5026
5027 if (mBeaconMuteRefCount > 0) {
5028 // any playback causes beacon to be muted
5029 return setBeaconMute(true);
5030 } else {
5031 // no other playback: unmute when beacon starts playing, mute when it stops
5032 return setBeaconMute(mBeaconPlayingRefCount == 0);
5033 }
5034}
5035
5036uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5037 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5038 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5039 // keep track of muted state to avoid repeating mute/unmute operations
5040 if (mBeaconMuted != mute) {
5041 // mute/unmute AUDIO_STREAM_TTS on all outputs
5042 ALOGV("\t muting %d", mute);
5043 uint32_t maxLatency = 0;
5044 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005045 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005046 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005047 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005048 0 /*delay*/, AUDIO_DEVICE_NONE);
5049 const uint32_t latency = desc->latency() * 2;
5050 if (latency > maxLatency) {
5051 maxLatency = latency;
5052 }
5053 }
5054 mBeaconMuted = mute;
5055 return maxLatency;
5056 }
5057 return 0;
5058}
5059
François Gaffie11d30102018-11-02 16:09:09 +01005060DeviceVector AudioPolicyManager::getDevicesForStrategy(routing_strategy strategy, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005061{
Eric Laurent97ac8712018-07-27 18:59:02 -07005062 // Honor explicit routing requests only if all active clients have a preferred route in which
5063 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005064 sp<DeviceDescriptor> device = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5065 if (device != nullptr) {
5066 return DeviceVector(device);
Paul McLeanaa981192015-03-21 09:55:15 -07005067 }
5068
Eric Laurente552edb2014-03-10 17:42:56 -07005069 if (fromCache) {
François Gaffie11d30102018-11-02 16:09:09 +01005070 ALOGVV("%s from cache strategy %d, device %s", __func__, strategy,
5071 mDevicesForStrategy[strategy].toString().c_str());
5072 return mDevicesForStrategy[strategy];
Eric Laurente552edb2014-03-10 17:42:56 -07005073 }
François Gaffie11d30102018-11-02 16:09:09 +01005074 return mAvailableOutputDevices.getDevicesFromTypeMask(mEngine->getDeviceForStrategy(strategy));
Eric Laurente552edb2014-03-10 17:42:56 -07005075}
5076
Eric Laurente0720872014-03-11 09:30:41 -07005077void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005078{
5079 for (int i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005080 mDevicesForStrategy[i] = getDevicesForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07005081 }
5082 mPreviousOutputs = mOutputs;
5083}
5084
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005085uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005086 audio_devices_t prevDeviceType,
Eric Laurente552edb2014-03-10 17:42:56 -07005087 uint32_t delayMs)
5088{
5089 // mute/unmute strategies using an incompatible device combination
5090 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5091 // if unmuting, unmute only after the specified delay
5092 if (outputDesc->isDuplicated()) {
5093 return 0;
5094 }
5095
5096 uint32_t muteWaitMs = 0;
François Gaffie11d30102018-11-02 16:09:09 +01005097 audio_devices_t deviceType = outputDesc->devices().types();
5098 bool shouldMute = outputDesc->isActive() && (popcount(deviceType) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005099
5100 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005101 audio_devices_t curDeviceType =
5102 getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5103 curDeviceType = curDeviceType & outputDesc->supportedDevices().types();
5104 bool mute = shouldMute && (curDeviceType & deviceType) && (curDeviceType != deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005105 bool doMute = false;
5106
5107 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5108 doMute = true;
5109 outputDesc->mStrategyMutedByDevice[i] = true;
5110 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5111 doMute = true;
5112 outputDesc->mStrategyMutedByDevice[i] = false;
5113 }
Eric Laurent99401132014-05-07 19:48:15 -07005114 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005115 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005116 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005117 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005118 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005119 continue;
5120 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005121 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
François Gaffie11d30102018-11-02 16:09:09 +01005122 mute ? "muting" : "unmuting", i, curDeviceType);
Eric Laurentc75307b2015-03-17 15:29:32 -07005123 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005124 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005125 if (mute) {
5126 // FIXME: should not need to double latency if volume could be applied
5127 // immediately by the audioflinger mixer. We must account for the delay
5128 // between now and the next time the audioflinger thread for this output
5129 // will process a buffer (which corresponds to one buffer size,
5130 // usually 1/2 or 1/4 of the latency).
5131 if (muteWaitMs < desc->latency() * 2) {
5132 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005133 }
5134 }
5135 }
5136 }
5137 }
5138 }
5139
Eric Laurent99401132014-05-07 19:48:15 -07005140 // temporary mute output if device selection changes to avoid volume bursts due to
5141 // different per device volumes
François Gaffie11d30102018-11-02 16:09:09 +01005142 if (outputDesc->isActive() && (deviceType != prevDeviceType)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005143 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5144 // temporary mute duration is conservatively set to 4 times the reported latency
5145 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5146 if (muteWaitMs < tempMuteWaitMs) {
5147 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005148 }
Eric Laurentdc462862016-07-19 12:29:53 -07005149
Eric Laurent99401132014-05-07 19:48:15 -07005150 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005151 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005152 // make sure that we do not start the temporary mute period too early in case of
5153 // delayed device change
5154 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005155 setStrategyMute((routing_strategy)i, false, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005156 delayMs + tempMuteDurationMs, deviceType);
Eric Laurent99401132014-05-07 19:48:15 -07005157 }
5158 }
5159 }
5160
Eric Laurente552edb2014-03-10 17:42:56 -07005161 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5162 if (muteWaitMs > delayMs) {
5163 muteWaitMs -= delayMs;
5164 usleep(muteWaitMs * 1000);
5165 return muteWaitMs;
5166 }
5167 return 0;
5168}
5169
François Gaffie11d30102018-11-02 16:09:09 +01005170uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5171 const DeviceVector &devices,
5172 bool force,
5173 int delayMs,
5174 audio_patch_handle_t *patchHandle,
5175 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005176{
François Gaffie11d30102018-11-02 16:09:09 +01005177 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005178 uint32_t muteWaitMs;
5179
5180 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005181 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5182 nullptr /* patchHandle */, requiresMuteCheck);
5183 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5184 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005185 return muteWaitMs;
5186 }
Eric Laurente552edb2014-03-10 17:42:56 -07005187
5188 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005189 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Eric Laurente552edb2014-03-10 17:42:56 -07005190
François Gaffie11d30102018-11-02 16:09:09 +01005191 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5192 // output profile
5193 if (!devices.isEmpty() && filteredDevices.isEmpty()) {
5194 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5195 return 0;
5196 }
Eric Laurente552edb2014-03-10 17:42:56 -07005197
François Gaffie11d30102018-11-02 16:09:09 +01005198 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005199
François Gaffie11d30102018-11-02 16:09:09 +01005200 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5201
5202 if (!filteredDevices.isEmpty()) {
5203 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005204 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005205
5206 // if the outputs are not materially active, there is no need to mute.
5207 if (requiresMuteCheck) {
François Gaffie11d30102018-11-02 16:09:09 +01005208 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices.types(), delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005209 } else {
5210 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5211 muteWaitMs = 0;
5212 }
Eric Laurente552edb2014-03-10 17:42:56 -07005213
5214 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005215 // the requested device is AUDIO_DEVICE_NONE
5216 // OR the requested device is the same as current device
5217 // AND force is not specified
5218 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005219 // Doing this check here allows the caller to call setOutputDevices() without conditions
5220 if ((!filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
5221 !force && outputDesc->getPatchHandle() != 0) {
5222 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5223 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005224 return muteWaitMs;
5225 }
5226
François Gaffie11d30102018-11-02 16:09:09 +01005227 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005228
Eric Laurente552edb2014-03-10 17:42:56 -07005229 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005230 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005231 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005232 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005233 PatchBuilder patchBuilder;
5234 patchBuilder.addSource(outputDesc);
5235 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5236 for (const auto &filteredDevice : filteredDevices) {
5237 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005238 }
5239
François Gaffie11d30102018-11-02 16:09:09 +01005240 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005241 }
Eric Laurente552edb2014-03-10 17:42:56 -07005242
5243 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005244 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005245
5246 return muteWaitMs;
5247}
5248
Eric Laurentc75307b2015-03-17 15:29:32 -07005249status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005250 int delayMs,
5251 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005252{
Eric Laurent6a94d692014-05-20 11:18:06 -07005253 ssize_t index;
5254 if (patchHandle) {
5255 index = mAudioPatches.indexOfKey(*patchHandle);
5256 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005257 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005258 }
5259 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005260 return INVALID_OPERATION;
5261 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5263 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005264 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005265 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005266 removeAudioPatch(patchDesc->mHandle);
5267 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005268 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005269 return status;
5270}
5271
5272status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005273 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005274 bool force,
5275 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005276{
5277 status_t status = NO_ERROR;
5278
Eric Laurent1f2f2232014-06-02 12:01:23 -07005279 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005280 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5281 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005282
François Gaffie11d30102018-11-02 16:09:09 +01005283 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005284 PatchBuilder patchBuilder;
5285 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005286 // AUDIO_SOURCE_HOTWORD is for internal use only:
5287 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005288 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5289 auto result = usecase;
5290 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5291 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5292 }
5293 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005294 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005295 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005296 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005297 }
5298 }
5299 return status;
5300}
5301
Eric Laurent6a94d692014-05-20 11:18:06 -07005302status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5303 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005304{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005305 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005306 ssize_t index;
5307 if (patchHandle) {
5308 index = mAudioPatches.indexOfKey(*patchHandle);
5309 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005310 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 }
5312 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005313 return INVALID_OPERATION;
5314 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005315 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5316 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005317 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005318 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005319 removeAudioPatch(patchDesc->mHandle);
5320 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005321 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005322 return status;
5323}
5324
François Gaffie11d30102018-11-02 16:09:09 +01005325sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005326 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005327 audio_format_t& format,
5328 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005329 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005330{
5331 // Choose an input profile based on the requested capture parameters: select the first available
5332 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005333 //
5334 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5335 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005336
Glenn Kasten730b9262018-03-29 15:01:26 -07005337 sp<IOProfile> firstInexact;
5338 uint32_t updatedSamplingRate = 0;
5339 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5340 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005341 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005342 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005343 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005344 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005345 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005346 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005347 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005348 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005349 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005350 &channelMask /*updatedChannelMask*/,
5351 // FIXME ugly cast
5352 (audio_output_flags_t) flags,
5353 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005354 return profile;
5355 }
François Gaffie11d30102018-11-02 16:09:09 +01005356 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005357 samplingRate,
5358 &updatedSamplingRate,
5359 format,
5360 &updatedFormat,
5361 channelMask,
5362 &updatedChannelMask,
5363 // FIXME ugly cast
5364 (audio_output_flags_t) flags,
5365 false /*exactMatchRequiredForInputFlags*/)) {
5366 firstInexact = profile;
5367 }
5368
Eric Laurente552edb2014-03-10 17:42:56 -07005369 }
5370 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005371 if (firstInexact != nullptr) {
5372 samplingRate = updatedSamplingRate;
5373 format = updatedFormat;
5374 channelMask = updatedChannelMask;
5375 return firstInexact;
5376 }
Eric Laurente552edb2014-03-10 17:42:56 -07005377 return NULL;
5378}
5379
Francois Gaffie716e1432019-01-14 16:58:59 +01005380sp<DeviceDescriptor> AudioPolicyManager::getDeviceAndMixForAttributes(
5381 const audio_attributes_t &attributes, AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005382{
Eric Laurent97ac8712018-07-27 18:59:02 -07005383 // Honor explicit routing requests only if all active clients have a preferred route in which
5384 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005385 sp<DeviceDescriptor> device =
Francois Gaffie716e1432019-01-14 16:58:59 +01005386 findPreferredDevice(mInputs, attributes.source, mAvailableInputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005387 if (device != nullptr) {
5388 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005389 }
5390
François Gaffie11d30102018-11-02 16:09:09 +01005391 sp<DeviceDescriptor> selectedDeviceFromMix =
Francois Gaffie716e1432019-01-14 16:58:59 +01005392 mPolicyMixes.getDeviceAndMixForInputSource(attributes.source, mAvailableInputDevices,
François Gaffie11d30102018-11-02 16:09:09 +01005393 policyMix);
5394 return (selectedDeviceFromMix != nullptr) ?
Francois Gaffie716e1432019-01-14 16:58:59 +01005395 selectedDeviceFromMix : getDeviceForAttributes(attributes);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005396}
5397
Francois Gaffie716e1432019-01-14 16:58:59 +01005398sp<DeviceDescriptor> AudioPolicyManager::getDeviceForAttributes(const audio_attributes_t &attributes)
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005399{
Francois Gaffie716e1432019-01-14 16:58:59 +01005400 audio_devices_t device = mEngine->getDeviceForInputSource(attributes.source);
5401 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
5402 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
5403 return mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
5404 String8(attributes.tags + strlen("addr=")));
5405 }
François Gaffie11d30102018-11-02 16:09:09 +01005406 return mAvailableInputDevices.getDevice(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005407}
5408
Eric Laurente0720872014-03-11 09:30:41 -07005409float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005410 int index,
5411 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005412{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005413 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005414
5415 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5416 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5417 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5418 // the ringtone volume
5419 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5420 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5421 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5422 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5423 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5424 }
5425
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005426 // in-call: always cap volume by voice volume + some low headroom
5427 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005428 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005429 switch (stream) {
5430 case AUDIO_STREAM_SYSTEM:
5431 case AUDIO_STREAM_RING:
5432 case AUDIO_STREAM_MUSIC:
5433 case AUDIO_STREAM_ALARM:
5434 case AUDIO_STREAM_NOTIFICATION:
5435 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5436 case AUDIO_STREAM_DTMF:
5437 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005438 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005439 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005440 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005441 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005442 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005443 if (volumeDB > maxVoiceVolDb) {
5444 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5445 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5446 volumeDB = maxVoiceVolDb;
5447 }
5448 } break;
5449 default:
5450 break;
5451 }
5452 }
5453
Eric Laurente552edb2014-03-10 17:42:56 -07005454 // if a headset is connected, apply the following rules to ring tones and notifications
5455 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005456 // - always attenuate notifications volume by 6dB
5457 // - attenuate ring tones volume by 6dB unless music is not playing and
5458 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005459 // - if music is playing, always limit the volume to current music volume,
5460 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005461 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005462 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5463 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5464 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005465 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005466 AUDIO_DEVICE_OUT_USB_HEADSET |
5467 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005468 ((stream_strategy == STRATEGY_SONIFICATION)
5469 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005470 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005471 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005472 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005473 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005474 // when the phone is ringing we must consider that music could have been paused just before
5475 // by the music application and behave as if music was active if the last music track was
5476 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005477 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005478 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005479 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005480 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005481 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005482 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5483 musicDevice),
5484 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005485 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5486 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005487 if (volumeDB > minVolDB) {
5488 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005489 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005490 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005491 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5492 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5493 // on A2DP, also ensure notification volume is not too low compared to media when
5494 // intended to be played
5495 if ((volumeDB > -96.0f) &&
5496 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5497 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5498 stream, device,
5499 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5500 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5501 }
5502 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005503 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5504 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005505 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005506 }
5507 }
5508
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005509 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005510}
5511
Eric Laurent3839bc02018-07-10 18:33:34 -07005512int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5513 audio_stream_type_t srcStream,
5514 audio_stream_type_t dstStream)
5515{
5516 if (srcStream == dstStream) {
5517 return srcIndex;
5518 }
5519 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5520 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5521 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5522 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5523
5524 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5525}
5526
Eric Laurente0720872014-03-11 09:30:41 -07005527status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005528 int index,
5529 const sp<AudioOutputDescriptor>& outputDesc,
5530 audio_devices_t device,
5531 int delayMs,
5532 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005533{
Eric Laurente552edb2014-03-10 17:42:56 -07005534 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005535 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005536 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005537 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005538 return NO_ERROR;
5539 }
François Gaffie2110e042015-03-24 08:41:51 +01005540 audio_policy_forced_cfg_t forceUseForComm =
5541 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005542 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005543 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5544 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005545 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005546 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005547 return INVALID_OPERATION;
5548 }
5549
Eric Laurentc75307b2015-03-17 15:29:32 -07005550 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005551 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005552 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005553
Eric Laurentffbc80f2015-03-18 18:30:19 -07005554 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005555 if (outputDesc->isFixedVolume(device) ||
5556 // Force VoIP volume to max for bluetooth SCO
5557 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5558 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005559 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005560 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005561
Eric Laurentffbc80f2015-03-18 18:30:19 -07005562 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005563
Eric Laurent3b73df72014-03-11 09:06:29 -07005564 if (stream == AUDIO_STREAM_VOICE_CALL ||
5565 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005566 float voiceVolume;
5567 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005568 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005569 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005570 } else {
5571 voiceVolume = 1.0;
5572 }
5573
Eric Laurent18fba842016-03-31 14:41:26 -07005574 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005575 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5576 mLastVoiceVolume = voiceVolume;
5577 }
5578 }
5579
5580 return NO_ERROR;
5581}
5582
Eric Laurentc75307b2015-03-17 15:29:32 -07005583void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5584 audio_devices_t device,
5585 int delayMs,
5586 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005587{
Eric Laurentc75307b2015-03-17 15:29:32 -07005588 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005589
Eric Laurent794fde22016-03-11 09:50:45 -08005590 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005591 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005592 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005593 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005594 device,
5595 delayMs,
5596 force);
5597 }
5598}
5599
Eric Laurente0720872014-03-11 09:30:41 -07005600void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005601 bool on,
5602 const sp<AudioOutputDescriptor>& outputDesc,
5603 int delayMs,
5604 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005605{
Eric Laurent72249d52015-06-08 11:12:15 -07005606 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5607 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005608 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005609 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005610 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005611 }
5612 }
5613}
5614
Eric Laurente0720872014-03-11 09:30:41 -07005615void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005616 bool on,
5617 const sp<AudioOutputDescriptor>& outputDesc,
5618 int delayMs,
5619 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005620{
Eric Laurente552edb2014-03-10 17:42:56 -07005621 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005622 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005623 }
5624
Eric Laurentc75307b2015-03-17 15:29:32 -07005625 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5626 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005627
5628 if (on) {
5629 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005630 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005631 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005632 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005633 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005634 }
5635 }
5636 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5637 outputDesc->mMuteCount[stream]++;
5638 } else {
5639 if (outputDesc->mMuteCount[stream] == 0) {
5640 ALOGV("setStreamMute() unmuting non muted stream!");
5641 return;
5642 }
5643 if (--outputDesc->mMuteCount[stream] == 0) {
5644 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005645 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005646 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005647 device,
5648 delayMs);
5649 }
5650 }
5651}
5652
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005653audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5654{
5655 // flags to stream type mapping
5656 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5657 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5658 }
5659 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5660 return AUDIO_STREAM_BLUETOOTH_SCO;
5661 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005662 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5663 return AUDIO_STREAM_TTS;
5664 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005665
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005666 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005667}
Eric Laurente83b55d2014-11-14 10:06:21 -08005668
François Gaffie53615e22015-03-19 09:24:12 +01005669bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5670{
Eric Laurente83b55d2014-11-14 10:06:21 -08005671 // has flags that map to a strategy?
5672 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5673 return true;
5674 }
5675
5676 // has known usage?
5677 switch (paa->usage) {
5678 case AUDIO_USAGE_UNKNOWN:
5679 case AUDIO_USAGE_MEDIA:
5680 case AUDIO_USAGE_VOICE_COMMUNICATION:
5681 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5682 case AUDIO_USAGE_ALARM:
5683 case AUDIO_USAGE_NOTIFICATION:
5684 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5685 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5686 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5687 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5688 case AUDIO_USAGE_NOTIFICATION_EVENT:
5689 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5690 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5691 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5692 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005693 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005694 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005695 break;
5696 default:
5697 return false;
5698 }
5699 return true;
5700}
5701
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005702bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005703 routing_strategy strategy, uint32_t inPastMs,
5704 nsecs_t sysTime) const
5705{
5706 if ((sysTime == 0) && (inPastMs != 0)) {
5707 sysTime = systemTime();
5708 }
Eric Laurent794fde22016-03-11 09:50:45 -08005709 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005710 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005711 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005712 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5713 return true;
5714 }
5715 }
5716 return false;
5717}
5718
François Gaffie11d30102018-11-02 16:09:09 +01005719bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<SwAudioOutputDescriptor>& outputDesc,
5720 routing_strategy strategy, uint32_t inPastMs,
5721 nsecs_t sysTime) const
Eric Laurent484e9272018-06-07 17:29:23 -07005722{
5723 for (size_t i = 0; i < mOutputs.size(); i++) {
5724 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5725 if (outputDesc->sharesHwModuleWith(desc)
5726 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5727 return true;
5728 }
5729 }
5730 return false;
5731}
5732
François Gaffie2110e042015-03-24 08:41:51 +01005733audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5734{
5735 return mEngine->getForceUse(usage);
5736}
5737
5738bool AudioPolicyManager::isInCall()
5739{
5740 return isStateInCall(mEngine->getPhoneState());
5741}
5742
5743bool AudioPolicyManager::isStateInCall(int state)
5744{
5745 return is_state_in_call(state);
5746}
5747
Eric Laurentd60560a2015-04-10 11:31:20 -07005748void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5749{
5750 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005751 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5752 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5753 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5754 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005755 }
5756 }
5757
5758 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5759 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5760 bool release = false;
5761 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5762 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5763 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5764 source->ext.device.type == deviceDesc->type()) {
5765 release = true;
5766 }
5767 }
5768 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5769 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5770 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5771 sink->ext.device.type == deviceDesc->type()) {
5772 release = true;
5773 }
5774 }
5775 if (release) {
5776 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5777 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5778 }
5779 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005780
5781 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005782}
5783
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005784void AudioPolicyManager::modifySurroundFormats(
5785 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005786 std::unordered_set<audio_format_t> enforcedSurround(
5787 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005788 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5789 for (const auto& pair : mConfig.getSurroundFormats()) {
5790 allSurround.insert(pair.first);
5791 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5792 }
Phil Burk09bc4612016-02-24 15:58:15 -08005793
5794 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5795 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005796 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005797 // This is the resulting set of formats depending on the surround mode:
5798 // 'all surround' = allSurround
5799 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5800 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5801 // 'manual surround' = mManualSurroundFormats
5802 // AUTO: formats v 'enforced surround'
5803 // ALWAYS: formats v 'all surround' v 'enforced surround'
5804 // NEVER: formats ^ 'non-surround'
5805 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005806
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005807 std::unordered_set<audio_format_t> formatSet;
5808 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5809 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005810 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005811 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005812 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005813 formatSet.insert(*formatIter);
5814 }
5815 }
5816 } else {
5817 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5818 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005819 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005820
jiabin81772902018-04-02 17:52:27 -07005821 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005822 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005823 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5824 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5825 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005826 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005827 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5828 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5829 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005830 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005831 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005832 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005833 for (const auto& format : formatSet) {
5834 formatsPtr->push(format);
5835 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005836}
5837
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005838void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005839 ChannelsVector &channelMasks = *channelMasksPtr;
5840 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5841 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5842
5843 // If NEVER, then remove support for channelMasks > stereo.
5844 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5845 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5846 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5847 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5848 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5849 channelMasks.removeAt(maskIndex);
5850 } else {
5851 maskIndex++;
5852 }
5853 }
jiabin81772902018-04-02 17:52:27 -07005854 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5855 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5856 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005857 bool supports5dot1 = false;
5858 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005859 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005860 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5861 supports5dot1 = true;
5862 break;
5863 }
5864 }
5865 // If not then add 5.1 support.
5866 if (!supports5dot1) {
5867 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005868 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005869 }
Phil Burk09bc4612016-02-24 15:58:15 -08005870 }
5871}
5872
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005873void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005874 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005875 AudioProfileVector &profiles)
5876{
5877 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005878 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005879
François Gaffie112b0af2015-11-19 16:13:25 +01005880 // Format MUST be checked first to update the list of AudioProfile
5881 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005882 reply = mpClientInterface->getParameters(
5883 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005884 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005885 AudioParameter repliedParameters(reply);
5886 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005887 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005888 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5889 return;
5890 }
Phil Burk09bc4612016-02-24 15:58:15 -08005891 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005892 if (device == AUDIO_DEVICE_OUT_HDMI
5893 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005894 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005895 }
Phil Burk09bc4612016-02-24 15:58:15 -08005896 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005897 }
François Gaffie112b0af2015-11-19 16:13:25 +01005898
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005899 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005900 ChannelsVector channelMasks;
5901 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005902 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005903 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005904
5905 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005906 reply = mpClientInterface->getParameters(
5907 ioHandle,
5908 requestedParameters.toString() + ";" +
5909 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005910 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005911 AudioParameter repliedParameters(reply);
5912 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005913 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005914 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005915 }
5916 }
5917 if (profiles.hasDynamicChannelsFor(format)) {
5918 reply = mpClientInterface->getParameters(ioHandle,
5919 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005920 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005921 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005922 AudioParameter repliedParameters(reply);
5923 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005924 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005925 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005926 if (device == AUDIO_DEVICE_OUT_HDMI
5927 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005928 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07005929 }
François Gaffie112b0af2015-11-19 16:13:25 +01005930 }
5931 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005932 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005933 }
5934}
Eric Laurentd60560a2015-04-10 11:31:20 -07005935
Mikhail Naganovdc769682018-05-04 15:34:08 -07005936status_t AudioPolicyManager::installPatch(const char *caller,
5937 audio_patch_handle_t *patchHandle,
5938 AudioIODescriptorInterface *ioDescriptor,
5939 const struct audio_patch *patch,
5940 int delayMs)
5941{
5942 ssize_t index = mAudioPatches.indexOfKey(
5943 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5944 *patchHandle : ioDescriptor->getPatchHandle());
5945 sp<AudioPatch> patchDesc;
5946 status_t status = installPatch(
5947 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5948 if (status == NO_ERROR) {
5949 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5950 }
5951 return status;
5952}
5953
5954status_t AudioPolicyManager::installPatch(const char *caller,
5955 ssize_t index,
5956 audio_patch_handle_t *patchHandle,
5957 const struct audio_patch *patch,
5958 int delayMs,
5959 uid_t uid,
5960 sp<AudioPatch> *patchDescPtr)
5961{
5962 sp<AudioPatch> patchDesc;
5963 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5964 if (index >= 0) {
5965 patchDesc = mAudioPatches.valueAt(index);
5966 afPatchHandle = patchDesc->mAfPatchHandle;
5967 }
5968
5969 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
5970 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
5971 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
5972 if (status == NO_ERROR) {
5973 if (index < 0) {
5974 patchDesc = new AudioPatch(patch, uid);
5975 addAudioPatch(patchDesc->mHandle, patchDesc);
5976 } else {
5977 patchDesc->mPatch = *patch;
5978 }
5979 patchDesc->mAfPatchHandle = afPatchHandle;
5980 if (patchHandle) {
5981 *patchHandle = patchDesc->mHandle;
5982 }
5983 nextAudioPortGeneration();
5984 mpClientInterface->onAudioPatchListUpdate();
5985 }
5986 if (patchDescPtr) *patchDescPtr = patchDesc;
5987 return status;
5988}
5989
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08005990} // namespace android