blob: 5e5ea1120b39a065508801910e2b4b35d47e057d [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/time.h>
28#include <sys/resource.h>
29
jiabin57303cc2018-12-18 15:45:57 -080030#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080031#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IServiceManager.h>
33#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070034#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070036#include <media/audiohal/DeviceHalInterface.h>
37#include <media/audiohal/DevicesFactoryHalInterface.h>
38#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070039#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070041#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <utils/String16.h>
43#include <utils/threads.h>
44
Steven Morelandf0c02ce2018-02-23 14:53:55 -080045#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/properties.h>
47
Dima Zavin64760242011-05-11 14:15:23 -070048#include <system/audio.h>
Mikhail Naganov2996f672019-04-18 12:29:59 -070049#include <audiomanager/AudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070052#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
Andy Hung6770c6f2015-04-07 13:43:36 -070054#include <media/AudioResamplerPublic.h>
55
Mikhail Naganov9fe94012016-10-14 14:57:40 -070056#include <system/audio_effects/effect_visualizer.h>
57#include <system/audio_effects/effect_ns.h>
58#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Glenn Kasten3b21c502011-12-15 09:52:39 -080060#include <audio_utils/primitives.h>
61
Eric Laurentfeb0db62011-07-22 09:04:31 -070062#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080063
Glenn Kasten9e58b552013-01-18 15:09:48 -080064#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070065#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080066#include <media/nbaio/Pipe.h>
67#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080068#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070069#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070070#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080071
rago3bd1c872016-09-26 12:58:14 -070072//#define BUFLOG_NDEBUG 0
73#include <BufLog.h>
74
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080075#include "TypedLogger.h"
76
Mathias Agopian65ab4712010-07-14 17:59:35 -070077// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
John Grossman1c345192012-03-27 14:00:17 -070079// Note: the following macro is used for extremely verbose logging message. In
80// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
81// 0; but one side effect of this is to turn all LOGV's as well. Some messages
82// are so verbose that we want to suppress them even when we have ALOG_ASSERT
83// turned on. Do not uncomment the #def below unless you really know what you
84// are doing and want to see all of the extremely verbose messages.
85//#define VERY_VERY_VERBOSE_LOGGING
86#ifdef VERY_VERY_VERBOSE_LOGGING
87#define ALOGVV ALOGV
88#else
89#define ALOGVV(a...) do { } while(0)
90#endif
Eric Laurentde070132010-07-13 04:45:46 -070091
Mathias Agopian65ab4712010-07-14 17:59:35 -070092namespace android {
93
Glenn Kastenec1d6b52011-12-12 09:04:45 -080094static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
95static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070096static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070097static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070098
Glenn Kasten58912562012-04-03 10:45:00 -070099
John Grossman4ff14ba2012-02-08 16:37:41 -0800100nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800101
Eric Laurent81784c32012-11-19 14:55:58 -0800102uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700103
Eric Laurent813e2a72013-08-31 12:59:48 -0700104// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
105// we define a minimum time during which a global effect is considered enabled.
106static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
107
Eric Laurentfc235202016-12-20 18:48:17 -0800108Mutex gLock;
109wp<AudioFlinger> gAudioFlinger;
110
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700111// Keep a strong reference to media.log service around forever.
112// The service is within our parent process so it can never die in a way that we could observe.
113// These two variables are const after initialization.
114static sp<IBinder> sMediaLogServiceAsBinder;
115static sp<IMediaLogService> sMediaLogService;
116
117static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
118
119static void sMediaLogInit()
120{
121 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
122 if (sMediaLogServiceAsBinder != 0) {
123 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
124 }
125}
126
jiabin57303cc2018-12-18 15:45:57 -0800127// Keep a strong reference to external vibrator service
128static sp<os::IExternalVibratorService> sExternalVibratorService;
129
130static sp<os::IExternalVibratorService> getExternalVibratorService() {
131 if (sExternalVibratorService == 0) {
132 sp <IBinder> binder = defaultServiceManager()->getService(
133 String16("external_vibrator_service"));
134 if (binder != 0) {
135 sExternalVibratorService =
136 interface_cast<os::IExternalVibratorService>(binder);
137 }
138 }
139 return sExternalVibratorService;
140}
141
Mathias Agopian65ab4712010-07-14 17:59:35 -0700142// ----------------------------------------------------------------------------
143
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700144std::string formatToString(audio_format_t format) {
145 std::string result;
146 FormatConverter::toString(format, result);
147 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800148}
149
Mathias Agopian65ab4712010-07-14 17:59:35 -0700150// ----------------------------------------------------------------------------
151
152AudioFlinger::AudioFlinger()
153 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800154 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800155 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800156 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700157 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800158 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800159 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700160 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800161 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700162 mBtNrecIsOff(false),
163 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700164 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800165 mTotalMemory(0),
166 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700167 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700168 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700169 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700171 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
172 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
173 // zero ID has a special meaning, so unavailable
174 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
175 }
176
Glenn Kastenae0cff12016-02-24 13:57:49 -0800177 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800178 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800179 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
180 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700181 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800182 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700183
Wei Jia3f273d12015-11-24 09:06:49 -0800184 // reset battery stats.
185 // if the audio service has crashed, battery stats could be left
186 // in bad state, reset the state upon service start.
187 BatteryNotifier::getInstance().noteResetAudio();
188
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700189 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700190 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
191
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800192 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700193}
194
195void AudioFlinger::onFirstRef()
196{
Eric Laurent93575202011-01-18 18:39:02 -0800197 Mutex::Autolock _l(mLock);
198
Dima Zavin799a70e2011-04-18 16:57:27 -0700199 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800200 char val_str[PROPERTY_VALUE_MAX] = { 0 };
201 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
202 uint32_t int_val;
203 if (1 == sscanf(val_str, "%u", &int_val)) {
204 mStandbyTimeInNsecs = milliseconds(int_val);
205 ALOGI("Using %u mSec as standby time.", int_val);
206 } else {
207 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
208 ALOGI("Using default %u mSec as standby time.",
209 (uint32_t)(mStandbyTimeInNsecs / 1000000));
210 }
211 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212
Eric Laurenta4c5a552012-03-29 10:12:40 -0700213 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800214
215 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700216}
217
218AudioFlinger::~AudioFlinger()
219{
220 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700221 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700222 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223 }
224 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700225 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700226 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700227 }
Andy Hungb4946b62019-03-14 11:19:28 -0700228 while (!mMmapThreads.isEmpty()) {
229 const audio_io_handle_t io = mMmapThreads.keyAt(0);
230 if (mMmapThreads.valueAt(0)->isOutput()) {
231 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
232 } else {
233 closeInput_nonvirtual(io); // removes entry from mMmapThreads
234 }
235 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700236
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800237 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
238 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700239 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700240 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700241
242 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700243 if (sMediaLogService != 0) {
244 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
245 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
246 mUnregisteredWriters.pop();
247 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700248 }
249 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700250}
251
Eric Laurentfc235202016-12-20 18:48:17 -0800252//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800253__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800254status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
255 const audio_attributes_t *attr,
256 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700257 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800258 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800259 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800260 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700261 sp<MmapStreamInterface>& interface,
262 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800263{
264 sp<AudioFlinger> af;
265 {
266 Mutex::Autolock _l(gLock);
267 af = gAudioFlinger.promote();
268 }
269 status_t ret = NO_INIT;
270 if (af != 0) {
271 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800272 direction, attr, config, client, deviceId,
273 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800274 }
275 return ret;
276}
277
Eric Laurent6acd1d42017-01-04 14:23:29 -0800278status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
279 const audio_attributes_t *attr,
280 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700281 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800282 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800283 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800284 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700285 sp<MmapStreamInterface>& interface,
286 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800287{
288 status_t ret = initCheck();
289 if (ret != NO_ERROR) {
290 return ret;
291 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800292 audio_session_t actualSessionId = *sessionId;
293 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
294 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
295 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800296 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700297 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800298 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
299 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
300 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
301 fullConfig.sample_rate = config->sample_rate;
302 fullConfig.channel_mask = config->channel_mask;
303 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800304 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800305 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800306 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200307 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800308 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800309 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
310 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800311 deviceId, &portId, &secondaryOutputs);
312 ALOGW_IF(!secondaryOutputs.empty(),
313 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800314 } else {
315 ret = AudioSystem::getInputForAttr(attr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700316 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800317 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800318 client.clientPid,
319 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800320 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800321 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700322 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800323 }
324 if (ret != NO_ERROR) {
325 return ret;
326 }
327
328 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
329 // audio policy manager and we can retrieve it
330 sp<MmapThread> thread = mMmapThreads.valueFor(io);
331 if (thread != 0) {
332 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800333 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700334 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800335 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800336 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700337 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700338 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700339 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800340 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700341 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800342 ret = NO_INIT;
343 }
344
345 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
346
Eric Laurentfc235202016-12-20 18:48:17 -0800347 return ret;
348}
349
jiabin57303cc2018-12-18 15:45:57 -0800350/* static */
351int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
352 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
353 if (evs != 0) {
354 int32_t ret;
355 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
356 if (status.isOk()) {
357 return ret;
358 }
359 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800360 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800361}
362
363/* static */
364void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
365 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
366 if (evs != 0) {
367 evs->onExternalVibrationStop(*externalVibration);
368 }
369}
370
Eric Laurenta4c5a552012-03-29 10:12:40 -0700371static const char * const audio_interfaces[] = {
372 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
373 AUDIO_HARDWARE_MODULE_ID_A2DP,
374 AUDIO_HARDWARE_MODULE_ID_USB,
375};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700376
Phil Burk062e67a2015-02-11 13:40:50 -0800377AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700378 audio_module_handle_t module,
379 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700380{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700381 // if module is 0, the request comes from an old policy manager and we should load
382 // well known modules
383 if (module == 0) {
384 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700385 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700386 loadHwModule_l(audio_interfaces[i]);
387 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700388 // then try to find a module supporting the requested device.
389 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
390 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700391 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
392 uint32_t supportedDevices;
393 if (dev->getSupportedDevices(&supportedDevices) == OK &&
394 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700395 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700396 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700397 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700398 } else {
399 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700400 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
401 if (audioHwDevice != NULL) {
402 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700403 }
404 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700405
Dima Zavin799a70e2011-04-18 16:57:27 -0700406 return NULL;
407}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408
Glenn Kasten0f11b512014-01-31 16:18:54 -0800409void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410{
411 const size_t SIZE = 256;
412 char buffer[SIZE];
413 String8 result;
414
415 result.append("Clients:\n");
416 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800417 sp<Client> client = mClients.valueAt(i).promote();
418 if (client != 0) {
419 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
420 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421 }
422 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700423
Eric Laurentd1b28d42013-09-18 18:47:13 -0700424 result.append("Notification Clients:\n");
425 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
426 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
427 result.append(buffer);
428 }
429
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700430 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800431 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700432 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
433 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800434 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700435 result.append(buffer);
436 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438}
439
440
Glenn Kasten0f11b512014-01-31 16:18:54 -0800441void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442{
443 const size_t SIZE = 256;
444 char buffer[SIZE];
445 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800446 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447
John Grossman4ff14ba2012-02-08 16:37:41 -0800448 snprintf(buffer, SIZE, "Hardware status: %d\n"
449 "Standby Time mSec: %u\n",
450 hardwareStatus,
451 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 result.append(buffer);
453 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454}
455
Glenn Kasten0f11b512014-01-31 16:18:54 -0800456void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457{
458 const size_t SIZE = 256;
459 char buffer[SIZE];
460 String8 result;
461 snprintf(buffer, SIZE, "Permission Denial: "
462 "can't dump AudioFlinger from pid=%d, uid=%d\n",
463 IPCThreadState::self()->getCallingPid(),
464 IPCThreadState::self()->getCallingUid());
465 result.append(buffer);
466 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467}
468
Eric Laurent81784c32012-11-19 14:55:58 -0800469bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700470{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700471 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
472 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700473}
474
475status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
476{
Glenn Kasten44deb052012-02-05 18:09:08 -0800477 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700478 dumpPermissionDenial(fd, args);
479 } else {
480 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800481 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700482 if (!hardwareLocked) {
483 String8 result(kHardwareLockedString);
484 write(fd, result.string(), result.size());
485 } else {
486 mHardwareLock.unlock();
487 }
488
Eric Tan7b651152018-07-13 10:17:19 -0700489 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700490
491 // failed to lock - AudioFlinger is probably deadlocked
492 if (!locked) {
493 String8 result(kDeadlockedString);
494 write(fd, result.string(), result.size());
495 }
496
Eric Laurent021cf962014-05-13 10:18:14 -0700497 bool clientLocked = dumpTryLock(mClientLock);
498 if (!clientLocked) {
499 String8 result(kClientLockedString);
500 write(fd, result.string(), result.size());
501 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700502
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700503 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700504 mEffectsFactoryHal->dumpEffects(fd);
505 } else {
506 String8 result(kNoEffectsFactory);
507 write(fd, result.string(), result.size());
508 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700509
Mathias Agopian65ab4712010-07-14 17:59:35 -0700510 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700511 if (clientLocked) {
512 mClientLock.unlock();
513 }
514
Mathias Agopian65ab4712010-07-14 17:59:35 -0700515 dumpInternals(fd, args);
516
517 // dump playback threads
518 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
519 mPlaybackThreads.valueAt(i)->dump(fd, args);
520 }
521
522 // dump record threads
523 for (size_t i = 0; i < mRecordThreads.size(); i++) {
524 mRecordThreads.valueAt(i)->dump(fd, args);
525 }
526
Eric Laurent6acd1d42017-01-04 14:23:29 -0800527 // dump mmap threads
528 for (size_t i = 0; i < mMmapThreads.size(); i++) {
529 mMmapThreads.valueAt(i)->dump(fd, args);
530 }
531
Eric Laurentaaa44472014-09-12 17:41:50 -0700532 // dump orphan effect chains
533 if (mOrphanEffectChains.size() != 0) {
534 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
535 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
536 mOrphanEffectChains.valueAt(i)->dump(fd, args);
537 }
538 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700539 // dump all hardware devs
540 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700541 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
542 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700543 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700544
Mikhail Naganov201369b2018-05-16 16:52:32 -0700545 mPatchPanel.dump(fd);
546
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700547 // dump external setParameters
548 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
549 dprintf(fd, "\n%s setParameters:\n", name);
550 logger.dump(fd, " " /* prefix */);
551 };
552 dumpLogger(mRejectedSetParameterLog, "Rejected");
553 dumpLogger(mAppSetParameterLog, "App");
554 dumpLogger(mSystemSetParameterLog, "System");
555
Andy Hunga8115dc2018-08-24 15:51:59 -0700556 // dump historical threads in the last 10 seconds
557 const std::string threadLog = mThreadLog.dumpToString(
558 "Historical Thread Log ", 0 /* lines */,
559 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
560 write(fd, threadLog.c_str(), threadLog.size());
561
rago3bd1c872016-09-26 12:58:14 -0700562 BUFLOG_RESET;
563
Glenn Kastend65d73c2012-06-22 17:21:07 -0700564 if (locked) {
565 mLock.unlock();
566 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800567
Andy Hung8946a282018-04-19 20:04:56 -0700568#ifdef TEE_SINK
569 // NBAIO_Tee dump is safe to call outside of AF lock.
570 NBAIO_Tee::dumpAll(fd, "_DUMP");
571#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800572 // append a copy of media.log here by forwarding fd to it, but don't attempt
573 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700574 if (sMediaLogServiceAsBinder != 0) {
575 dprintf(fd, "\nmedia.log:\n");
576 Vector<String16> args;
577 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800578 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700579
580 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700581 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700582 bool unreachableMemory = false;
583 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700584 if (arg == String16("-m")) {
585 dumpMem = true;
586 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700587 unreachableMemory = true;
588 }
589 }
590
Andy Hung07b745e2016-05-23 16:21:07 -0700591 if (dumpMem) {
592 dprintf(fd, "\nDumping memory:\n");
593 std::string s = dumpMemoryAddresses(100 /* limit */);
594 write(fd, s.c_str(), s.size());
595 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700596 if (unreachableMemory) {
597 dprintf(fd, "\nDumping unreachable memory:\n");
598 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700599 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700600 write(fd, s.c_str(), s.size());
601 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602 }
603 return NO_ERROR;
604}
605
Eric Laurent021cf962014-05-13 10:18:14 -0700606sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800607{
Eric Laurent021cf962014-05-13 10:18:14 -0700608 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800609 // If pid is already in the mClients wp<> map, then use that entry
610 // (for which promote() is always != 0), otherwise create a new entry and Client.
611 sp<Client> client = mClients.valueFor(pid).promote();
612 if (client == 0) {
613 client = new Client(this, pid);
614 mClients.add(pid, client);
615 }
616
617 return client;
618}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700619
Glenn Kasten9e58b552013-01-18 15:09:48 -0800620sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
621{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700622 // If there is no memory allocated for logs, return a dummy writer that does nothing.
623 // Similarly if we can't contact the media.log service, also return a dummy writer.
624 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800625 return new NBLog::Writer();
626 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700627 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
628 // If allocation fails, consult the vector of previously unregistered writers
629 // and garbage-collect one or more them until an allocation succeeds
630 if (shared == 0) {
631 Mutex::Autolock _l(mUnregisteredWritersLock);
632 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
633 {
634 // Pick the oldest stale writer to garbage-collect
635 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
636 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700637 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700638 // Now the media.log remote reference to IMemory is gone. When our last local
639 // reference to IMemory also drops to zero at end of this block,
640 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
641 }
642 // Re-attempt the allocation
643 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
644 if (shared != 0) {
645 goto success;
646 }
647 }
648 // Even after garbage-collecting all old writers, there is still not enough memory,
649 // so return a dummy writer
650 return new NBLog::Writer();
651 }
652success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800653 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
654 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
655 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700656 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800657 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800658}
659
660void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
661{
Glenn Kasten685ef092013-02-04 08:15:34 -0800662 if (writer == 0) {
663 return;
664 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800665 sp<IMemory> iMemory(writer->getIMemory());
666 if (iMemory == 0) {
667 return;
668 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700669 // Rather than removing the writer immediately, append it to a queue of old writers to
670 // be garbage-collected later. This allows us to continue to view old logs for a while.
671 Mutex::Autolock _l(mUnregisteredWritersLock);
672 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800673}
674
Mathias Agopian65ab4712010-07-14 17:59:35 -0700675// IAudioFlinger interface
676
Eric Laurent21da6472017-11-09 16:29:26 -0800677sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
678 CreateTrackOutput& output,
679 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700680{
681 sp<PlaybackThread::Track> track;
682 sp<TrackHandle> trackHandle;
683 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700684 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800685 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800686 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800687 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688
Eric Laurent21da6472017-11-09 16:29:26 -0800689 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700690 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800691 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700692 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
693 std::vector<int> effectIds;
694
695
Andy Hung4ef19fa2018-05-15 19:35:29 -0700696 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800697 ALOGW_IF(clientUid != callingUid,
698 "%s uid %d tried to pass itself off as %d",
699 __FUNCTION__, callingUid, clientUid);
700 clientUid = callingUid;
701 updatePid = true;
702 }
703 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700704 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800705 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800706 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700707 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800708 __func__, callingUid, callingPid, clientPid);
709 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700710 }
711
Eric Laurent21da6472017-11-09 16:29:26 -0800712 audio_session_t sessionId = input.sessionId;
713 if (sessionId == AUDIO_SESSION_ALLOCATE) {
714 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800715 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
716 lStatus = BAD_VALUE;
717 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800718 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800719
Eric Laurent21da6472017-11-09 16:29:26 -0800720 output.sessionId = sessionId;
721 output.outputId = AUDIO_IO_HANDLE_NONE;
722 output.selectedDeviceId = input.selectedDeviceId;
723
724 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200725 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800726 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800727
728 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
729 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
730 goto Exit;
731 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800732 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
733 // but if someone uses binder directly they could bypass that and cause us to crash
734 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000735 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736 lStatus = BAD_VALUE;
737 goto Exit;
738 }
739
Glenn Kasten53b5d092014-02-05 10:00:23 -0800740 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800741 if (!audio_is_output_channel(input.config.channel_mask)) {
742 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800743 lStatus = BAD_VALUE;
744 goto Exit;
745 }
746
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700747 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800748 if (!audio_is_valid_format(input.config.format)) {
749 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700750 lStatus = BAD_VALUE;
751 goto Exit;
752 }
753
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754 {
755 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800756 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800758 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700759 lStatus = BAD_VALUE;
760 goto Exit;
761 }
762
Eric Laurent21da6472017-11-09 16:29:26 -0800763 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764
Glenn Kastene848bd92014-03-13 15:00:32 -0700765 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800766 // check if an effect chain with the same session ID is present on another
767 // output thread and move it here.
768 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
769 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
770 if (mPlaybackThreads.keyAt(i) != output.outputId) {
771 uint32_t sessions = t->hasAudioSession(sessionId);
772 if (sessions & ThreadBase::EFFECT_SESSION) {
773 effectThread = t.get();
774 break;
Eric Laurentde070132010-07-13 04:45:46 -0700775 }
776 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700777 }
Eric Laurent21da6472017-11-09 16:29:26 -0800778 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700779
Eric Laurent21da6472017-11-09 16:29:26 -0800780 output.sampleRate = input.config.sample_rate;
781 output.frameCount = input.frameCount;
782 output.notificationFrameCount = input.notificationFrameCount;
783 output.flags = input.flags;
784
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700785 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
786 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800787 &output.frameCount, &output.notificationFrameCount,
788 input.notificationsPerBuffer, input.speed,
789 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700790 callingPid, input.clientInfo.clientTid, clientUid,
791 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800792 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700793 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700794
Eric Laurent21da6472017-11-09 16:29:26 -0800795 output.afFrameCount = thread->frameCount();
796 output.afSampleRate = thread->sampleRate();
797 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800798 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800799
Kevin Rocard153f92d2018-12-18 18:33:28 -0800800 if (lStatus == NO_ERROR) {
801 // Connect secondary outputs. Failure on a secondary output must not imped the primary
802 // Any secondary output setup failure will lead to a desync between the AP and AF until
803 // the track is destroyed.
804 TeePatches teePatches;
805 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
806 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
807 if (secondaryThread == NULL) {
808 ALOGE("no playback thread found for secondary output %d", output.outputId);
809 continue;
810 }
811
812 size_t frameCount = std::lcm(thread->frameCount(), secondaryThread->frameCount());
813
814 using namespace std::chrono_literals;
815 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
816 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
817 output.sampleRate,
818 inChannelMask,
819 input.config.format,
820 frameCount,
821 NULL /* buffer */,
822 (size_t)0 /* bufferSize */,
823 AUDIO_INPUT_FLAG_DIRECT,
824 0ns /* timeout */);
825 status_t status = patchRecord->initCheck();
826 if (status != NO_ERROR) {
827 ALOGE("Secondary output patchRecord init failed: %d", status);
828 continue;
829 }
830 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
831 streamType,
832 output.sampleRate,
833 input.config.channel_mask,
834 input.config.format,
835 frameCount,
836 patchRecord->buffer(),
837 patchRecord->bufferSize(),
838 output.flags,
839 0ns /* timeout */);
840 status = patchTrack->initCheck();
841 if (status != NO_ERROR) {
842 ALOGE("Secondary output patchTrack init failed: %d", status);
843 continue;
844 }
845 teePatches.push_back({patchRecord, patchTrack});
846 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800847 // In case the downstream patchTrack on the secondaryThread temporarily outlives
848 // our created track, ensure the corresponding patchRecord is still alive.
849 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
850 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800851 }
852 track->setTeePatches(std::move(teePatches));
853 }
854
Eric Laurent39e94f82010-07-28 01:32:47 -0700855 // move effect chain to this output thread if an effect on same session was waiting
856 // for a track to be created
857 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700858 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700859 Mutex::Autolock _dl(thread->mLock);
860 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700861 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
862 effectThreadId = thread->id();
863 effectIds = thread->getEffectIds_l(sessionId);
864 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700865 }
Eric Laurenta011e352012-03-29 15:51:43 -0700866
867 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700868 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800869 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700870 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700871 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700872 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700873 } else {
874 mPendingSyncEvents[i]->cancel();
875 }
Eric Laurenta011e352012-03-29 15:51:43 -0700876 mPendingSyncEvents.removeAt(i);
877 i--;
878 }
879 }
880 }
Glenn Kastene198c362013-08-13 09:13:36 -0700881
Eric Laurent21da6472017-11-09 16:29:26 -0800882 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883 }
Glenn Kastene198c362013-08-13 09:13:36 -0700884
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700885 if (lStatus != NO_ERROR) {
886 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700887 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700888 // Don't hold mClientLock when releasing the reference on the track as the
889 // destructor will acquire it.
890 {
891 Mutex::Autolock _cl(mClientLock);
892 client.clear();
893 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700894 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700895 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896 }
897
Eric Laurent6c796322019-04-09 14:13:17 -0700898 // effectThreadId is not NONE if an effect chain corresponding to the track session
899 // was found on another thread and must be moved on this thread
900 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
901 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
902 }
903
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700904 // return handle to client
905 trackHandle = new TrackHandle(track);
906
Mathias Agopian65ab4712010-07-14 17:59:35 -0700907Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800908 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700909 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800910 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700911 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700912 return trackHandle;
913}
914
Glenn Kasten2c073da2016-02-26 09:14:08 -0800915uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916{
917 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800918 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800920 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 return 0;
922 }
923 return thread->sampleRate();
924}
925
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800926audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927{
928 Mutex::Autolock _l(mLock);
929 PlaybackThread *thread = checkPlaybackThread_l(output);
930 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000931 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800932 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700933 }
934 return thread->format();
935}
936
Glenn Kasten2c073da2016-02-26 09:14:08 -0800937size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938{
939 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800940 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700941 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800942 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700943 return 0;
944 }
Glenn Kasten58912562012-04-03 10:45:00 -0700945 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
946 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947 return thread->frameCount();
948}
949
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700950size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
951{
952 Mutex::Autolock _l(mLock);
953 ThreadBase *thread = checkThread_l(ioHandle);
954 if (thread == NULL) {
955 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
956 return 0;
957 }
958 return thread->frameCountHAL();
959}
960
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800961uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700962{
963 Mutex::Autolock _l(mLock);
964 PlaybackThread *thread = checkPlaybackThread_l(output);
965 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800966 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967 return 0;
968 }
969 return thread->latency();
970}
971
972status_t AudioFlinger::setMasterVolume(float value)
973{
Eric Laurenta1884f92011-08-23 08:25:03 -0700974 status_t ret = initCheck();
975 if (ret != NO_ERROR) {
976 return ret;
977 }
978
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979 // check calling permissions
980 if (!settingsAllowed()) {
981 return PERMISSION_DENIED;
982 }
983
Eric Laurenta4c5a552012-03-29 10:12:40 -0700984 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700985 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700986
John Grossmanee578c02012-07-23 17:05:46 -0700987 // Set master volume in the HALs which support it.
988 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
989 AutoMutex lock(mHardwareLock);
990 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800991
John Grossmanee578c02012-07-23 17:05:46 -0700992 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
993 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700994 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800995 }
John Grossmanee578c02012-07-23 17:05:46 -0700996 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700998
John Grossmanee578c02012-07-23 17:05:46 -0700999 // Now set the master volume in each playback thread. Playback threads
1000 // assigned to HALs which do not have master volume support will apply
1001 // master volume during the mix operation. Threads with HALs which do
1002 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001003 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1004 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1005 continue;
1006 }
John Grossmanee578c02012-07-23 17:05:46 -07001007 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001008 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009
1010 return NO_ERROR;
1011}
1012
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001013status_t AudioFlinger::setMasterBalance(float balance)
1014{
1015 status_t ret = initCheck();
1016 if (ret != NO_ERROR) {
1017 return ret;
1018 }
1019
1020 // check calling permissions
1021 if (!settingsAllowed()) {
1022 return PERMISSION_DENIED;
1023 }
1024
1025 // check range
1026 if (isnan(balance) || fabs(balance) > 1.f) {
1027 return BAD_VALUE;
1028 }
1029
1030 Mutex::Autolock _l(mLock);
1031
1032 // short cut.
1033 if (mMasterBalance == balance) return NO_ERROR;
1034
1035 mMasterBalance = balance;
1036
1037 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1038 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1039 continue;
1040 }
1041 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1042 }
1043
1044 return NO_ERROR;
1045}
1046
Glenn Kastenf78aee72012-01-04 11:00:47 -08001047status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048{
Eric Laurenta1884f92011-08-23 08:25:03 -07001049 status_t ret = initCheck();
1050 if (ret != NO_ERROR) {
1051 return ret;
1052 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001053
1054 // check calling permissions
1055 if (!settingsAllowed()) {
1056 return PERMISSION_DENIED;
1057 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001058 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001059 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060 return BAD_VALUE;
1061 }
1062
1063 { // scope for the lock
1064 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001065 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001066 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001067 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068 mHardwareStatus = AUDIO_HW_IDLE;
1069 }
1070
1071 if (NO_ERROR == ret) {
1072 Mutex::Autolock _l(mLock);
1073 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001074 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001075 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 }
1077
1078 return ret;
1079}
1080
1081status_t AudioFlinger::setMicMute(bool state)
1082{
Eric Laurenta1884f92011-08-23 08:25:03 -07001083 status_t ret = initCheck();
1084 if (ret != NO_ERROR) {
1085 return ret;
1086 }
1087
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088 // check calling permissions
1089 if (!settingsAllowed()) {
1090 return PERMISSION_DENIED;
1091 }
1092
1093 AutoMutex lock(mHardwareLock);
1094 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001095 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001096 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1097 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001098 if (result != NO_ERROR) {
1099 ret = result;
1100 }
1101 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102 mHardwareStatus = AUDIO_HW_IDLE;
1103 return ret;
1104}
1105
1106bool AudioFlinger::getMicMute() const
1107{
Eric Laurenta1884f92011-08-23 08:25:03 -07001108 status_t ret = initCheck();
1109 if (ret != NO_ERROR) {
1110 return false;
1111 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001112 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001113 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001114 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001116 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001117 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1118 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001119 if (result == NO_ERROR) {
1120 mute = mute && state;
1121 }
1122 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001124
1125 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126}
1127
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001128void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1129{
1130 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1131
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001132 AutoMutex lock(mLock);
1133 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001134 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1135 }
1136 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1137 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001138 }
1139}
1140
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141status_t AudioFlinger::setMasterMute(bool muted)
1142{
John Grossmand8f178d2012-07-20 14:51:35 -07001143 status_t ret = initCheck();
1144 if (ret != NO_ERROR) {
1145 return ret;
1146 }
1147
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148 // check calling permissions
1149 if (!settingsAllowed()) {
1150 return PERMISSION_DENIED;
1151 }
1152
John Grossmanee578c02012-07-23 17:05:46 -07001153 Mutex::Autolock _l(mLock);
1154 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001155
John Grossmanee578c02012-07-23 17:05:46 -07001156 // Set master mute in the HALs which support it.
1157 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1158 AutoMutex lock(mHardwareLock);
1159 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001160
John Grossmanee578c02012-07-23 17:05:46 -07001161 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1162 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001163 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001164 }
John Grossmanee578c02012-07-23 17:05:46 -07001165 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001166 }
1167
John Grossmanee578c02012-07-23 17:05:46 -07001168 // Now set the master mute in each playback thread. Playback threads
1169 // assigned to HALs which do not have master mute support will apply master
1170 // mute during the mix operation. Threads with HALs which do support master
1171 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001172 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1173 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1174 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001175 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176
1177 return NO_ERROR;
1178}
1179
1180float AudioFlinger::masterVolume() const
1181{
Glenn Kasten98067102011-12-13 11:47:54 -08001182 Mutex::Autolock _l(mLock);
1183 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184}
1185
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001186status_t AudioFlinger::getMasterBalance(float *balance) const
1187{
1188 Mutex::Autolock _l(mLock);
1189 *balance = getMasterBalance_l();
1190 return NO_ERROR; // if called through binder, may return a transactional error
1191}
1192
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193bool AudioFlinger::masterMute() const
1194{
Glenn Kasten98067102011-12-13 11:47:54 -08001195 Mutex::Autolock _l(mLock);
1196 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001197}
1198
John Grossman4ff14ba2012-02-08 16:37:41 -08001199float AudioFlinger::masterVolume_l() const
1200{
John Grossman4ff14ba2012-02-08 16:37:41 -08001201 return mMasterVolume;
1202}
1203
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001204float AudioFlinger::getMasterBalance_l() const
1205{
1206 return mMasterBalance;
1207}
1208
John Grossmand8f178d2012-07-20 14:51:35 -07001209bool AudioFlinger::masterMute_l() const
1210{
John Grossmanee578c02012-07-23 17:05:46 -07001211 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001212}
1213
Eric Laurent223fd5c2014-11-11 13:43:36 -08001214status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1215{
1216 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001217 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001218 return BAD_VALUE;
1219 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001220 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1221 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1222 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001223 return PERMISSION_DENIED;
1224 }
1225
1226 return NO_ERROR;
1227}
1228
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001229status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1230 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231{
1232 // check calling permissions
1233 if (!settingsAllowed()) {
1234 return PERMISSION_DENIED;
1235 }
1236
Eric Laurent223fd5c2014-11-11 13:43:36 -08001237 status_t status = checkStreamType(stream);
1238 if (status != NO_ERROR) {
1239 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240 }
Eric Laurent98e38192018-02-15 18:31:53 -08001241 if (output == AUDIO_IO_HANDLE_NONE) {
1242 return BAD_VALUE;
1243 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001244 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1245 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001246
1247 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001248 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1249 if (volumeInterface == NULL) {
1250 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001251 }
Eric Laurent98e38192018-02-15 18:31:53 -08001252 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253
1254 return NO_ERROR;
1255}
1256
Glenn Kastenfff6d712012-01-12 16:38:12 -08001257status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001258{
1259 // check calling permissions
1260 if (!settingsAllowed()) {
1261 return PERMISSION_DENIED;
1262 }
1263
Eric Laurent223fd5c2014-11-11 13:43:36 -08001264 status_t status = checkStreamType(stream);
1265 if (status != NO_ERROR) {
1266 return status;
1267 }
1268 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1269
1270 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001271 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001272 return BAD_VALUE;
1273 }
1274
Eric Laurent93575202011-01-18 18:39:02 -08001275 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001277 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1278 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1279 volumeInterfaces[i]->setStreamMute(stream, muted);
1280 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001281
1282 return NO_ERROR;
1283}
1284
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001285float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001287 status_t status = checkStreamType(stream);
1288 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001289 return 0.0f;
1290 }
Eric Laurent98e38192018-02-15 18:31:53 -08001291 if (output == AUDIO_IO_HANDLE_NONE) {
1292 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001293 }
1294
Eric Laurent98e38192018-02-15 18:31:53 -08001295 AutoMutex lock(mLock);
1296 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1297 if (volumeInterface == NULL) {
1298 return 0.0f;
1299 }
1300
1301 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001302}
1303
Glenn Kastenfff6d712012-01-12 16:38:12 -08001304bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001305{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001306 status_t status = checkStreamType(stream);
1307 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001308 return true;
1309 }
1310
Glenn Kasten6637baa2012-01-09 09:40:36 -08001311 AutoMutex lock(mLock);
1312 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001313}
1314
Eric Laurent054d9d32015-04-24 08:48:48 -07001315
1316void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1317{
1318 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1319 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1320 }
1321}
1322
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001323// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1324void AudioFlinger::forwardParametersToDownstreamPatches_l(
1325 audio_io_handle_t upStream, const String8& keyValuePairs,
1326 std::function<bool(const sp<PlaybackThread>&)> useThread)
1327{
1328 std::vector<PatchPanel::SoftwarePatch> swPatches;
1329 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1330 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1331 __func__, swPatches.size(), upStream);
1332 for (const auto& swPatch : swPatches) {
1333 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1334 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1335 downStream->setParameters(keyValuePairs);
1336 }
1337 }
1338}
1339
Eric Laurentf1047e82018-04-16 19:18:20 -07001340// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1341// Some keys are used for audio routing and audio path configuration and should be reserved for use
1342// by audio policy and audio flinger for functional, privacy and security reasons.
1343void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1344{
1345 static const String8 kReservedParameters[] = {
1346 String8(AudioParameter::keyRouting),
1347 String8(AudioParameter::keySamplingRate),
1348 String8(AudioParameter::keyFormat),
1349 String8(AudioParameter::keyChannels),
1350 String8(AudioParameter::keyFrameCount),
1351 String8(AudioParameter::keyInputSource),
1352 String8(AudioParameter::keyMonoOutput),
1353 String8(AudioParameter::keyStreamConnect),
1354 String8(AudioParameter::keyStreamDisconnect),
1355 String8(AudioParameter::keyStreamSupportedFormats),
1356 String8(AudioParameter::keyStreamSupportedChannels),
1357 String8(AudioParameter::keyStreamSupportedSamplingRates),
1358 };
1359
Andy Hung4ef19fa2018-05-15 19:35:29 -07001360 if (isAudioServerUid(callingUid)) {
1361 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001362 }
1363
1364 AudioParameter param = AudioParameter(keyValuePairs);
1365 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001366 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001367 for (auto& key : kReservedParameters) {
1368 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001369 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001370 param.remove(key);
1371 }
1372 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001373 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1374 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001375 keyValuePairs = param.toString();
1376}
1377
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001378void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1379 size_t rejectedKVPSize, const String8& rejectedKVPs,
1380 uid_t callingUid) {
1381 auto prefix = String8::format("UID %5d", callingUid);
1382 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1383 if (rejectedKVPSize != 0) {
1384 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1385 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1386 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1387 } else {
1388 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1389 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1390 }
1391}
1392
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001393status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001394{
Eric Laurentf1047e82018-04-16 19:18:20 -07001395 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1396 ioHandle, keyValuePairs.string(),
1397 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001398
Mathias Agopian65ab4712010-07-14 17:59:35 -07001399 // check calling permissions
1400 if (!settingsAllowed()) {
1401 return PERMISSION_DENIED;
1402 }
1403
Eric Laurentf1047e82018-04-16 19:18:20 -07001404 String8 filteredKeyValuePairs = keyValuePairs;
1405 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1406
1407 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1408
Glenn Kasten142f5192014-03-25 17:44:59 -07001409 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1410 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001411 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001412 // result will remain NO_INIT if no audio device is present
1413 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001414 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001415 AutoMutex lock(mHardwareLock);
1416 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1417 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001418 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001419 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001420 // return success if at least one audio device accepts the parameters as not all
1421 // HALs are requested to support all parameters. If no audio device supports the
1422 // requested parameters, the last error is reported.
1423 if (final_result != NO_ERROR) {
1424 final_result = result;
1425 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001426 }
1427 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001428 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001429 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001430 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001431 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001432 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1433 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001434 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001435 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001436 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001437 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001438 }
1439 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001440 String8 screenState;
1441 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001442 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001443 if (isOff != (AudioFlinger::mScreenState & 1)) {
1444 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001445 }
1446 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001447 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448 }
1449
1450 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1451 // and the thread is exited once the lock is released
1452 sp<ThreadBase> thread;
1453 {
1454 Mutex::Autolock _l(mLock);
1455 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001456 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001457 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001458 if (thread == 0) {
1459 thread = checkMmapThread_l(ioHandle);
1460 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001461 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001462 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001463 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001464 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001465 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1466 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001467 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001468 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 }
1470 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001471 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001472 status_t result = thread->setParameters(filteredKeyValuePairs);
1473 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1474 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475 }
1476 return BAD_VALUE;
1477}
1478
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001479String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001480{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001481 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1482 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483
Eric Laurenta4c5a552012-03-29 10:12:40 -07001484 Mutex::Autolock _l(mLock);
1485
Glenn Kasten142f5192014-03-25 17:44:59 -07001486 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001487 String8 out_s8;
1488
Dima Zavin799a70e2011-04-18 16:57:27 -07001489 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001490 String8 s;
1491 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001492 {
1493 AutoMutex lock(mHardwareLock);
1494 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001495 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1496 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001497 mHardwareStatus = AUDIO_HW_IDLE;
1498 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001499 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001500 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001501 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 }
1503
Eric Laurent6acd1d42017-01-04 14:23:29 -08001504 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1505 if (thread == NULL) {
1506 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1507 if (thread == NULL) {
1508 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1509 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001510 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001511 }
1512 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001514 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515}
1516
Glenn Kastendd8104c2012-07-02 12:42:44 -07001517size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1518 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001519{
Eric Laurenta1884f92011-08-23 08:25:03 -07001520 status_t ret = initCheck();
1521 if (ret != NO_ERROR) {
1522 return 0;
1523 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001524 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001525 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001526 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001527 return 0;
1528 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001529
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001530 AutoMutex lock(mHardwareLock);
1531 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001532 audio_config_t config, proposed;
1533 memset(&proposed, 0, sizeof(proposed));
1534 proposed.sample_rate = sampleRate;
1535 proposed.channel_mask = channelMask;
1536 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001537
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001538 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001539 size_t frames;
1540 for (;;) {
1541 // Note: config is currently a const parameter for get_input_buffer_size()
1542 // but we use a copy from proposed in case config changes from the call.
1543 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001544 status_t result = dev->getInputBufferSize(&config, &frames);
1545 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001546 break; // hal success, config is the result
1547 }
1548 // change one parameter of the configuration each iteration to a more "common" value
1549 // to see if the device will support it.
1550 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1551 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1552 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1553 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1554 } else {
1555 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1556 "format %#x, channelMask 0x%X",
1557 sampleRate, format, channelMask);
1558 break; // retries failed, break out of loop with frames == 0.
1559 }
1560 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001561 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001562 if (frames > 0 && config.sample_rate != sampleRate) {
1563 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1564 }
1565 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566}
1567
Glenn Kasten5f972c02014-01-13 09:59:31 -08001568uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 Mutex::Autolock _l(mLock);
1571
1572 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1573 if (recordThread != NULL) {
1574 return recordThread->getInputFramesLost();
1575 }
1576 return 0;
1577}
1578
1579status_t AudioFlinger::setVoiceVolume(float value)
1580{
Eric Laurenta1884f92011-08-23 08:25:03 -07001581 status_t ret = initCheck();
1582 if (ret != NO_ERROR) {
1583 return ret;
1584 }
1585
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586 // check calling permissions
1587 if (!settingsAllowed()) {
1588 return PERMISSION_DENIED;
1589 }
1590
1591 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001592 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001593 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001594 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 mHardwareStatus = AUDIO_HW_IDLE;
1596
1597 return ret;
1598}
1599
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001600status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001601 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 Mutex::Autolock _l(mLock);
1604
1605 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1606 if (playbackThread != NULL) {
1607 return playbackThread->getRenderPosition(halFrames, dspFrames);
1608 }
1609
1610 return BAD_VALUE;
1611}
1612
1613void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1614{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001616 if (client == 0) {
1617 return;
1618 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001619 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001620 {
1621 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001622 if (mNotificationClients.indexOfKey(pid) < 0) {
1623 sp<NotificationClient> notificationClient = new NotificationClient(this,
1624 client,
1625 pid);
1626 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627
Eric Laurent021cf962014-05-13 10:18:14 -07001628 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629
Marco Nelissen06b46062014-11-14 07:58:25 -08001630 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001631 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001632 }
1633 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634
Eric Laurent021cf962014-05-13 10:18:14 -07001635 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001636 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001637 // the config change is always sent from playback or record threads to avoid deadlock
1638 // with AudioSystem::gLock
1639 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001640 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001641 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001643 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001644 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645 }
1646}
1647
1648void AudioFlinger::removeNotificationClient(pid_t pid)
1649{
Eric Laurent6c796322019-04-09 14:13:17 -07001650 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001651 {
Eric Laurent6c796322019-04-09 14:13:17 -07001652 Mutex::Autolock _l(mLock);
1653 {
1654 Mutex::Autolock _cl(mClientLock);
1655 mNotificationClients.removeItem(pid);
1656 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001657
Eric Laurent6c796322019-04-09 14:13:17 -07001658 ALOGV("%d died, releasing its sessions", pid);
1659 size_t num = mAudioSessionRefs.size();
1660 bool removed = false;
1661 for (size_t i = 0; i < num; ) {
1662 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1663 ALOGV(" pid %d @ %zu", ref->mPid, i);
1664 if (ref->mPid == pid) {
1665 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1666 mAudioSessionRefs.removeAt(i);
1667 delete ref;
1668 removed = true;
1669 num--;
1670 } else {
1671 i++;
1672 }
1673 }
1674 if (removed) {
1675 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001676 }
1677 }
Eric Laurent6c796322019-04-09 14:13:17 -07001678 for (auto& effect : removedEffects) {
1679 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001680 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681}
1682
Eric Laurent73e26b62015-04-27 16:55:58 -07001683void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001684 const sp<AudioIoDescriptor>& ioDesc,
1685 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686{
Eric Laurent021cf962014-05-13 10:18:14 -07001687 Mutex::Autolock _l(mClientLock);
1688 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001690 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1691 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1692 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693 }
1694}
1695
Eric Laurent021cf962014-05-13 10:18:14 -07001696// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697void AudioFlinger::removeClient_l(pid_t pid)
1698{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001699 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001700 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701 mClients.removeItem(pid);
1702}
1703
Eric Laurent717e1282012-06-29 16:36:52 -07001704// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001705sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1706 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001707{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001708 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001709
1710 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001711 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001712 ALOG_ASSERT(thread == 0);
1713 thread = mPlaybackThreads.valueAt(i);
1714 }
1715 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001716 if (thread != nullptr) {
1717 return thread;
1718 }
1719 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1720 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1721 ALOG_ASSERT(thread == 0);
1722 thread = mRecordThreads.valueAt(i);
1723 }
1724 }
1725 if (thread != nullptr) {
1726 return thread;
1727 }
1728 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1729 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1730 ALOG_ASSERT(thread == 0);
1731 thread = mMmapThreads.valueAt(i);
1732 }
1733 }
Eric Laurent717e1282012-06-29 16:36:52 -07001734 return thread;
1735}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738
1739// ----------------------------------------------------------------------------
1740
1741AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1742 : RefBase(),
1743 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001744 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745{
Andy Hung6f248bb2018-01-23 14:04:37 -08001746 mMemoryDealer = new MemoryDealer(
1747 audioFlinger->getClientSharedHeapSize(),
1748 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749}
1750
Eric Laurent021cf962014-05-13 10:18:14 -07001751// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001752AudioFlinger::Client::~Client()
1753{
1754 mAudioFlinger->removeClient_l(mPid);
1755}
1756
Glenn Kasten435dbe62012-01-30 10:15:48 -08001757sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758{
1759 return mMemoryDealer;
1760}
1761
1762// ----------------------------------------------------------------------------
1763
1764AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1765 const sp<IAudioFlingerClient>& client,
1766 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001767 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768{
1769}
1770
1771AudioFlinger::NotificationClient::~NotificationClient()
1772{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773}
1774
Glenn Kasten0f11b512014-01-31 16:18:54 -08001775void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776{
1777 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001778 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779}
1780
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001781// ----------------------------------------------------------------------------
1782AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1783 : mPendingRequests(false) {}
1784
1785
1786void AudioFlinger::MediaLogNotifier::requestMerge() {
1787 AutoMutex _l(mMutex);
1788 mPendingRequests = true;
1789 mCond.signal();
1790}
1791
1792bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001793 // Should already have been checked, but just in case
1794 if (sMediaLogService == 0) {
1795 return false;
1796 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001797 // Wait until there are pending requests
1798 {
1799 AutoMutex _l(mMutex);
1800 mPendingRequests = false; // to ignore past requests
1801 while (!mPendingRequests) {
1802 mCond.wait(mMutex);
1803 // TODO may also need an exitPending check
1804 }
1805 mPendingRequests = false;
1806 }
1807 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001808 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001809 usleep(kPostTriggerSleepPeriod);
1810 return true;
1811}
1812
1813void AudioFlinger::requestLogMerge() {
1814 mMediaLogNotifier->requestMerge();
1815}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001816
1817// ----------------------------------------------------------------------------
1818
Eric Laurentf14db3c2017-12-08 14:20:36 -08001819sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1820 CreateRecordOutput& output,
1821 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822{
1823 sp<RecordThread::RecordTrack> recordTrack;
1824 sp<RecordHandle> recordHandle;
1825 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001827 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001828 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829
Eric Laurentf14db3c2017-12-08 14:20:36 -08001830 output.cblk.clear();
1831 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001832 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001833
Eric Laurentf14db3c2017-12-08 14:20:36 -08001834 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001835 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001836 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001837 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001838 ALOGW_IF(clientUid != callingUid,
1839 "%s uid %d tried to pass itself off as %d",
1840 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001841 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001842 updatePid = true;
1843 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001844 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -07001845 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001846 if (updatePid) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001847 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001848 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001849 __func__, callingUid, callingPid, clientPid);
1850 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001851 }
1852
Andy Hung6770c6f2015-04-07 13:43:36 -07001853 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001854 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1855 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001856 lStatus = BAD_VALUE;
1857 goto Exit;
1858 }
1859
Glenn Kasten53b5d092014-02-05 10:00:23 -08001860 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001861 if (!audio_is_input_channel(input.config.channel_mask)) {
1862 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001863 lStatus = BAD_VALUE;
1864 goto Exit;
1865 }
1866
Eric Laurentf14db3c2017-12-08 14:20:36 -08001867 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1868 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1869 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1870 lStatus = BAD_VALUE;
1871 goto Exit;
1872 }
1873
1874 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001875 output.selectedDeviceId = input.selectedDeviceId;
1876 output.flags = input.flags;
1877
1878 client = registerPid(clientPid);
1879
1880 // Not a conventional loop, but a retry loop for at most two iterations total.
1881 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1882 // Exits loop via break on no error of got exit on error
1883 // The sp<> references will be dropped when re-entering scope.
1884 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1885 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001886 // release previously opened input if retrying.
1887 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1888 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001889 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001890 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001891 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001892 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001893 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001894 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07001895 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001896 sessionId,
1897 // FIXME compare to AudioTrack
1898 clientPid,
1899 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001900 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001901 &input.config,
1902 output.flags, &output.selectedDeviceId, &portId);
1903
Glenn Kasten05997e22014-03-13 15:08:33 -07001904 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001906 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001908 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909 lStatus = BAD_VALUE;
1910 goto Exit;
1911 }
1912
Eric Laurentf14db3c2017-12-08 14:20:36 -08001913 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914
Eric Laurentf14db3c2017-12-08 14:20:36 -08001915 output.sampleRate = input.config.sample_rate;
1916 output.frameCount = input.frameCount;
1917 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001918
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001919 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001920 input.config.format, input.config.channel_mask,
1921 &output.frameCount, sessionId,
1922 &output.notificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001923 callingPid, clientUid, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001924 input.clientInfo.clientTid,
1925 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001926 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001927
Eric Laurentf14db3c2017-12-08 14:20:36 -08001928 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1929 // audio policy manager without FAST constraint
1930 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001931 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001932 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001933
1934 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001935 goto Exit;
1936 }
1937
1938 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1939 // session and move it to this thread.
1940 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1941 if (chain != 0) {
1942 Mutex::Autolock _l(thread->mLock);
1943 thread->addEffectChain_l(chain);
1944 }
1945 break;
1946 }
1947 // End of retry loop.
1948 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 }
Glenn Kastene198c362013-08-13 09:13:36 -07001950
Eric Laurentf14db3c2017-12-08 14:20:36 -08001951 output.cblk = recordTrack->getCblk();
1952 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08001953 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001954
1955 // return handle to client
1956 recordHandle = new RecordHandle(recordTrack);
1957
1958Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001959 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001960 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001961 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001962 // Don't hold mClientLock when releasing the reference on the track as the
1963 // destructor will acquire it.
1964 {
1965 Mutex::Autolock _cl(mClientLock);
1966 client.clear();
1967 }
Eric Laurent896c9672017-12-08 14:08:45 -08001968 recordTrack.clear();
1969 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001970 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001971 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 }
1973
Glenn Kasten9156ef32013-08-06 15:39:08 -07001974 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 return recordHandle;
1976}
1977
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001978
1979
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980// ----------------------------------------------------------------------------
1981
Eric Laurenta4c5a552012-03-29 10:12:40 -07001982audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1983{
Eric Laurent44622db2014-08-01 19:00:33 -07001984 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001985 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001986 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001987 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001988 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001989 }
1990 Mutex::Autolock _l(mLock);
1991 return loadHwModule_l(name);
1992}
1993
1994// loadHwModule_l() must be called with AudioFlinger::mLock held
1995audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1996{
1997 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1998 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1999 ALOGW("loadHwModule() module %s already loaded", name);
2000 return mAudioHwDevs.keyAt(i);
2001 }
2002 }
2003
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002004 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002005
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002006 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002007 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002008 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002009 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002010 }
2011
2012 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002013 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002014 mHardwareStatus = AUDIO_HW_IDLE;
2015 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002016 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002017 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002018 }
2019
John Grossmanee578c02012-07-23 17:05:46 -07002020 // Check and cache this HAL's level of support for master mute and master
2021 // volume. If this is the first HAL opened, and it supports the get
2022 // methods, use the initial values provided by the HAL as the current
2023 // master mute and volume settings.
2024
2025 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2026 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07002027 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07002028
2029 if (0 == mAudioHwDevs.size()) {
2030 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002031 float mv;
2032 if (OK == dev->getMasterVolume(&mv)) {
2033 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002034 }
2035
2036 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002037 bool mm;
2038 if (OK == dev->getMasterMute(&mm)) {
2039 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002040 }
2041 }
2042
Eric Laurenta4c5a552012-03-29 10:12:40 -07002043 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002044 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002045 flags = static_cast<AudioHwDevice::Flags>(flags |
2046 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2047 }
2048
2049 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002050 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002051 flags = static_cast<AudioHwDevice::Flags>(flags |
2052 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2053 }
2054
Eric Laurenta4c5a552012-03-29 10:12:40 -07002055 mHardwareStatus = AUDIO_HW_IDLE;
2056 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002057 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002058 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2059 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2060 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002061
Glenn Kastena13cde92016-03-28 15:26:02 -07002062 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002063 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002064
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002065 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002066
2067 return handle;
2068
2069}
2070
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002071// ----------------------------------------------------------------------------
2072
Glenn Kasten3b16c762012-11-14 08:44:39 -08002073uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002074{
2075 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002076 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002077 return thread != NULL ? thread->sampleRate() : 0;
2078}
2079
Glenn Kastene33054e2012-11-14 12:54:39 -08002080size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002081{
2082 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002083 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002084 return thread != NULL ? thread->frameCountHAL() : 0;
2085}
2086
2087// ----------------------------------------------------------------------------
2088
Andy Hung6f248bb2018-01-23 14:04:37 -08002089status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002090{
2091 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002092 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002093 return PERMISSION_DENIED;
2094 }
2095 Mutex::Autolock _l(mLock);
2096 if (mIsDeviceTypeKnown) {
2097 return INVALID_OPERATION;
2098 }
2099 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002100 mTotalMemory = totalMemory;
2101 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2102 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2103 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2104 // though actual setting is determined through device configuration.
2105 constexpr int64_t GB = 1024 * 1024 * 1024;
2106 mClientSharedHeapSize =
2107 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2108 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2109 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2110 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2111 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002112 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002113
2114 // TODO: Cache the client shared heap size in a persistent property.
2115 // It's possible that a native process or Java service or app accesses audioserver
2116 // after it is registered by system server, but before AudioService updates
2117 // the memory info. This would occur immediately after boot or an audioserver
2118 // crash and restore. Before update from AudioService, the client would get the
2119 // minimum heap size.
2120
2121 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2122 (isLowRamDevice ? "true" : "false"),
2123 (long long)mTotalMemory,
2124 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002125 return NO_ERROR;
2126}
2127
Andy Hung6f248bb2018-01-23 14:04:37 -08002128size_t AudioFlinger::getClientSharedHeapSize() const
2129{
2130 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2131 if (heapSizeInBytes != 0) { // read-only property overrides all.
2132 return heapSizeInBytes;
2133 }
2134 return mClientSharedHeapSize;
2135}
2136
Mikhail Naganovdea53042018-04-26 13:10:21 -07002137status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2138{
2139 ALOGV(__func__);
2140
2141 audio_module_handle_t module;
2142 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2143 module = config->ext.device.hw_module;
2144 } else {
2145 module = config->ext.mix.hw_module;
2146 }
2147
2148 Mutex::Autolock _l(mLock);
2149 ssize_t index = mAudioHwDevs.indexOfKey(module);
2150 if (index < 0) {
2151 ALOGW("%s() bad hw module %d", __func__, module);
2152 return BAD_VALUE;
2153 }
2154
2155 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2156 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2157}
2158
Eric Laurent93c3d412014-08-01 14:48:35 -07002159audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2160{
2161 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002162
2163 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2164 if (index >= 0) {
2165 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2166 mHwAvSyncIds.valueAt(index), sessionId);
2167 return mHwAvSyncIds.valueAt(index);
2168 }
2169
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002170 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002171 if (dev == NULL) {
2172 return AUDIO_HW_SYNC_INVALID;
2173 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002174 String8 reply;
2175 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002176 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002177 param = AudioParameter(reply);
2178 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002179
2180 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002181 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002182 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2183 return AUDIO_HW_SYNC_INVALID;
2184 }
2185
2186 // allow only one session for a given HW A/V sync ID.
2187 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2188 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2189 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2190 value, mHwAvSyncIds.keyAt(i));
2191 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002192 break;
2193 }
2194 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002195
2196 mHwAvSyncIds.add(sessionId, value);
2197
2198 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2199 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2200 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002201 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002202 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002203 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002204 String8 keyValuePairs = param.toString();
2205 thread->setParameters(keyValuePairs);
2206 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2207 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002208 break;
2209 }
2210 }
2211
2212 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2213 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002214}
2215
Eric Laurent72e3f392015-05-20 14:43:50 -07002216status_t AudioFlinger::systemReady()
2217{
2218 Mutex::Autolock _l(mLock);
2219 ALOGI("%s", __FUNCTION__);
2220 if (mSystemReady) {
2221 ALOGW("%s called twice", __FUNCTION__);
2222 return NO_ERROR;
2223 }
2224 mSystemReady = true;
2225 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2226 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2227 thread->systemReady();
2228 }
2229 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2230 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2231 thread->systemReady();
2232 }
2233 return NO_ERROR;
2234}
2235
jiabin46a76fa2018-01-05 10:18:21 -08002236status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2237{
jiabin9ff780e2018-03-19 18:19:52 -07002238 AutoMutex lock(mHardwareLock);
2239 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2240 status_t status = dev->getMicrophones(microphones);
2241 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002242}
2243
Eric Laurentfa90e842014-10-17 18:12:31 -07002244// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2245void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2246{
2247 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2248 if (index >= 0) {
2249 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2250 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2251 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002252 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002253 String8 keyValuePairs = param.toString();
2254 thread->setParameters(keyValuePairs);
2255 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2256 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002257 }
2258}
2259
2260
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002261// ----------------------------------------------------------------------------
2262
Eric Laurent83b88082014-06-20 18:31:16 -07002263
Eric Laurent6acd1d42017-01-04 14:23:29 -08002264sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002265 audio_io_handle_t *output,
2266 audio_config_t *config,
2267 audio_devices_t devices,
2268 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002269 audio_output_flags_t flags)
2270{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002271 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002272 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002273 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002274 }
2275
Eric Laurentcf2c0212014-07-25 16:20:43 -07002276 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002277 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2278 } else {
2279 // Audio Policy does not currently request a specific output handle.
2280 // If this is ever needed, see openInput_l() for example code.
2281 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2282 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002283 }
Eric Laurent83b88082014-06-20 18:31:16 -07002284
2285 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2286
Eric Laurent83b88082014-06-20 18:31:16 -07002287 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002288 // This if statement allows overriding the audio policy settings
2289 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2290 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2291 // Check only for Normal Mixing mode
2292 if (kEnableExtendedPrecision) {
2293 // Specify format (uncomment one below to choose)
2294 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2295 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2296 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2297 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002298 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002299 }
2300 if (kEnableExtendedChannels) {
2301 // Specify channel mask (uncomment one below to choose)
2302 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2303 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2304 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2305 }
Eric Laurent83b88082014-06-20 18:31:16 -07002306 }
2307
Phil Burk062e67a2015-02-11 13:40:50 -08002308 AudioStreamOut *outputStream = NULL;
2309 status_t status = outHwDev->openOutputStream(
2310 &outputStream,
2311 *output,
2312 devices,
2313 flags,
2314 config,
2315 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002316
2317 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002318
Phil Burk062e67a2015-02-11 13:40:50 -08002319 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002320 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2321 sp<MmapPlaybackThread> thread =
2322 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2323 devices, AUDIO_DEVICE_NONE, mSystemReady);
2324 mMmapThreads.add(*output, thread);
2325 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2326 *output, thread.get());
2327 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002328 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002329 sp<PlaybackThread> thread;
2330 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2331 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2332 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2333 *output, thread.get());
2334 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2335 || !isValidPcmSinkFormat(config->format)
2336 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2337 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2338 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2339 *output, thread.get());
2340 } else {
2341 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2342 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2343 *output, thread.get());
2344 }
2345 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002346 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002347 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002348 }
Eric Laurent83b88082014-06-20 18:31:16 -07002349 }
2350
2351 return 0;
2352}
2353
Eric Laurentcf2c0212014-07-25 16:20:43 -07002354status_t AudioFlinger::openOutput(audio_module_handle_t module,
2355 audio_io_handle_t *output,
2356 audio_config_t *config,
2357 audio_devices_t *devices,
2358 const String8& address,
2359 uint32_t *latencyMs,
2360 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002362 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2363 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002364 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002365 (devices != NULL) ? *devices : 0,
2366 config->sample_rate,
2367 config->format,
2368 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002369 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002371 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002372 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002373 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002374
Mathias Agopian65ab4712010-07-14 17:59:35 -07002375 Mutex::Autolock _l(mLock);
2376
Eric Laurent6acd1d42017-01-04 14:23:29 -08002377 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002378 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002379 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2380 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2381 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382
Eric Laurent6acd1d42017-01-04 14:23:29 -08002383 // notify client processes of the new output creation
2384 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002385
Eric Laurent6acd1d42017-01-04 14:23:29 -08002386 // the first primary output opened designates the primary hw device
2387 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002388 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002389 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002390
Eric Laurent6acd1d42017-01-04 14:23:29 -08002391 AutoMutex lock(mHardwareLock);
2392 mHardwareStatus = AUDIO_HW_SET_MODE;
2393 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2394 mHardwareStatus = AUDIO_HW_IDLE;
2395 }
2396 } else {
2397 MmapThread *mmapThread = (MmapThread *)thread.get();
2398 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002399 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002400 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401 }
2402
Eric Laurentcf2c0212014-07-25 16:20:43 -07002403 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404}
2405
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002406audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2407 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408{
2409 Mutex::Autolock _l(mLock);
2410 MixerThread *thread1 = checkMixerThread_l(output1);
2411 MixerThread *thread2 = checkMixerThread_l(output2);
2412
2413 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002414 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2415 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002416 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417 }
2418
Glenn Kasteneeecb982016-02-26 10:44:04 -08002419 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002420 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 thread->addOutputTrack(thread2);
2422 mPlaybackThreads.add(id, thread);
2423 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002424 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 return id;
2426}
2427
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002428status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429{
Glenn Kastend96c5722012-04-25 13:44:49 -07002430 return closeOutput_nonvirtual(output);
2431}
2432
2433status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2434{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 // keep strong reference on the playback thread so that
2436 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002437 sp<PlaybackThread> playbackThread;
2438 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 {
2440 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002441 playbackThread = checkPlaybackThread_l(output);
2442 if (playbackThread != NULL) {
2443 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444
Andy Hungdc099c22018-09-18 13:46:39 -07002445 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002446
Eric Laurent6acd1d42017-01-04 14:23:29 -08002447 if (playbackThread->type() == ThreadBase::MIXER) {
2448 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2449 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2450 DuplicatingThread *dupThread =
2451 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2452 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2453 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002454 }
2455 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002456
2457
Eric Laurent6acd1d42017-01-04 14:23:29 -08002458 mPlaybackThreads.removeItem(output);
2459 // save all effects to the default thread
2460 if (mPlaybackThreads.size()) {
2461 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2462 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002463 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002464 Mutex::Autolock _dl(dstThread->mLock);
2465 Mutex::Autolock _sl(playbackThread->mLock);
2466 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2467 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002468 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002469 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002470 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471 }
2472 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002473 } else {
2474 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2475 if (mmapThread == 0) {
2476 return BAD_VALUE;
2477 }
Andy Hungdc099c22018-09-18 13:46:39 -07002478 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002479 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002480 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002482 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2483 ioDesc->mIoHandle = output;
2484 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002485 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002487 // The thread entity (active unit of execution) is no longer running here,
2488 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489
Eric Laurent6acd1d42017-01-04 14:23:29 -08002490 if (playbackThread != 0) {
2491 playbackThread->exit();
2492 if (!playbackThread->isDuplicating()) {
2493 closeOutputFinish(playbackThread);
2494 }
2495 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002496 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002497 mmapThread->exit();
2498 AudioStreamOut *out = mmapThread->clearOutput();
2499 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2500 // from now on thread->mOutput is NULL
2501 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 }
2503 return NO_ERROR;
2504}
2505
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002506void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002507{
2508 AudioStreamOut *out = thread->clearOutput();
2509 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2510 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002511 delete out;
2512}
2513
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002514void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002515{
2516 mPlaybackThreads.removeItem(thread->mId);
2517 thread->exit();
2518 closeOutputFinish(thread);
2519}
2520
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002521status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002522{
2523 Mutex::Autolock _l(mLock);
2524 PlaybackThread *thread = checkPlaybackThread_l(output);
2525
2526 if (thread == NULL) {
2527 return BAD_VALUE;
2528 }
2529
Steve Block3856b092011-10-20 11:56:00 +01002530 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 thread->suspend();
2532
2533 return NO_ERROR;
2534}
2535
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002536status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537{
2538 Mutex::Autolock _l(mLock);
2539 PlaybackThread *thread = checkPlaybackThread_l(output);
2540
2541 if (thread == NULL) {
2542 return BAD_VALUE;
2543 }
2544
Steve Block3856b092011-10-20 11:56:00 +01002545 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546
2547 thread->restore();
2548
2549 return NO_ERROR;
2550}
2551
Eric Laurentcf2c0212014-07-25 16:20:43 -07002552status_t AudioFlinger::openInput(audio_module_handle_t module,
2553 audio_io_handle_t *input,
2554 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002555 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002556 const String8& address,
2557 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002558 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559{
Eric Laurent83b88082014-06-20 18:31:16 -07002560 Mutex::Autolock _l(mLock);
2561
Glenn Kastene7d66712015-03-05 13:46:52 -08002562 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002563 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002564 }
2565
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002566 sp<ThreadBase> thread = openInput_l(
2567 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002568
2569 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002570 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002571 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002572 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002573 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002574 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002575}
Dima Zavin799a70e2011-04-18 16:57:27 -07002576
Eric Laurent6acd1d42017-01-04 14:23:29 -08002577sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002578 audio_io_handle_t *input,
2579 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002580 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002581 const String8& address,
2582 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002583 audio_input_flags_t flags,
2584 audio_devices_t outputDevice,
2585 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002586{
Glenn Kastene7d66712015-03-05 13:46:52 -08002587 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002588 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002589 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002590 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002591 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002592
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002593 // Some flags are specific to framework and must not leak to the HAL.
2594 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2595
Glenn Kasteneeecb982016-02-26 10:44:04 -08002596 // Audio Policy can request a specific handle for hardware hotword.
2597 // The goal here is not to re-open an already opened input.
2598 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002599 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002600 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2601 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2602 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2603 return 0;
2604 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2605 // This should not happen in a transient state with current design.
2606 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2607 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002608 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002609
Eric Laurentcf2c0212014-07-25 16:20:43 -07002610 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002611 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002612 sp<StreamInHalInterface> inStream;
2613 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002614 *input, devices, &halconfig, flags, address.string(), source,
2615 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002616 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2617 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002618 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002619 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002620 halconfig.sample_rate,
2621 halconfig.format,
2622 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002623 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002624 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002626 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002627 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002628 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002629 audio_is_linear_pcm(config->format) &&
2630 audio_is_linear_pcm(halconfig.format) &&
2631 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002632 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2633 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002634 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002635 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002636 inStream.clear();
2637 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002638 *input, devices, &halconfig, flags, address.string(), source,
2639 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002640 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641 }
2642
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002643 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002644 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002645 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2646 sp<MmapCaptureThread> thread =
2647 new MmapCaptureThread(this, *input,
2648 inHwDev, inputStream,
2649 primaryOutputDevice_l(), devices, mSystemReady);
2650 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002651 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2652 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002653 return thread;
2654 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002655 // Start record thread
2656 // RecordThread requires both input and output device indication to forward to audio
2657 // pre processing modules
2658 sp<RecordThread> thread = new RecordThread(this,
2659 inputStream,
2660 *input,
2661 primaryOutputDevice_l(),
2662 devices,
2663 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002664 );
2665 mRecordThreads.add(*input, thread);
2666 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2667 return thread;
2668 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669 }
2670
Eric Laurentcf2c0212014-07-25 16:20:43 -07002671 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002672 return 0;
2673}
2674
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002675status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676{
Glenn Kastend96c5722012-04-25 13:44:49 -07002677 return closeInput_nonvirtual(input);
2678}
2679
2680status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2681{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002682 // keep strong reference on the record thread so that
2683 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002684 sp<RecordThread> recordThread;
2685 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686 {
2687 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002688 recordThread = checkRecordThread_l(input);
2689 if (recordThread != 0) {
2690 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002691
Andy Hungdc099c22018-09-18 13:46:39 -07002692 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002693
Eric Laurent6acd1d42017-01-04 14:23:29 -08002694 // If we still have effect chains, it means that a client still holds a handle
2695 // on at least one effect. We must either move the chain to an existing thread with the
2696 // same session ID or put it aside in case a new record thread is opened for a
2697 // new capture on the same session
2698 sp<EffectChain> chain;
2699 {
2700 Mutex::Autolock _sl(recordThread->mLock);
2701 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2702 // Note: maximum one chain per record thread
2703 if (effectChains.size() != 0) {
2704 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002705 }
2706 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002707 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002708 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002709 // This should only happen in case of overlap between one thread tear down and the
2710 // creation of its replacement
2711 size_t i;
2712 for (i = 0; i < mRecordThreads.size(); i++) {
2713 sp<RecordThread> t = mRecordThreads.valueAt(i);
2714 if (t == recordThread) {
2715 continue;
2716 }
2717 if (t->hasAudioSession(chain->sessionId()) != 0) {
2718 Mutex::Autolock _l(t->mLock);
2719 ALOGV("closeInput() found thread %d for effect session %d",
2720 t->id(), chain->sessionId());
2721 t->addEffectChain_l(chain);
2722 break;
2723 }
2724 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002725 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002726 if (i == mRecordThreads.size()) {
2727 putOrphanEffectChain_l(chain);
2728 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002729 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002730 mRecordThreads.removeItem(input);
2731 } else {
2732 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2733 if (mmapThread == 0) {
2734 return BAD_VALUE;
2735 }
Andy Hungdc099c22018-09-18 13:46:39 -07002736 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002737 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002738 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002739 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2740 ioDesc->mIoHandle = input;
2741 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742 }
Eric Laurent83b88082014-06-20 18:31:16 -07002743 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2744 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002745 if (recordThread != 0) {
2746 closeInputFinish(recordThread);
2747 } else if (mmapThread != 0) {
2748 mmapThread->exit();
2749 AudioStreamIn *in = mmapThread->clearInput();
2750 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2751 // from now on thread->mInput is NULL
2752 delete in;
2753 }
Eric Laurent83b88082014-06-20 18:31:16 -07002754 return NO_ERROR;
2755}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002757void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002758{
2759 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002760 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002761 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002762 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002763 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002764}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002765
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002766void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002767{
2768 mRecordThreads.removeItem(thread->mId);
2769 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770}
2771
Glenn Kastend2304db2014-02-03 07:40:31 -08002772status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002773{
2774 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002775 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002776
2777 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2778 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002779 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002780 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002781 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2782 mMmapThreads[i]->invalidateTracks(stream);
2783 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002784 return NO_ERROR;
2785}
2786
2787
Glenn Kasteneeecb982016-02-26 10:44:04 -08002788audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789{
Glenn Kasten9d003132016-04-06 14:38:09 -07002790 // This is a binder API, so a malicious client could pass in a bad parameter.
2791 // Check for that before calling the internal API nextUniqueId().
2792 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2793 ALOGE("newAudioUniqueId invalid use %d", use);
2794 return AUDIO_UNIQUE_ID_ALLOCATE;
2795 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002796 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002797}
2798
Glenn Kastend848eb42016-03-08 13:42:11 -08002799void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002800{
2801 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002802 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002803 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002804 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2805 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002806 caller = pid;
2807 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002808
Eric Laurent021cf962014-05-13 10:18:14 -07002809 {
2810 Mutex::Autolock _cl(mClientLock);
2811 // Ignore requests received from processes not known as notification client. The request
2812 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2813 // called from a different pid leaving a stale session reference. Also we don't know how
2814 // to clear this reference if the client process dies.
2815 if (mNotificationClients.indexOfKey(caller) < 0) {
2816 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2817 return;
2818 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002819 }
2820
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002821 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002822 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002823 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002824 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2825 ref->mCnt++;
2826 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002827 return;
2828 }
2829 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002830 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2831 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002832}
2833
Glenn Kastend848eb42016-03-08 13:42:11 -08002834void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002835{
Eric Laurent6c796322019-04-09 14:13:17 -07002836 std::vector< sp<EffectModule> > removedEffects;
2837 {
2838 Mutex::Autolock _l(mLock);
2839 pid_t caller = IPCThreadState::self()->getCallingPid();
2840 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2841 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2842 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
2843 caller = pid;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002844 }
Eric Laurent6c796322019-04-09 14:13:17 -07002845 size_t num = mAudioSessionRefs.size();
2846 for (size_t i = 0; i < num; i++) {
2847 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2848 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2849 ref->mCnt--;
2850 ALOGV(" decremented refcount to %d", ref->mCnt);
2851 if (ref->mCnt == 0) {
2852 mAudioSessionRefs.removeAt(i);
2853 delete ref;
2854 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2855 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2856 }
2857 goto Exit;
2858 }
2859 }
2860 // If the caller is audioserver it is likely that the session being released was acquired
2861 // on behalf of a process not in notification clients and we ignore the warning.
2862 ALOGW_IF(!isAudioServerUid(callerUid),
2863 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002864 }
Eric Laurent6c796322019-04-09 14:13:17 -07002865
2866Exit:
2867 for (auto& effect : removedEffects) {
2868 effect->updatePolicyState();
2869 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002870}
2871
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002872bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2873{
2874 size_t num = mAudioSessionRefs.size();
2875 for (size_t i = 0; i < num; i++) {
2876 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2877 if (ref->mSessionid == audioSession) {
2878 return true;
2879 }
2880 }
2881 return false;
2882}
2883
Eric Laurent6c796322019-04-09 14:13:17 -07002884std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002885
Steve Block3856b092011-10-20 11:56:00 +01002886 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002887
2888 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07002889 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002890
2891 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2892 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002893 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002894 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2895 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002896 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2897 chains.push(ec);
2898 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002899 }
2900 }
Eric Laurent6c796322019-04-09 14:13:17 -07002901
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002902 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2903 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002904 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002905 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2906 sp<EffectChain> ec = t->mEffectChains[j];
2907 chains.push(ec);
2908 }
2909 }
2910
Eric Laurent6c796322019-04-09 14:13:17 -07002911 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2912 sp<MmapThread> t = mMmapThreads.valueAt(i);
2913 Mutex::Autolock _l(t->mLock);
2914 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2915 sp<EffectChain> ec = t->mEffectChains[j];
2916 chains.push(ec);
2917 }
2918 }
2919
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002920 for (size_t i = 0; i < chains.size(); i++) {
2921 sp<EffectChain> ec = chains[i];
2922 int sessionid = ec->sessionId();
2923 sp<ThreadBase> t = ec->mThread.promote();
2924 if (t == 0) {
2925 continue;
2926 }
2927 size_t numsessionrefs = mAudioSessionRefs.size();
2928 bool found = false;
2929 for (size_t k = 0; k < numsessionrefs; k++) {
2930 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002931 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002932 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002933 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002934 found = true;
2935 break;
2936 }
2937 }
2938 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002939 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002940 // remove all effects from the chain
2941 while (ec->mEffects.size()) {
2942 sp<EffectModule> effect = ec->mEffects[0];
2943 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002944 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002945 if (effect->purgeHandles()) {
2946 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002947 }
Eric Laurent6c796322019-04-09 14:13:17 -07002948 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002949 }
2950 }
2951 }
Eric Laurent6c796322019-04-09 14:13:17 -07002952 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002953}
2954
Andy Hungdc099c22018-09-18 13:46:39 -07002955// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2956void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2957{
2958 audio_utils::FdToString fdToString;
2959 const int fd = fdToString.fd();
2960 if (fd >= 0) {
2961 thread->dump(fd, {} /* args */);
2962 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
2963 }
2964}
2965
Glenn Kasteneeecb982016-02-26 10:44:04 -08002966// checkThread_l() must be called with AudioFlinger::mLock held
2967AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2968{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002969 ThreadBase *thread = checkMmapThread_l(ioHandle);
2970 if (thread == 0) {
2971 switch (audio_unique_id_get_use(ioHandle)) {
2972 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2973 thread = checkPlaybackThread_l(ioHandle);
2974 break;
2975 case AUDIO_UNIQUE_ID_USE_INPUT:
2976 thread = checkRecordThread_l(ioHandle);
2977 break;
2978 default:
2979 break;
2980 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002981 }
2982 return thread;
2983}
2984
Mathias Agopian65ab4712010-07-14 17:59:35 -07002985// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002986AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987{
Glenn Kastena1117922012-01-26 10:53:32 -08002988 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002989}
2990
2991// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002992AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993{
2994 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002995 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002996}
2997
2998// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002999AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003000{
Glenn Kastena1117922012-01-26 10:53:32 -08003001 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003002}
3003
Eric Laurent6acd1d42017-01-04 14:23:29 -08003004// checkMmapThread_l() must be called with AudioFlinger::mLock held
3005AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3006{
3007 return mMmapThreads.valueFor(io).get();
3008}
3009
3010
3011// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3012AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3013{
Eric Laurent7459b902017-04-19 18:10:41 -07003014 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003015 if (volumeInterface == nullptr) {
3016 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3017 if (mmapThread != nullptr) {
3018 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003019 MmapPlaybackThread *mmapPlaybackThread =
3020 static_cast<MmapPlaybackThread *>(mmapThread);
3021 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003022 }
3023 }
3024 }
3025 return volumeInterface;
3026}
3027
3028Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3029{
3030 Vector <VolumeInterface *> volumeInterfaces;
3031 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003032 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003033 }
3034 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3035 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003036 MmapPlaybackThread *mmapPlaybackThread =
3037 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3038 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003039 }
3040 }
3041 return volumeInterfaces;
3042}
3043
Glenn Kasteneeecb982016-02-26 10:44:04 -08003044audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003045{
Glenn Kasten9d003132016-04-06 14:38:09 -07003046 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003047 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003048 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3049 for (int retry = 0; retry < maxRetries; retry++) {
3050 // The cast allows wraparound from max positive to min negative instead of abort
3051 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3052 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3053 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3054 // allow wrap by skipping 0 and -1 for session ids
3055 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3056 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3057 return (audio_unique_id_t) (base | use);
3058 }
3059 }
3060 // We have no way of recovering from wraparound
3061 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3062 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063}
3064
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003065AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003066{
3067 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3068 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003069 if(thread->isDuplicating()) {
3070 continue;
3071 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003072 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003073 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003074 return thread;
3075 }
3076 }
3077 return NULL;
3078}
3079
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003080audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003081{
3082 PlaybackThread *thread = primaryPlaybackThread_l();
3083
3084 if (thread == NULL) {
3085 return 0;
3086 }
3087
Eric Laurentf1c04f92012-08-28 14:26:53 -07003088 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003089}
3090
Glenn Kastena7335632016-06-09 17:09:53 -07003091AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3092{
3093 size_t minFrameCount = 0;
3094 PlaybackThread *minThread = NULL;
3095 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3096 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3097 if (!thread->isDuplicating()) {
3098 size_t frameCount = thread->frameCountHAL();
3099 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3100 (frameCount == minFrameCount && thread->hasFastMixer() &&
3101 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3102 minFrameCount = frameCount;
3103 minThread = thread;
3104 }
3105 }
3106 }
3107 return minThread;
3108}
3109
Eric Laurenta011e352012-03-29 15:51:43 -07003110sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003111 audio_session_t triggerSession,
3112 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003113 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003114 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003115{
3116 Mutex::Autolock _l(mLock);
3117
3118 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3119 status_t playStatus = NAME_NOT_FOUND;
3120 status_t recStatus = NAME_NOT_FOUND;
3121 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3122 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3123 if (playStatus == NO_ERROR) {
3124 return event;
3125 }
3126 }
3127 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3128 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3129 if (recStatus == NO_ERROR) {
3130 return event;
3131 }
3132 }
3133 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3134 mPendingSyncEvents.add(event);
3135 } else {
3136 ALOGV("createSyncEvent() invalid event %d", event->type());
3137 event.clear();
3138 }
3139 return event;
3140}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003141
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142// ----------------------------------------------------------------------------
3143// Effect management
3144// ----------------------------------------------------------------------------
3145
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003146sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3147 return mEffectsFactoryHal;
3148}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149
Glenn Kastenf587ba52012-01-26 16:25:10 -08003150status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151{
3152 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003153 if (mEffectsFactoryHal.get()) {
3154 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3155 } else {
3156 return -ENODEV;
3157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158}
3159
Glenn Kastenf587ba52012-01-26 16:25:10 -08003160status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161{
3162 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003163 if (mEffectsFactoryHal.get()) {
3164 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3165 } else {
3166 return -ENODEV;
3167 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168}
3169
Glenn Kasten5e92a782012-01-30 07:40:52 -08003170status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003171 const effect_uuid_t *pTypeUuid,
3172 uint32_t preferredTypeFlag,
3173 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003175 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3176 return BAD_VALUE;
3177 }
3178
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003180
3181 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003182 return -ENODEV;
3183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003185 status_t status = NO_ERROR;
3186 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3187 // If uuid is specified, request effect descriptor from that.
3188 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3189 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3190 // If uuid is not specified, look for an available implementation
3191 // of the required type instead.
3192
3193 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3194 effect_descriptor_t desc;
3195 desc.flags = 0; // prevent compiler warning
3196
3197 uint32_t numEffects = 0;
3198 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3199 if (status < 0) {
3200 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3201 return status;
3202 }
3203
3204 bool found = false;
3205 for (uint32_t i = 0; i < numEffects; i++) {
3206 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3207 if (status < 0) {
3208 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3209 continue;
3210 }
3211 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3212 // If matching type found save effect descriptor.
3213 found = true;
3214 *descriptor = desc;
3215
3216 // If there's no preferred flag or this descriptor matches the preferred
3217 // flag, success! If this descriptor doesn't match the preferred
3218 // flag, continue enumeration in case a better matching version of this
3219 // effect type is available. Note that this means if no effect with a
3220 // correct flag is found, the descriptor returned will correspond to the
3221 // last effect that at least had a matching type uuid (if any).
3222 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3223 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3224 break;
3225 }
3226 }
3227 }
3228
3229 if (!found) {
3230 status = NAME_NOT_FOUND;
3231 ALOGW("getEffectDescriptor(): Effect not found by type.");
3232 }
3233 } else {
3234 status = BAD_VALUE;
3235 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3236 }
3237 return status;
3238}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003240sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 effect_descriptor_t *pDesc,
3242 const sp<IEffectClient>& effectClient,
3243 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003244 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003245 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003246 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003247 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248 status_t *status,
3249 int *id,
3250 int *enabled)
3251{
3252 status_t lStatus = NO_ERROR;
3253 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255
Eric Laurentb6436272016-12-07 19:24:50 -08003256 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003257 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003258 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3259 ALOGW_IF(pid != -1 && pid != callingPid,
3260 "%s uid %d pid %d tried to pass itself off as pid %d",
3261 __func__, callingUid, callingPid, pid);
3262 pid = callingPid;
3263 }
3264
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003265 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3266 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267
3268 if (pDesc == NULL) {
3269 lStatus = BAD_VALUE;
3270 goto Exit;
3271 }
3272
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003273 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003274 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003275 lStatus = NO_INIT;
3276 goto Exit;
3277 }
3278
Andy Hung6096dcd2019-03-13 13:20:30 -07003279 // check audio settings permission for global effects
3280 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3281 if (!settingsAllowed()) {
3282 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3283 lStatus = PERMISSION_DENIED;
3284 goto Exit;
3285 }
3286 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3287 if (!isAudioServerUid(callingUid)) {
3288 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3289 lStatus = PERMISSION_DENIED;
3290 goto Exit;
3291 }
3292
3293 if (io == AUDIO_IO_HANDLE_NONE) {
3294 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3295 lStatus = BAD_VALUE;
3296 goto Exit;
3297 }
3298 } else {
3299 // general sessionId.
3300
3301 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3302 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3303 lStatus = BAD_VALUE;
3304 goto Exit;
3305 }
3306
3307 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3308 // to prevent creating an effect when one doesn't actually have track with that session?
3309 }
3310
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003312 // Get the full effect descriptor from the uuid/type.
3313 // If the session is the output mix, prefer an auxiliary effect,
3314 // otherwise no preference.
3315 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3316 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3317 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3318 if (lStatus < 0) {
3319 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3320 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 }
3322
3323 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003324 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3326 lStatus = INVALID_OPERATION;
3327 goto Exit;
3328 }
3329
Eric Laurent59255e42011-07-27 19:49:51 -07003330 // check recording permission for visualizer
3331 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003332 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003333 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003334 lStatus = PERMISSION_DENIED;
3335 goto Exit;
3336 }
3337
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003339 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003340 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003341 // if the output returned by getOutputForEffect() is removed before we lock the
3342 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3343 // and we will exit safely
3344 io = AudioSystem::getOutputForEffect(&desc);
3345 ALOGV("createEffect got output %d", io);
3346 }
3347
3348 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349
3350 // If output is not specified try to find a matching audio session ID in one of the
3351 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003352 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3353 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003354 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3355 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003356 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003357 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003358 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3359 if (io == AUDIO_IO_HANDLE_NONE) {
3360 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003362 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003363 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003364 }
Andy Hung444bb552019-03-14 17:06:39 -07003365
3366 // If you wish to create a Record preprocessing AudioEffect in Java,
3367 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3368 // Otherwise it will fail when created on a Playback thread by legacy
3369 // handling below. Ditto with Mmap, the associated Mmap track must be created
3370 // before creating the AudioEffect or the io handle must be specified.
3371 //
3372 // Detect if the effect is created after an AudioRecord is destroyed.
3373 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3374 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3375 " for session %d no longer exists",
3376 __func__, desc.name, sessionId);
3377 lStatus = PERMISSION_DENIED;
3378 goto Exit;
3379 }
3380
3381 // Legacy handling of creating an effect on an expired or made-up
3382 // session id. We think that it is a Playback effect.
3383 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003384 // If no output thread contains the requested session ID, default to
3385 // first output. The effect chain will be moved to the correct output
3386 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003387 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003388 io = mPlaybackThreads.keyAt(0);
3389 }
Steve Block3856b092011-10-20 11:56:00 +01003390 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003391 } else if (checkPlaybackThread_l(io) != nullptr) {
3392 // allow only one effect chain per sessionId on mPlaybackThreads.
3393 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3394 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3395 if (io == checkIo) continue;
3396 const uint32_t sessionType =
3397 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3398 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3399 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3400 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3401 android_errorWriteLog(0x534e4554, "123237974");
3402 lStatus = BAD_VALUE;
3403 goto Exit;
3404 }
3405 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003406 }
3407 ThreadBase *thread = checkRecordThread_l(io);
3408 if (thread == NULL) {
3409 thread = checkPlaybackThread_l(io);
3410 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003411 thread = checkMmapThread_l(io);
3412 if (thread == NULL) {
3413 ALOGE("createEffect() unknown output thread");
3414 lStatus = BAD_VALUE;
3415 goto Exit;
3416 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003417 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003418 } else {
3419 // Check if one effect chain was awaiting for an effect to be created on this
3420 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003421 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003422 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003423 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003424 thread->addEffectChain_l(chain);
3425 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003426 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003427
Eric Laurent021cf962014-05-13 10:18:14 -07003428 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003430 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003431 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003432 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003433 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003434 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003435 // remove local strong reference to Client with mClientLock held
3436 Mutex::Autolock _cl(mClientLock);
3437 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003438 } else {
3439 // handle must be valid here, but check again to be safe.
3440 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003441 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442 }
3443
Eric Laurent6c796322019-04-09 14:13:17 -07003444 if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
3445 // Check CPU and memory usage
3446 sp<EffectModule> effect = handle->effect().promote();
3447 if (effect != nullptr) {
3448 status_t rStatus = effect->updatePolicyState();
3449 if (rStatus != NO_ERROR) {
3450 lStatus = rStatus;
3451 }
3452 }
3453 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003454 handle.clear();
3455 }
3456
Mathias Agopian65ab4712010-07-14 17:59:35 -07003457Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003458 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003459 return handle;
3460}
3461
Glenn Kastend848eb42016-03-08 13:42:11 -08003462status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003463 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003464{
Steve Block3856b092011-10-20 11:56:00 +01003465 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003466 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003467 Mutex::Autolock _l(mLock);
3468 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003469 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003470 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003471 }
Eric Laurentde070132010-07-13 04:45:46 -07003472 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3473 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003474 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003475 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476 }
Eric Laurentde070132010-07-13 04:45:46 -07003477 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3478 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003479 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003480 return BAD_VALUE;
3481 }
3482
3483 Mutex::Autolock _dl(dstThread->mLock);
3484 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003485 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486}
3487
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003488
3489void AudioFlinger::setEffectSuspended(int effectId,
3490 audio_session_t sessionId,
3491 bool suspended)
3492{
3493 Mutex::Autolock _l(mLock);
3494
3495 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3496 if (thread == nullptr) {
3497 return;
3498 }
3499 Mutex::Autolock _sl(thread->mLock);
3500 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3501 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3502}
3503
3504
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003505// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003506status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003507 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003508 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003509{
Steve Block3856b092011-10-20 11:56:00 +01003510 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003511 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003512
Eric Laurent59255e42011-07-27 19:49:51 -07003513 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003514 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003515 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003516 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003517 return INVALID_OPERATION;
3518 }
3519
Eric Laurent4c415062016-06-17 16:14:16 -07003520 // Check whether the destination thread and all effects in the chain are compatible
3521 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003522 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003523 " destination thread %p is not compatible with effects in the chain",
3524 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003525 return INVALID_OPERATION;
3526 }
3527
Eric Laurent39e94f82010-07-28 01:32:47 -07003528 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003529 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003530 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003531 // removed.
3532 srcThread->removeEffectChain_l(chain);
3533
3534 // transfer all effects one by one so that new effect chain is created on new thread with
3535 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003536 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003537 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003538 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003539 Vector< sp<EffectModule> > removed;
3540 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003541 while (effect != 0) {
3542 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003543 removed.add(effect);
3544 status = dstThread->addEffect_l(effect);
3545 if (status != NO_ERROR) {
3546 break;
3547 }
Eric Laurentec35a142011-10-05 17:42:25 -07003548 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3549 if (effect->state() == EffectModule::ACTIVE ||
3550 effect->state() == EffectModule::STOPPING) {
3551 effect->start();
3552 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003553 // if the move request is not received from audio policy manager, the effect must be
3554 // re-registered with the new strategy and output
3555 if (dstChain == 0) {
3556 dstChain = effect->chain().promote();
3557 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003558 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003559 status = NO_INIT;
3560 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003561 }
3562 strategy = dstChain->strategy();
3563 }
Eric Laurentde070132010-07-13 04:45:46 -07003564 effect = chain->getEffectFromId_l(0);
3565 }
3566
Eric Laurent5baf2af2013-09-12 17:37:00 -07003567 if (status != NO_ERROR) {
3568 for (size_t i = 0; i < removed.size(); i++) {
3569 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003570 }
3571 }
3572
3573 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574}
3575
Eric Laurent6c796322019-04-09 14:13:17 -07003576status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3577 const sp<PlaybackThread>& dstThread,
3578 sp<PlaybackThread> *srcThread)
3579{
3580 status_t status = NO_ERROR;
3581 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003582 sp<PlaybackThread> thread =
3583 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003584
3585 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3586 Mutex::Autolock _dl(dstThread->mLock);
3587 Mutex::Autolock _sl(thread->mLock);
3588 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3589 sp<EffectChain> dstChain;
3590 if (srcChain == 0) {
3591 return INVALID_OPERATION;
3592 }
3593
3594 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3595 if (effect == 0) {
3596 return INVALID_OPERATION;
3597 }
3598 thread->removeEffect_l(effect);
3599 status = dstThread->addEffect_l(effect);
3600 if (status != NO_ERROR) {
3601 thread->addEffect_l(effect);
3602 status = INVALID_OPERATION;
3603 goto Exit;
3604 }
3605
3606 dstChain = effect->chain().promote();
3607 if (dstChain == 0) {
3608 thread->addEffect_l(effect);
3609 status = INVALID_OPERATION;
3610 }
3611
3612Exit:
3613 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3614 if (effect->state() == EffectModule::ACTIVE ||
3615 effect->state() == EffectModule::STOPPING) {
3616 effect->start();
3617 }
3618 }
3619
3620 if (status == NO_ERROR && srcThread != nullptr) {
3621 *srcThread = thread;
3622 }
3623 return status;
3624}
3625
Eric Laurent5baf2af2013-09-12 17:37:00 -07003626bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003627{
3628 if (mGlobalEffectEnableTime != 0 &&
3629 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3630 return true;
3631 }
3632
3633 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3634 sp<EffectChain> ec =
3635 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003636 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003637 return true;
3638 }
3639 }
3640 return false;
3641}
3642
Eric Laurent5baf2af2013-09-12 17:37:00 -07003643void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003644{
3645 Mutex::Autolock _l(mLock);
3646
3647 mGlobalEffectEnableTime = systemTime();
3648
3649 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3650 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3651 if (t->mType == ThreadBase::OFFLOAD) {
3652 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3653 }
3654 }
3655
3656}
3657
Eric Laurentaaa44472014-09-12 17:41:50 -07003658status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3659{
Eric Laurentd8365c52017-07-16 15:27:05 -07003660 // clear possible suspended state before parking the chain so that it starts in default state
3661 // when attached to a new record thread
3662 chain->setEffectSuspended_l(FX_IID_AEC, false);
3663 chain->setEffectSuspended_l(FX_IID_NS, false);
3664
Glenn Kastend848eb42016-03-08 13:42:11 -08003665 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003666 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003667 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003668 if (index >= 0) {
3669 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3670 return ALREADY_EXISTS;
3671 }
3672 mOrphanEffectChains.add(session, chain);
3673 return NO_ERROR;
3674}
3675
3676sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3677{
3678 sp<EffectChain> chain;
3679 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003680 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003681 if (index >= 0) {
3682 chain = mOrphanEffectChains.valueAt(index);
3683 mOrphanEffectChains.removeItemsAt(index);
3684 }
3685 return chain;
3686}
3687
3688bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3689{
3690 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003691 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003692 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003693 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003694 if (index >= 0) {
3695 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003696 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003697 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003698 mOrphanEffectChains.removeItemsAt(index);
3699 }
3700 return true;
3701 }
3702 return false;
3703}
3704
3705
Mathias Agopian65ab4712010-07-14 17:59:35 -07003706// ----------------------------------------------------------------------------
3707
3708status_t AudioFlinger::onTransact(
3709 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3710{
3711 return BnAudioFlinger::onTransact(code, data, reply, flags);
3712}
3713
Glenn Kasten63238ef2015-03-02 15:50:29 -08003714} // namespace android