blob: 090705337ad47b363fe620b951a5635f13d63145 [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>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070034#include <media/audiohal/DeviceHalInterface.h>
35#include <media/audiohal/DevicesFactoryHalInterface.h>
36#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070037#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070038#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070039#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <utils/String16.h>
41#include <utils/threads.h>
42
Steven Morelandf0c02ce2018-02-23 14:53:55 -080043#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <cutils/properties.h>
45
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
Mathias Agopian65ab4712010-07-14 17:59:35 -070048#include "AudioFlinger.h"
49
Andy Hung6770c6f2015-04-07 13:43:36 -070050#include <media/AudioResamplerPublic.h>
51
Mikhail Naganov9fe94012016-10-14 14:57:40 -070052#include <system/audio_effects/effect_visualizer.h>
53#include <system/audio_effects/effect_ns.h>
54#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055
Glenn Kasten3b21c502011-12-15 09:52:39 -080056#include <audio_utils/primitives.h>
Andy Hung7ad78182018-05-10 20:54:29 -070057#include <audio_utils/string.h>
Glenn Kasten3b21c502011-12-15 09:52:39 -080058
Eric Laurentfeb0db62011-07-22 09:04:31 -070059#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080060
Glenn Kasten9e58b552013-01-18 15:09:48 -080061#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070062#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080063#include <media/nbaio/Pipe.h>
64#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070065#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080066#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070067#include <mediautils/ServiceUtilities.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070068#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080069
rago3bd1c872016-09-26 12:58:14 -070070//#define BUFLOG_NDEBUG 0
71#include <BufLog.h>
72
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080073#include "TypedLogger.h"
74
Mathias Agopian65ab4712010-07-14 17:59:35 -070075// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
John Grossman1c345192012-03-27 14:00:17 -070077// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
Eric Laurentde070132010-07-13 04:45:46 -070089
Mathias Agopian65ab4712010-07-14 17:59:35 -070090namespace android {
91
Glenn Kastenec1d6b52011-12-12 09:04:45 -080092static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
93static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070094static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070095static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070096
Glenn Kasten58912562012-04-03 10:45:00 -070097
John Grossman4ff14ba2012-02-08 16:37:41 -080098nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080099
Eric Laurent81784c32012-11-19 14:55:58 -0800100uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700101
Eric Laurentfc235202016-12-20 18:48:17 -0800102
Glenn Kasten46909e72013-02-26 09:20:22 -0800103#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800104bool AudioFlinger::mTeeSinkInputEnabled = false;
105bool AudioFlinger::mTeeSinkOutputEnabled = false;
106bool AudioFlinger::mTeeSinkTrackEnabled = false;
107
108size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
109size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
110size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800111#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800112
Eric Laurent813e2a72013-08-31 12:59:48 -0700113// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
114// we define a minimum time during which a global effect is considered enabled.
115static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
116
Eric Laurentfc235202016-12-20 18:48:17 -0800117Mutex gLock;
118wp<AudioFlinger> gAudioFlinger;
119
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700120// Keep a strong reference to media.log service around forever.
121// The service is within our parent process so it can never die in a way that we could observe.
122// These two variables are const after initialization.
123static sp<IBinder> sMediaLogServiceAsBinder;
124static sp<IMediaLogService> sMediaLogService;
125
126static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
127
128static void sMediaLogInit()
129{
130 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
131 if (sMediaLogServiceAsBinder != 0) {
132 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
133 }
134}
135
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136// ----------------------------------------------------------------------------
137
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700138std::string formatToString(audio_format_t format) {
139 std::string result;
140 FormatConverter::toString(format, result);
141 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800142}
143
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144// ----------------------------------------------------------------------------
145
146AudioFlinger::AudioFlinger()
147 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800148 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800149 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800150 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700151 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800152 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800153 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700154 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800155 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700156 mBtNrecIsOff(false),
157 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700158 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800159 mTotalMemory(0),
160 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700161 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700162 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700163 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700164{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700165 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
166 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
167 // zero ID has a special meaning, so unavailable
168 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
169 }
170
Glenn Kastenae0cff12016-02-24 13:57:49 -0800171 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800172 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800173 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
174 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700175 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800176 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700177
Wei Jia3f273d12015-11-24 09:06:49 -0800178 // reset battery stats.
179 // if the audio service has crashed, battery stats could be left
180 // in bad state, reset the state upon service start.
181 BatteryNotifier::getInstance().noteResetAudio();
182
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700183 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700184 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
185
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800186 mMediaLogNotifier->run("MediaLogNotifier");
187
Glenn Kasten46909e72013-02-26 09:20:22 -0800188#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800189 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800190 (void) property_get("ro.debuggable", value, "0");
191 int debuggable = atoi(value);
192 int teeEnabled = 0;
193 if (debuggable) {
194 (void) property_get("af.tee", value, "0");
195 teeEnabled = atoi(value);
196 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800197 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700198 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700200 }
201 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800202 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700203 }
204 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800205 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700206 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800207#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700208}
209
210void AudioFlinger::onFirstRef()
211{
Eric Laurent93575202011-01-18 18:39:02 -0800212 Mutex::Autolock _l(mLock);
213
Dima Zavin799a70e2011-04-18 16:57:27 -0700214 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800215 char val_str[PROPERTY_VALUE_MAX] = { 0 };
216 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
217 uint32_t int_val;
218 if (1 == sscanf(val_str, "%u", &int_val)) {
219 mStandbyTimeInNsecs = milliseconds(int_val);
220 ALOGI("Using %u mSec as standby time.", int_val);
221 } else {
222 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
223 ALOGI("Using default %u mSec as standby time.",
224 (uint32_t)(mStandbyTimeInNsecs / 1000000));
225 }
226 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700227
Eric Laurenta4c5a552012-03-29 10:12:40 -0700228 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800229
230 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231}
232
233AudioFlinger::~AudioFlinger()
234{
235 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700236 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700237 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700238 }
239 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700240 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700241 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700242 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700243
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800244 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
245 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700246 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700248
249 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700250 if (sMediaLogService != 0) {
251 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
252 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
253 mUnregisteredWriters.pop();
254 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700255 }
256 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700257}
258
Eric Laurentfc235202016-12-20 18:48:17 -0800259//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800260__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800261status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
262 const audio_attributes_t *attr,
263 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700264 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800265 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800266 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800267 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700268 sp<MmapStreamInterface>& interface,
269 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800270{
271 sp<AudioFlinger> af;
272 {
273 Mutex::Autolock _l(gLock);
274 af = gAudioFlinger.promote();
275 }
276 status_t ret = NO_INIT;
277 if (af != 0) {
278 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800279 direction, attr, config, client, deviceId,
280 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800281 }
282 return ret;
283}
284
Eric Laurent6acd1d42017-01-04 14:23:29 -0800285status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
286 const audio_attributes_t *attr,
287 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700288 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800289 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800290 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800291 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700292 sp<MmapStreamInterface>& interface,
293 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800294{
295 status_t ret = initCheck();
296 if (ret != NO_ERROR) {
297 return ret;
298 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800299 audio_session_t actualSessionId = *sessionId;
300 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
301 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
302 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800303 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700304 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800305 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
306 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
307 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
308 fullConfig.sample_rate = config->sample_rate;
309 fullConfig.channel_mask = config->channel_mask;
310 fullConfig.format = config->format;
311 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800312 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200313 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800314 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800315 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
316 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700317 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800318 } else {
319 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800320 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800321 client.clientPid,
322 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800323 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800324 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700325 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800326 }
327 if (ret != NO_ERROR) {
328 return ret;
329 }
330
331 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
332 // audio policy manager and we can retrieve it
333 sp<MmapThread> thread = mMmapThreads.valueFor(io);
334 if (thread != 0) {
335 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800336 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700337 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800338 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800339 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700340 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Phil Burk4e1af9f2018-01-03 15:54:35 -0800341 AudioSystem::releaseOutput(io, streamType, actualSessionId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700342 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800343 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700344 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800345 ret = NO_INIT;
346 }
347
348 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
349
Eric Laurentfc235202016-12-20 18:48:17 -0800350 return ret;
351}
352
Eric Laurenta4c5a552012-03-29 10:12:40 -0700353static const char * const audio_interfaces[] = {
354 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
355 AUDIO_HARDWARE_MODULE_ID_A2DP,
356 AUDIO_HARDWARE_MODULE_ID_USB,
357};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700358
Phil Burk062e67a2015-02-11 13:40:50 -0800359AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700360 audio_module_handle_t module,
361 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700362{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700363 // if module is 0, the request comes from an old policy manager and we should load
364 // well known modules
365 if (module == 0) {
366 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700367 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700368 loadHwModule_l(audio_interfaces[i]);
369 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700370 // then try to find a module supporting the requested device.
371 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
372 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700373 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
374 uint32_t supportedDevices;
375 if (dev->getSupportedDevices(&supportedDevices) == OK &&
376 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700377 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700378 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700379 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700380 } else {
381 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700382 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
383 if (audioHwDevice != NULL) {
384 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700385 }
386 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700387
Dima Zavin799a70e2011-04-18 16:57:27 -0700388 return NULL;
389}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390
Glenn Kasten0f11b512014-01-31 16:18:54 -0800391void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392{
393 const size_t SIZE = 256;
394 char buffer[SIZE];
395 String8 result;
396
397 result.append("Clients:\n");
398 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800399 sp<Client> client = mClients.valueAt(i).promote();
400 if (client != 0) {
401 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
402 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403 }
404 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700405
Eric Laurentd1b28d42013-09-18 18:47:13 -0700406 result.append("Notification Clients:\n");
407 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
408 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
409 result.append(buffer);
410 }
411
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700412 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800413 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700414 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
415 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800416 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700417 result.append(buffer);
418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420}
421
422
Glenn Kasten0f11b512014-01-31 16:18:54 -0800423void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424{
425 const size_t SIZE = 256;
426 char buffer[SIZE];
427 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800428 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429
John Grossman4ff14ba2012-02-08 16:37:41 -0800430 snprintf(buffer, SIZE, "Hardware status: %d\n"
431 "Standby Time mSec: %u\n",
432 hardwareStatus,
433 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434 result.append(buffer);
435 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436}
437
Glenn Kasten0f11b512014-01-31 16:18:54 -0800438void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439{
440 const size_t SIZE = 256;
441 char buffer[SIZE];
442 String8 result;
443 snprintf(buffer, SIZE, "Permission Denial: "
444 "can't dump AudioFlinger from pid=%d, uid=%d\n",
445 IPCThreadState::self()->getCallingPid(),
446 IPCThreadState::self()->getCallingUid());
447 result.append(buffer);
448 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449}
450
Eric Laurent81784c32012-11-19 14:55:58 -0800451bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452{
453 bool locked = false;
454 for (int i = 0; i < kDumpLockRetries; ++i) {
455 if (mutex.tryLock() == NO_ERROR) {
456 locked = true;
457 break;
458 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800459 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460 }
461 return locked;
462}
463
464status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
465{
Glenn Kasten44deb052012-02-05 18:09:08 -0800466 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 dumpPermissionDenial(fd, args);
468 } else {
469 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800470 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 if (!hardwareLocked) {
472 String8 result(kHardwareLockedString);
473 write(fd, result.string(), result.size());
474 } else {
475 mHardwareLock.unlock();
476 }
477
Eric Laurent81784c32012-11-19 14:55:58 -0800478 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479
480 // failed to lock - AudioFlinger is probably deadlocked
481 if (!locked) {
482 String8 result(kDeadlockedString);
483 write(fd, result.string(), result.size());
484 }
485
Eric Laurent021cf962014-05-13 10:18:14 -0700486 bool clientLocked = dumpTryLock(mClientLock);
487 if (!clientLocked) {
488 String8 result(kClientLockedString);
489 write(fd, result.string(), result.size());
490 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700491
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700492 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700493 mEffectsFactoryHal->dumpEffects(fd);
494 } else {
495 String8 result(kNoEffectsFactory);
496 write(fd, result.string(), result.size());
497 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700498
Mathias Agopian65ab4712010-07-14 17:59:35 -0700499 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700500 if (clientLocked) {
501 mClientLock.unlock();
502 }
503
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504 dumpInternals(fd, args);
505
506 // dump playback threads
507 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
508 mPlaybackThreads.valueAt(i)->dump(fd, args);
509 }
510
511 // dump record threads
512 for (size_t i = 0; i < mRecordThreads.size(); i++) {
513 mRecordThreads.valueAt(i)->dump(fd, args);
514 }
515
Eric Laurent6acd1d42017-01-04 14:23:29 -0800516 // dump mmap threads
517 for (size_t i = 0; i < mMmapThreads.size(); i++) {
518 mMmapThreads.valueAt(i)->dump(fd, args);
519 }
520
Eric Laurentaaa44472014-09-12 17:41:50 -0700521 // dump orphan effect chains
522 if (mOrphanEffectChains.size() != 0) {
523 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
524 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
525 mOrphanEffectChains.valueAt(i)->dump(fd, args);
526 }
527 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700528 // dump all hardware devs
529 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700530 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
531 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700532 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700533
Glenn Kasten46909e72013-02-26 09:20:22 -0800534#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700535 // dump the serially shared record tee sink
536 if (mRecordTeeSource != 0) {
Glenn Kasten5b2191a2016-08-19 11:44:47 -0700537 dumpTee(fd, mRecordTeeSource, AUDIO_IO_HANDLE_NONE, 'C');
Glenn Kastend06785b2012-09-30 12:29:28 -0700538 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800539#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700540
rago3bd1c872016-09-26 12:58:14 -0700541 BUFLOG_RESET;
542
Glenn Kastend65d73c2012-06-22 17:21:07 -0700543 if (locked) {
544 mLock.unlock();
545 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800546
547 // append a copy of media.log here by forwarding fd to it, but don't attempt
548 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700549 if (sMediaLogServiceAsBinder != 0) {
550 dprintf(fd, "\nmedia.log:\n");
551 Vector<String16> args;
552 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800553 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700554
555 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700556 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700557 bool unreachableMemory = false;
558 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700559 if (arg == String16("-m")) {
560 dumpMem = true;
561 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700562 unreachableMemory = true;
563 }
564 }
565
Andy Hung07b745e2016-05-23 16:21:07 -0700566 if (dumpMem) {
567 dprintf(fd, "\nDumping memory:\n");
568 std::string s = dumpMemoryAddresses(100 /* limit */);
569 write(fd, s.c_str(), s.size());
570 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700571 if (unreachableMemory) {
572 dprintf(fd, "\nDumping unreachable memory:\n");
573 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700574 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700575 write(fd, s.c_str(), s.size());
576 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 }
578 return NO_ERROR;
579}
580
Eric Laurent021cf962014-05-13 10:18:14 -0700581sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800582{
Eric Laurent021cf962014-05-13 10:18:14 -0700583 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800584 // If pid is already in the mClients wp<> map, then use that entry
585 // (for which promote() is always != 0), otherwise create a new entry and Client.
586 sp<Client> client = mClients.valueFor(pid).promote();
587 if (client == 0) {
588 client = new Client(this, pid);
589 mClients.add(pid, client);
590 }
591
592 return client;
593}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594
Glenn Kasten9e58b552013-01-18 15:09:48 -0800595sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
596{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700597 // If there is no memory allocated for logs, return a dummy writer that does nothing.
598 // Similarly if we can't contact the media.log service, also return a dummy writer.
599 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800600 return new NBLog::Writer();
601 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700602 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
603 // If allocation fails, consult the vector of previously unregistered writers
604 // and garbage-collect one or more them until an allocation succeeds
605 if (shared == 0) {
606 Mutex::Autolock _l(mUnregisteredWritersLock);
607 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
608 {
609 // Pick the oldest stale writer to garbage-collect
610 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
611 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700612 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700613 // Now the media.log remote reference to IMemory is gone. When our last local
614 // reference to IMemory also drops to zero at end of this block,
615 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
616 }
617 // Re-attempt the allocation
618 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
619 if (shared != 0) {
620 goto success;
621 }
622 }
623 // Even after garbage-collecting all old writers, there is still not enough memory,
624 // so return a dummy writer
625 return new NBLog::Writer();
626 }
627success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800628 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
629 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
630 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700631 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800632 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800633}
634
635void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
636{
Glenn Kasten685ef092013-02-04 08:15:34 -0800637 if (writer == 0) {
638 return;
639 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800640 sp<IMemory> iMemory(writer->getIMemory());
641 if (iMemory == 0) {
642 return;
643 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700644 // Rather than removing the writer immediately, append it to a queue of old writers to
645 // be garbage-collected later. This allows us to continue to view old logs for a while.
646 Mutex::Autolock _l(mUnregisteredWritersLock);
647 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800648}
649
Mathias Agopian65ab4712010-07-14 17:59:35 -0700650// IAudioFlinger interface
651
Eric Laurent21da6472017-11-09 16:29:26 -0800652sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
653 CreateTrackOutput& output,
654 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700655{
656 sp<PlaybackThread::Track> track;
657 sp<TrackHandle> trackHandle;
658 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800660 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800661 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662
Eric Laurent21da6472017-11-09 16:29:26 -0800663 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700664 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800665 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700666 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800667 ALOGW_IF(clientUid != callingUid,
668 "%s uid %d tried to pass itself off as %d",
669 __FUNCTION__, callingUid, clientUid);
670 clientUid = callingUid;
671 updatePid = true;
672 }
673 pid_t clientPid = input.clientInfo.clientPid;
674 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700675 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800676 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700677 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800678 __func__, callingUid, callingPid, clientPid);
679 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700680 }
681
Eric Laurent21da6472017-11-09 16:29:26 -0800682 audio_session_t sessionId = input.sessionId;
683 if (sessionId == AUDIO_SESSION_ALLOCATE) {
684 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800685 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
686 lStatus = BAD_VALUE;
687 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800688 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800689
Eric Laurent21da6472017-11-09 16:29:26 -0800690 output.sessionId = sessionId;
691 output.outputId = AUDIO_IO_HANDLE_NONE;
692 output.selectedDeviceId = input.selectedDeviceId;
693
694 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200695 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800696 &output.selectedDeviceId, &portId);
697
698 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
699 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
700 goto Exit;
701 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800702 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
703 // but if someone uses binder directly they could bypass that and cause us to crash
704 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000705 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 lStatus = BAD_VALUE;
707 goto Exit;
708 }
709
Glenn Kasten53b5d092014-02-05 10:00:23 -0800710 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800711 if (!audio_is_output_channel(input.config.channel_mask)) {
712 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800713 lStatus = BAD_VALUE;
714 goto Exit;
715 }
716
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700717 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800718 if (!audio_is_valid_format(input.config.format)) {
719 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700720 lStatus = BAD_VALUE;
721 goto Exit;
722 }
723
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724 {
725 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800726 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700727 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800728 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729 lStatus = BAD_VALUE;
730 goto Exit;
731 }
732
Eric Laurent21da6472017-11-09 16:29:26 -0800733 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734
Glenn Kastene848bd92014-03-13 15:00:32 -0700735 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800736 // check if an effect chain with the same session ID is present on another
737 // output thread and move it here.
738 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
739 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
740 if (mPlaybackThreads.keyAt(i) != output.outputId) {
741 uint32_t sessions = t->hasAudioSession(sessionId);
742 if (sessions & ThreadBase::EFFECT_SESSION) {
743 effectThread = t.get();
744 break;
Eric Laurentde070132010-07-13 04:45:46 -0700745 }
746 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 }
Eric Laurent21da6472017-11-09 16:29:26 -0800748 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749
Eric Laurent21da6472017-11-09 16:29:26 -0800750 output.sampleRate = input.config.sample_rate;
751 output.frameCount = input.frameCount;
752 output.notificationFrameCount = input.notificationFrameCount;
753 output.flags = input.flags;
754
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700755 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
756 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800757 &output.frameCount, &output.notificationFrameCount,
758 input.notificationsPerBuffer, input.speed,
759 input.sharedBuffer, sessionId, &output.flags,
760 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800761 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700762 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700763
Eric Laurent21da6472017-11-09 16:29:26 -0800764 output.afFrameCount = thread->frameCount();
765 output.afSampleRate = thread->sampleRate();
766 output.afLatencyMs = thread->latency();
767
Eric Laurent39e94f82010-07-28 01:32:47 -0700768 // move effect chain to this output thread if an effect on same session was waiting
769 // for a track to be created
770 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700771 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700772 Mutex::Autolock _dl(thread->mLock);
773 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800774 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700775 }
Eric Laurenta011e352012-03-29 15:51:43 -0700776
777 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700778 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800779 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700780 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700781 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700782 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700783 } else {
784 mPendingSyncEvents[i]->cancel();
785 }
Eric Laurenta011e352012-03-29 15:51:43 -0700786 mPendingSyncEvents.removeAt(i);
787 i--;
788 }
789 }
790 }
Glenn Kastene198c362013-08-13 09:13:36 -0700791
Eric Laurent21da6472017-11-09 16:29:26 -0800792 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793 }
Glenn Kastene198c362013-08-13 09:13:36 -0700794
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700795 if (lStatus != NO_ERROR) {
796 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700797 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700798 // Don't hold mClientLock when releasing the reference on the track as the
799 // destructor will acquire it.
800 {
801 Mutex::Autolock _cl(mClientLock);
802 client.clear();
803 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700805 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806 }
807
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700808 // return handle to client
809 trackHandle = new TrackHandle(track);
810
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800812 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
813 AudioSystem::releaseOutput(output.outputId, streamType, sessionId);
814 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700815 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 return trackHandle;
817}
818
Glenn Kasten2c073da2016-02-26 09:14:08 -0800819uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820{
821 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800822 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800824 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825 return 0;
826 }
827 return thread->sampleRate();
828}
829
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800830audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831{
832 Mutex::Autolock _l(mLock);
833 PlaybackThread *thread = checkPlaybackThread_l(output);
834 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000835 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800836 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837 }
838 return thread->format();
839}
840
Glenn Kasten2c073da2016-02-26 09:14:08 -0800841size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842{
843 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800844 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800846 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847 return 0;
848 }
Glenn Kasten58912562012-04-03 10:45:00 -0700849 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
850 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851 return thread->frameCount();
852}
853
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700854size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
855{
856 Mutex::Autolock _l(mLock);
857 ThreadBase *thread = checkThread_l(ioHandle);
858 if (thread == NULL) {
859 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
860 return 0;
861 }
862 return thread->frameCountHAL();
863}
864
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800865uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866{
867 Mutex::Autolock _l(mLock);
868 PlaybackThread *thread = checkPlaybackThread_l(output);
869 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800870 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871 return 0;
872 }
873 return thread->latency();
874}
875
876status_t AudioFlinger::setMasterVolume(float value)
877{
Eric Laurenta1884f92011-08-23 08:25:03 -0700878 status_t ret = initCheck();
879 if (ret != NO_ERROR) {
880 return ret;
881 }
882
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883 // check calling permissions
884 if (!settingsAllowed()) {
885 return PERMISSION_DENIED;
886 }
887
Eric Laurenta4c5a552012-03-29 10:12:40 -0700888 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700889 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700890
John Grossmanee578c02012-07-23 17:05:46 -0700891 // Set master volume in the HALs which support it.
892 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
893 AutoMutex lock(mHardwareLock);
894 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800895
John Grossmanee578c02012-07-23 17:05:46 -0700896 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
897 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700898 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800899 }
John Grossmanee578c02012-07-23 17:05:46 -0700900 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902
John Grossmanee578c02012-07-23 17:05:46 -0700903 // Now set the master volume in each playback thread. Playback threads
904 // assigned to HALs which do not have master volume support will apply
905 // master volume during the mix operation. Threads with HALs which do
906 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700907 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
908 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
909 continue;
910 }
John Grossmanee578c02012-07-23 17:05:46 -0700911 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700912 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913
914 return NO_ERROR;
915}
916
Glenn Kastenf78aee72012-01-04 11:00:47 -0800917status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918{
Eric Laurenta1884f92011-08-23 08:25:03 -0700919 status_t ret = initCheck();
920 if (ret != NO_ERROR) {
921 return ret;
922 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923
924 // check calling permissions
925 if (!settingsAllowed()) {
926 return PERMISSION_DENIED;
927 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800928 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000929 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 return BAD_VALUE;
931 }
932
933 { // scope for the lock
934 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700935 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700936 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700937 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 mHardwareStatus = AUDIO_HW_IDLE;
939 }
940
941 if (NO_ERROR == ret) {
942 Mutex::Autolock _l(mLock);
943 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800944 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700945 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 }
947
948 return ret;
949}
950
951status_t AudioFlinger::setMicMute(bool state)
952{
Eric Laurenta1884f92011-08-23 08:25:03 -0700953 status_t ret = initCheck();
954 if (ret != NO_ERROR) {
955 return ret;
956 }
957
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958 // check calling permissions
959 if (!settingsAllowed()) {
960 return PERMISSION_DENIED;
961 }
962
963 AutoMutex lock(mHardwareLock);
964 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700965 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700966 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
967 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700968 if (result != NO_ERROR) {
969 ret = result;
970 }
971 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972 mHardwareStatus = AUDIO_HW_IDLE;
973 return ret;
974}
975
976bool AudioFlinger::getMicMute() const
977{
Eric Laurenta1884f92011-08-23 08:25:03 -0700978 status_t ret = initCheck();
979 if (ret != NO_ERROR) {
980 return false;
981 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800982 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700983 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800984 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800986 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700987 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
988 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800989 if (result == NO_ERROR) {
990 mute = mute && state;
991 }
992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800994
995 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996}
997
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800998void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
999{
1000 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1001
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001002 AutoMutex lock(mLock);
1003 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001004 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1005 }
1006 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1007 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001008 }
1009}
1010
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011status_t AudioFlinger::setMasterMute(bool muted)
1012{
John Grossmand8f178d2012-07-20 14:51:35 -07001013 status_t ret = initCheck();
1014 if (ret != NO_ERROR) {
1015 return ret;
1016 }
1017
Mathias Agopian65ab4712010-07-14 17:59:35 -07001018 // check calling permissions
1019 if (!settingsAllowed()) {
1020 return PERMISSION_DENIED;
1021 }
1022
John Grossmanee578c02012-07-23 17:05:46 -07001023 Mutex::Autolock _l(mLock);
1024 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001025
John Grossmanee578c02012-07-23 17:05:46 -07001026 // Set master mute in the HALs which support it.
1027 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1028 AutoMutex lock(mHardwareLock);
1029 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001030
John Grossmanee578c02012-07-23 17:05:46 -07001031 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1032 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001033 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001034 }
John Grossmanee578c02012-07-23 17:05:46 -07001035 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001036 }
1037
John Grossmanee578c02012-07-23 17:05:46 -07001038 // Now set the master mute in each playback thread. Playback threads
1039 // assigned to HALs which do not have master mute support will apply master
1040 // mute during the mix operation. Threads with HALs which do support master
1041 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001042 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1043 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1044 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001045 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046
1047 return NO_ERROR;
1048}
1049
1050float AudioFlinger::masterVolume() const
1051{
Glenn Kasten98067102011-12-13 11:47:54 -08001052 Mutex::Autolock _l(mLock);
1053 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054}
1055
1056bool AudioFlinger::masterMute() const
1057{
Glenn Kasten98067102011-12-13 11:47:54 -08001058 Mutex::Autolock _l(mLock);
1059 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060}
1061
John Grossman4ff14ba2012-02-08 16:37:41 -08001062float AudioFlinger::masterVolume_l() const
1063{
John Grossman4ff14ba2012-02-08 16:37:41 -08001064 return mMasterVolume;
1065}
1066
John Grossmand8f178d2012-07-20 14:51:35 -07001067bool AudioFlinger::masterMute_l() const
1068{
John Grossmanee578c02012-07-23 17:05:46 -07001069 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001070}
1071
Eric Laurent223fd5c2014-11-11 13:43:36 -08001072status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1073{
1074 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001075 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001076 return BAD_VALUE;
1077 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001078 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1079 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1080 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001081 return PERMISSION_DENIED;
1082 }
1083
1084 return NO_ERROR;
1085}
1086
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001087status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1088 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001089{
1090 // check calling permissions
1091 if (!settingsAllowed()) {
1092 return PERMISSION_DENIED;
1093 }
1094
Eric Laurent223fd5c2014-11-11 13:43:36 -08001095 status_t status = checkStreamType(stream);
1096 if (status != NO_ERROR) {
1097 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098 }
Eric Laurent98e38192018-02-15 18:31:53 -08001099 if (output == AUDIO_IO_HANDLE_NONE) {
1100 return BAD_VALUE;
1101 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001102 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103
1104 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001105 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1106 if (volumeInterface == NULL) {
1107 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108 }
Eric Laurent98e38192018-02-15 18:31:53 -08001109 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110
1111 return NO_ERROR;
1112}
1113
Glenn Kastenfff6d712012-01-12 16:38:12 -08001114status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115{
1116 // check calling permissions
1117 if (!settingsAllowed()) {
1118 return PERMISSION_DENIED;
1119 }
1120
Eric Laurent223fd5c2014-11-11 13:43:36 -08001121 status_t status = checkStreamType(stream);
1122 if (status != NO_ERROR) {
1123 return status;
1124 }
1125 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1126
1127 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001128 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 return BAD_VALUE;
1130 }
1131
Eric Laurent93575202011-01-18 18:39:02 -08001132 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001134 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1135 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1136 volumeInterfaces[i]->setStreamMute(stream, muted);
1137 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001138
1139 return NO_ERROR;
1140}
1141
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001142float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001143{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001144 status_t status = checkStreamType(stream);
1145 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 return 0.0f;
1147 }
Eric Laurent98e38192018-02-15 18:31:53 -08001148 if (output == AUDIO_IO_HANDLE_NONE) {
1149 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150 }
1151
Eric Laurent98e38192018-02-15 18:31:53 -08001152 AutoMutex lock(mLock);
1153 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1154 if (volumeInterface == NULL) {
1155 return 0.0f;
1156 }
1157
1158 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001159}
1160
Glenn Kastenfff6d712012-01-12 16:38:12 -08001161bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001163 status_t status = checkStreamType(stream);
1164 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001165 return true;
1166 }
1167
Glenn Kasten6637baa2012-01-09 09:40:36 -08001168 AutoMutex lock(mLock);
1169 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170}
1171
Eric Laurent054d9d32015-04-24 08:48:48 -07001172
1173void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1174{
1175 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1176 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1177 }
1178}
1179
Eric Laurentf1047e82018-04-16 19:18:20 -07001180// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1181// Some keys are used for audio routing and audio path configuration and should be reserved for use
1182// by audio policy and audio flinger for functional, privacy and security reasons.
1183void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1184{
1185 static const String8 kReservedParameters[] = {
1186 String8(AudioParameter::keyRouting),
1187 String8(AudioParameter::keySamplingRate),
1188 String8(AudioParameter::keyFormat),
1189 String8(AudioParameter::keyChannels),
1190 String8(AudioParameter::keyFrameCount),
1191 String8(AudioParameter::keyInputSource),
1192 String8(AudioParameter::keyMonoOutput),
1193 String8(AudioParameter::keyStreamConnect),
1194 String8(AudioParameter::keyStreamDisconnect),
1195 String8(AudioParameter::keyStreamSupportedFormats),
1196 String8(AudioParameter::keyStreamSupportedChannels),
1197 String8(AudioParameter::keyStreamSupportedSamplingRates),
1198 };
1199
Andy Hung4ef19fa2018-05-15 19:35:29 -07001200 if (isAudioServerUid(callingUid)) {
1201 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001202 }
1203
1204 AudioParameter param = AudioParameter(keyValuePairs);
1205 String8 value;
1206 for (auto& key : kReservedParameters) {
1207 if (param.get(key, value) == NO_ERROR) {
1208 ALOGW("%s: filtering key %s value %s from uid %d",
1209 __func__, key.string(), value.string(), callingUid);
1210 param.remove(key);
1211 }
1212 }
1213 keyValuePairs = param.toString();
1214}
1215
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001216status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217{
Eric Laurentf1047e82018-04-16 19:18:20 -07001218 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1219 ioHandle, keyValuePairs.string(),
1220 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001221
Mathias Agopian65ab4712010-07-14 17:59:35 -07001222 // check calling permissions
1223 if (!settingsAllowed()) {
1224 return PERMISSION_DENIED;
1225 }
1226
Eric Laurentf1047e82018-04-16 19:18:20 -07001227 String8 filteredKeyValuePairs = keyValuePairs;
1228 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1229
1230 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1231
Glenn Kasten142f5192014-03-25 17:44:59 -07001232 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1233 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001234 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001235 // result will remain NO_INIT if no audio device is present
1236 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001237 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001238 AutoMutex lock(mHardwareLock);
1239 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1240 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001241 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001242 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001243 // return success if at least one audio device accepts the parameters as not all
1244 // HALs are requested to support all parameters. If no audio device supports the
1245 // requested parameters, the last error is reported.
1246 if (final_result != NO_ERROR) {
1247 final_result = result;
1248 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001249 }
1250 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001251 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001252 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001253 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001254 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001255 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1256 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001257 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001258 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001259 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001260 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001261 }
1262 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001263 String8 screenState;
1264 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001265 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001266 if (isOff != (AudioFlinger::mScreenState & 1)) {
1267 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001268 }
1269 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001270 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271 }
1272
1273 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1274 // and the thread is exited once the lock is released
1275 sp<ThreadBase> thread;
1276 {
1277 Mutex::Autolock _l(mLock);
1278 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001279 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001280 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001281 if (thread == 0) {
1282 thread = checkMmapThread_l(ioHandle);
1283 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001284 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001285 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001286 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001287 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001288 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1289 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001290 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001291 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292 }
1293 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001294 if (thread != 0) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001295 return thread->setParameters(filteredKeyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296 }
1297 return BAD_VALUE;
1298}
1299
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001300String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001301{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001302 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1303 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001304
Eric Laurenta4c5a552012-03-29 10:12:40 -07001305 Mutex::Autolock _l(mLock);
1306
Glenn Kasten142f5192014-03-25 17:44:59 -07001307 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001308 String8 out_s8;
1309
Dima Zavin799a70e2011-04-18 16:57:27 -07001310 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001311 String8 s;
1312 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001313 {
1314 AutoMutex lock(mHardwareLock);
1315 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001316 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1317 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001318 mHardwareStatus = AUDIO_HW_IDLE;
1319 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001320 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001321 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001322 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001323 }
1324
Eric Laurent6acd1d42017-01-04 14:23:29 -08001325 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1326 if (thread == NULL) {
1327 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1328 if (thread == NULL) {
1329 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1330 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001331 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001332 }
1333 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001335 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001336}
1337
Glenn Kastendd8104c2012-07-02 12:42:44 -07001338size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1339 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001340{
Eric Laurenta1884f92011-08-23 08:25:03 -07001341 status_t ret = initCheck();
1342 if (ret != NO_ERROR) {
1343 return 0;
1344 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001345 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001346 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001347 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001348 return 0;
1349 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001350
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001351 AutoMutex lock(mHardwareLock);
1352 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001353 audio_config_t config, proposed;
1354 memset(&proposed, 0, sizeof(proposed));
1355 proposed.sample_rate = sampleRate;
1356 proposed.channel_mask = channelMask;
1357 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001358
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001359 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001360 size_t frames;
1361 for (;;) {
1362 // Note: config is currently a const parameter for get_input_buffer_size()
1363 // but we use a copy from proposed in case config changes from the call.
1364 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001365 status_t result = dev->getInputBufferSize(&config, &frames);
1366 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001367 break; // hal success, config is the result
1368 }
1369 // change one parameter of the configuration each iteration to a more "common" value
1370 // to see if the device will support it.
1371 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1372 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1373 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1374 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1375 } else {
1376 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1377 "format %#x, channelMask 0x%X",
1378 sampleRate, format, channelMask);
1379 break; // retries failed, break out of loop with frames == 0.
1380 }
1381 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001382 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001383 if (frames > 0 && config.sample_rate != sampleRate) {
1384 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1385 }
1386 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387}
1388
Glenn Kasten5f972c02014-01-13 09:59:31 -08001389uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001390{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391 Mutex::Autolock _l(mLock);
1392
1393 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1394 if (recordThread != NULL) {
1395 return recordThread->getInputFramesLost();
1396 }
1397 return 0;
1398}
1399
1400status_t AudioFlinger::setVoiceVolume(float value)
1401{
Eric Laurenta1884f92011-08-23 08:25:03 -07001402 status_t ret = initCheck();
1403 if (ret != NO_ERROR) {
1404 return ret;
1405 }
1406
Mathias Agopian65ab4712010-07-14 17:59:35 -07001407 // check calling permissions
1408 if (!settingsAllowed()) {
1409 return PERMISSION_DENIED;
1410 }
1411
1412 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001413 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001414 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001415 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416 mHardwareStatus = AUDIO_HW_IDLE;
1417
1418 return ret;
1419}
1420
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001421status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001422 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424 Mutex::Autolock _l(mLock);
1425
1426 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1427 if (playbackThread != NULL) {
1428 return playbackThread->getRenderPosition(halFrames, dspFrames);
1429 }
1430
1431 return BAD_VALUE;
1432}
1433
1434void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1435{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001437 if (client == 0) {
1438 return;
1439 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001440 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001441 {
1442 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001443 if (mNotificationClients.indexOfKey(pid) < 0) {
1444 sp<NotificationClient> notificationClient = new NotificationClient(this,
1445 client,
1446 pid);
1447 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448
Eric Laurent021cf962014-05-13 10:18:14 -07001449 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001450
Marco Nelissen06b46062014-11-14 07:58:25 -08001451 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001452 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001453 }
1454 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455
Eric Laurent021cf962014-05-13 10:18:14 -07001456 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001457 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001458 // the config change is always sent from playback or record threads to avoid deadlock
1459 // with AudioSystem::gLock
1460 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001461 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001462 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001464 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001465 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466 }
1467}
1468
1469void AudioFlinger::removeNotificationClient(pid_t pid)
1470{
1471 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001472 {
1473 Mutex::Autolock _cl(mClientLock);
1474 mNotificationClients.removeItem(pid);
1475 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001476
Steve Block3856b092011-10-20 11:56:00 +01001477 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001478 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001479 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001480 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001481 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001482 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001483 if (ref->mPid == pid) {
1484 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001485 mAudioSessionRefs.removeAt(i);
1486 delete ref;
1487 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001488 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001489 } else {
1490 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001491 }
1492 }
1493 if (removed) {
1494 purgeStaleEffects_l();
1495 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496}
1497
Eric Laurent73e26b62015-04-27 16:55:58 -07001498void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001499 const sp<AudioIoDescriptor>& ioDesc,
1500 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501{
Eric Laurent021cf962014-05-13 10:18:14 -07001502 Mutex::Autolock _l(mClientLock);
1503 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001505 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1506 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1507 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508 }
1509}
1510
Eric Laurent021cf962014-05-13 10:18:14 -07001511// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512void AudioFlinger::removeClient_l(pid_t pid)
1513{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001514 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001515 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516 mClients.removeItem(pid);
1517}
1518
Eric Laurent717e1282012-06-29 16:36:52 -07001519// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001520sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1521 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001522{
1523 sp<PlaybackThread> thread;
1524
1525 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1526 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1527 ALOG_ASSERT(thread == 0);
1528 thread = mPlaybackThreads.valueAt(i);
1529 }
1530 }
1531
1532 return thread;
1533}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536
1537// ----------------------------------------------------------------------------
1538
1539AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1540 : RefBase(),
1541 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001542 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001543{
Andy Hung6f248bb2018-01-23 14:04:37 -08001544 mMemoryDealer = new MemoryDealer(
1545 audioFlinger->getClientSharedHeapSize(),
1546 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547}
1548
Eric Laurent021cf962014-05-13 10:18:14 -07001549// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550AudioFlinger::Client::~Client()
1551{
1552 mAudioFlinger->removeClient_l(mPid);
1553}
1554
Glenn Kasten435dbe62012-01-30 10:15:48 -08001555sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556{
1557 return mMemoryDealer;
1558}
1559
1560// ----------------------------------------------------------------------------
1561
1562AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1563 const sp<IAudioFlingerClient>& client,
1564 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001565 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566{
1567}
1568
1569AudioFlinger::NotificationClient::~NotificationClient()
1570{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571}
1572
Glenn Kasten0f11b512014-01-31 16:18:54 -08001573void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574{
1575 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001576 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577}
1578
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001579// ----------------------------------------------------------------------------
1580AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1581 : mPendingRequests(false) {}
1582
1583
1584void AudioFlinger::MediaLogNotifier::requestMerge() {
1585 AutoMutex _l(mMutex);
1586 mPendingRequests = true;
1587 mCond.signal();
1588}
1589
1590bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001591 // Should already have been checked, but just in case
1592 if (sMediaLogService == 0) {
1593 return false;
1594 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001595 // Wait until there are pending requests
1596 {
1597 AutoMutex _l(mMutex);
1598 mPendingRequests = false; // to ignore past requests
1599 while (!mPendingRequests) {
1600 mCond.wait(mMutex);
1601 // TODO may also need an exitPending check
1602 }
1603 mPendingRequests = false;
1604 }
1605 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001606 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001607 usleep(kPostTriggerSleepPeriod);
1608 return true;
1609}
1610
1611void AudioFlinger::requestLogMerge() {
1612 mMediaLogNotifier->requestMerge();
1613}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614
1615// ----------------------------------------------------------------------------
1616
Eric Laurentf14db3c2017-12-08 14:20:36 -08001617sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1618 CreateRecordOutput& output,
1619 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620{
1621 sp<RecordThread::RecordTrack> recordTrack;
1622 sp<RecordHandle> recordHandle;
1623 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001625 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001626 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627
Eric Laurentf14db3c2017-12-08 14:20:36 -08001628 output.cblk.clear();
1629 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001630 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001631
Eric Laurentf14db3c2017-12-08 14:20:36 -08001632 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001633 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001634 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001635 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001636 ALOGW_IF(clientUid != callingUid,
1637 "%s uid %d tried to pass itself off as %d",
1638 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001639 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001640 updatePid = true;
1641 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001642 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001643 if (updatePid) {
1644 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001645 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001646 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001647 __func__, callingUid, callingPid, clientPid);
1648 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001649 }
1650
Andy Hung6770c6f2015-04-07 13:43:36 -07001651 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001652 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1653 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001654 lStatus = BAD_VALUE;
1655 goto Exit;
1656 }
1657
Glenn Kasten53b5d092014-02-05 10:00:23 -08001658 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001659 if (!audio_is_input_channel(input.config.channel_mask)) {
1660 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001661 lStatus = BAD_VALUE;
1662 goto Exit;
1663 }
1664
Eric Laurentf14db3c2017-12-08 14:20:36 -08001665 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1666 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1667 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1668 lStatus = BAD_VALUE;
1669 goto Exit;
1670 }
1671
1672 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001673 output.selectedDeviceId = input.selectedDeviceId;
1674 output.flags = input.flags;
1675
1676 client = registerPid(clientPid);
1677
1678 // Not a conventional loop, but a retry loop for at most two iterations total.
1679 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1680 // Exits loop via break on no error of got exit on error
1681 // The sp<> references will be dropped when re-entering scope.
1682 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1683 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001684 // release previously opened input if retrying.
1685 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1686 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001687 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001688 output.inputId = AUDIO_IO_HANDLE_NONE;
Eric Laurent77881cd2018-02-09 16:01:31 -08001689 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001690 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001691 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1692 sessionId,
1693 // FIXME compare to AudioTrack
1694 clientPid,
1695 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001696 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001697 &input.config,
1698 output.flags, &output.selectedDeviceId, &portId);
1699
Glenn Kasten05997e22014-03-13 15:08:33 -07001700 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001702 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001704 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705 lStatus = BAD_VALUE;
1706 goto Exit;
1707 }
1708
Eric Laurentf14db3c2017-12-08 14:20:36 -08001709 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710
Eric Laurentf14db3c2017-12-08 14:20:36 -08001711 output.sampleRate = input.config.sample_rate;
1712 output.frameCount = input.frameCount;
1713 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001714
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001715 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001716 input.config.format, input.config.channel_mask,
1717 &output.frameCount, sessionId,
1718 &output.notificationFrameCount,
1719 clientUid, &output.flags,
1720 input.clientInfo.clientTid,
1721 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001722 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001723
Eric Laurentf14db3c2017-12-08 14:20:36 -08001724 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1725 // audio policy manager without FAST constraint
1726 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001727 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001728 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001729
1730 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001731 goto Exit;
1732 }
1733
1734 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1735 // session and move it to this thread.
1736 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1737 if (chain != 0) {
1738 Mutex::Autolock _l(thread->mLock);
1739 thread->addEffectChain_l(chain);
1740 }
1741 break;
1742 }
1743 // End of retry loop.
1744 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745 }
Glenn Kastene198c362013-08-13 09:13:36 -07001746
Eric Laurentf14db3c2017-12-08 14:20:36 -08001747 output.cblk = recordTrack->getCblk();
1748 output.buffers = recordTrack->getBuffers();
1749
1750 // return handle to client
1751 recordHandle = new RecordHandle(recordTrack);
1752
1753Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001754 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001755 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001756 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001757 // Don't hold mClientLock when releasing the reference on the track as the
1758 // destructor will acquire it.
1759 {
1760 Mutex::Autolock _cl(mClientLock);
1761 client.clear();
1762 }
Eric Laurent896c9672017-12-08 14:08:45 -08001763 recordTrack.clear();
1764 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001765 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001766 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767 }
1768
Glenn Kasten9156ef32013-08-06 15:39:08 -07001769 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770 return recordHandle;
1771}
1772
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001773
1774
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775// ----------------------------------------------------------------------------
1776
Eric Laurenta4c5a552012-03-29 10:12:40 -07001777audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1778{
Eric Laurent44622db2014-08-01 19:00:33 -07001779 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001780 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001781 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001782 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001783 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001784 }
1785 Mutex::Autolock _l(mLock);
1786 return loadHwModule_l(name);
1787}
1788
1789// loadHwModule_l() must be called with AudioFlinger::mLock held
1790audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1791{
1792 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1793 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1794 ALOGW("loadHwModule() module %s already loaded", name);
1795 return mAudioHwDevs.keyAt(i);
1796 }
1797 }
1798
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001799 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001800
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001801 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001802 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001803 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001804 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001805 }
1806
1807 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001808 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001809 mHardwareStatus = AUDIO_HW_IDLE;
1810 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001811 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001812 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001813 }
1814
John Grossmanee578c02012-07-23 17:05:46 -07001815 // Check and cache this HAL's level of support for master mute and master
1816 // volume. If this is the first HAL opened, and it supports the get
1817 // methods, use the initial values provided by the HAL as the current
1818 // master mute and volume settings.
1819
1820 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1821 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001822 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001823
1824 if (0 == mAudioHwDevs.size()) {
1825 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001826 float mv;
1827 if (OK == dev->getMasterVolume(&mv)) {
1828 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001829 }
1830
1831 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001832 bool mm;
1833 if (OK == dev->getMasterMute(&mm)) {
1834 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001835 }
1836 }
1837
Eric Laurenta4c5a552012-03-29 10:12:40 -07001838 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001839 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001840 flags = static_cast<AudioHwDevice::Flags>(flags |
1841 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1842 }
1843
1844 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001845 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001846 flags = static_cast<AudioHwDevice::Flags>(flags |
1847 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1848 }
1849
Eric Laurenta4c5a552012-03-29 10:12:40 -07001850 mHardwareStatus = AUDIO_HW_IDLE;
1851 }
1852
Glenn Kastena13cde92016-03-28 15:26:02 -07001853 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001854 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001855
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001856 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001857
1858 return handle;
1859
1860}
1861
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001862// ----------------------------------------------------------------------------
1863
Glenn Kasten3b16c762012-11-14 08:44:39 -08001864uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001865{
1866 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001867 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001868 return thread != NULL ? thread->sampleRate() : 0;
1869}
1870
Glenn Kastene33054e2012-11-14 12:54:39 -08001871size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001872{
1873 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001874 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001875 return thread != NULL ? thread->frameCountHAL() : 0;
1876}
1877
1878// ----------------------------------------------------------------------------
1879
Andy Hung6f248bb2018-01-23 14:04:37 -08001880status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001881{
1882 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07001883 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001884 return PERMISSION_DENIED;
1885 }
1886 Mutex::Autolock _l(mLock);
1887 if (mIsDeviceTypeKnown) {
1888 return INVALID_OPERATION;
1889 }
1890 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001891 mTotalMemory = totalMemory;
1892 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
1893 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
1894 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
1895 // though actual setting is determined through device configuration.
1896 constexpr int64_t GB = 1024 * 1024 * 1024;
1897 mClientSharedHeapSize =
1898 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
1899 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
1900 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
1901 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
1902 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001903 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08001904
1905 // TODO: Cache the client shared heap size in a persistent property.
1906 // It's possible that a native process or Java service or app accesses audioserver
1907 // after it is registered by system server, but before AudioService updates
1908 // the memory info. This would occur immediately after boot or an audioserver
1909 // crash and restore. Before update from AudioService, the client would get the
1910 // minimum heap size.
1911
1912 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
1913 (isLowRamDevice ? "true" : "false"),
1914 (long long)mTotalMemory,
1915 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001916 return NO_ERROR;
1917}
1918
Andy Hung6f248bb2018-01-23 14:04:37 -08001919size_t AudioFlinger::getClientSharedHeapSize() const
1920{
1921 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
1922 if (heapSizeInBytes != 0) { // read-only property overrides all.
1923 return heapSizeInBytes;
1924 }
1925 return mClientSharedHeapSize;
1926}
1927
Mikhail Naganovdea53042018-04-26 13:10:21 -07001928status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
1929{
1930 ALOGV(__func__);
1931
1932 audio_module_handle_t module;
1933 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
1934 module = config->ext.device.hw_module;
1935 } else {
1936 module = config->ext.mix.hw_module;
1937 }
1938
1939 Mutex::Autolock _l(mLock);
1940 ssize_t index = mAudioHwDevs.indexOfKey(module);
1941 if (index < 0) {
1942 ALOGW("%s() bad hw module %d", __func__, module);
1943 return BAD_VALUE;
1944 }
1945
1946 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
1947 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
1948}
1949
Eric Laurent93c3d412014-08-01 14:48:35 -07001950audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1951{
1952 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001953
1954 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1955 if (index >= 0) {
1956 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1957 mHwAvSyncIds.valueAt(index), sessionId);
1958 return mHwAvSyncIds.valueAt(index);
1959 }
1960
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001961 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001962 if (dev == NULL) {
1963 return AUDIO_HW_SYNC_INVALID;
1964 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001965 String8 reply;
1966 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001967 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001968 param = AudioParameter(reply);
1969 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001970
1971 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001972 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001973 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1974 return AUDIO_HW_SYNC_INVALID;
1975 }
1976
1977 // allow only one session for a given HW A/V sync ID.
1978 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1979 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1980 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1981 value, mHwAvSyncIds.keyAt(i));
1982 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001983 break;
1984 }
1985 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001986
1987 mHwAvSyncIds.add(sessionId, value);
1988
1989 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1990 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1991 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001992 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001993 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001994 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001995 thread->setParameters(param.toString());
1996 break;
1997 }
1998 }
1999
2000 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2001 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002002}
2003
Eric Laurent72e3f392015-05-20 14:43:50 -07002004status_t AudioFlinger::systemReady()
2005{
2006 Mutex::Autolock _l(mLock);
2007 ALOGI("%s", __FUNCTION__);
2008 if (mSystemReady) {
2009 ALOGW("%s called twice", __FUNCTION__);
2010 return NO_ERROR;
2011 }
2012 mSystemReady = true;
2013 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2014 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2015 thread->systemReady();
2016 }
2017 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2018 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2019 thread->systemReady();
2020 }
2021 return NO_ERROR;
2022}
2023
jiabin46a76fa2018-01-05 10:18:21 -08002024status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2025{
jiabin9ff780e2018-03-19 18:19:52 -07002026 AutoMutex lock(mHardwareLock);
2027 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2028 status_t status = dev->getMicrophones(microphones);
2029 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002030}
2031
Eric Laurentfa90e842014-10-17 18:12:31 -07002032// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2033void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2034{
2035 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2036 if (index >= 0) {
2037 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2038 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2039 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002040 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07002041 thread->setParameters(param.toString());
2042 }
2043}
2044
2045
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002046// ----------------------------------------------------------------------------
2047
Eric Laurent83b88082014-06-20 18:31:16 -07002048
Eric Laurent6acd1d42017-01-04 14:23:29 -08002049sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002050 audio_io_handle_t *output,
2051 audio_config_t *config,
2052 audio_devices_t devices,
2053 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002054 audio_output_flags_t flags)
2055{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002056 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002057 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002058 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002059 }
2060
Eric Laurentcf2c0212014-07-25 16:20:43 -07002061 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002062 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2063 } else {
2064 // Audio Policy does not currently request a specific output handle.
2065 // If this is ever needed, see openInput_l() for example code.
2066 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2067 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002068 }
Eric Laurent83b88082014-06-20 18:31:16 -07002069
2070 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2071
Eric Laurent83b88082014-06-20 18:31:16 -07002072 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002073 // This if statement allows overriding the audio policy settings
2074 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2075 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2076 // Check only for Normal Mixing mode
2077 if (kEnableExtendedPrecision) {
2078 // Specify format (uncomment one below to choose)
2079 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2080 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2081 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2082 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002083 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002084 }
2085 if (kEnableExtendedChannels) {
2086 // Specify channel mask (uncomment one below to choose)
2087 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2088 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2089 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2090 }
Eric Laurent83b88082014-06-20 18:31:16 -07002091 }
2092
Phil Burk062e67a2015-02-11 13:40:50 -08002093 AudioStreamOut *outputStream = NULL;
2094 status_t status = outHwDev->openOutputStream(
2095 &outputStream,
2096 *output,
2097 devices,
2098 flags,
2099 config,
2100 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002101
2102 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002103
Phil Burk062e67a2015-02-11 13:40:50 -08002104 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002105 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2106 sp<MmapPlaybackThread> thread =
2107 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2108 devices, AUDIO_DEVICE_NONE, mSystemReady);
2109 mMmapThreads.add(*output, thread);
2110 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2111 *output, thread.get());
2112 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002113 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002114 sp<PlaybackThread> thread;
2115 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2116 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2117 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2118 *output, thread.get());
2119 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2120 || !isValidPcmSinkFormat(config->format)
2121 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2122 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2123 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2124 *output, thread.get());
2125 } else {
2126 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2127 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2128 *output, thread.get());
2129 }
2130 mPlaybackThreads.add(*output, thread);
2131 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002132 }
Eric Laurent83b88082014-06-20 18:31:16 -07002133 }
2134
2135 return 0;
2136}
2137
Eric Laurentcf2c0212014-07-25 16:20:43 -07002138status_t AudioFlinger::openOutput(audio_module_handle_t module,
2139 audio_io_handle_t *output,
2140 audio_config_t *config,
2141 audio_devices_t *devices,
2142 const String8& address,
2143 uint32_t *latencyMs,
2144 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002146 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2147 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002148 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002149 (devices != NULL) ? *devices : 0,
2150 config->sample_rate,
2151 config->format,
2152 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002153 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002154
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002155 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002156 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002157 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002158
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159 Mutex::Autolock _l(mLock);
2160
Eric Laurent6acd1d42017-01-04 14:23:29 -08002161 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002162 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002163 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2164 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2165 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166
Eric Laurent6acd1d42017-01-04 14:23:29 -08002167 // notify client processes of the new output creation
2168 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002169
Eric Laurent6acd1d42017-01-04 14:23:29 -08002170 // the first primary output opened designates the primary hw device
2171 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002172 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002173 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002174
Eric Laurent6acd1d42017-01-04 14:23:29 -08002175 AutoMutex lock(mHardwareLock);
2176 mHardwareStatus = AUDIO_HW_SET_MODE;
2177 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2178 mHardwareStatus = AUDIO_HW_IDLE;
2179 }
2180 } else {
2181 MmapThread *mmapThread = (MmapThread *)thread.get();
2182 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002183 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002184 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185 }
2186
Eric Laurentcf2c0212014-07-25 16:20:43 -07002187 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188}
2189
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002190audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2191 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192{
2193 Mutex::Autolock _l(mLock);
2194 MixerThread *thread1 = checkMixerThread_l(output1);
2195 MixerThread *thread2 = checkMixerThread_l(output2);
2196
2197 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002198 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2199 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002200 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201 }
2202
Glenn Kasteneeecb982016-02-26 10:44:04 -08002203 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002204 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002205 thread->addOutputTrack(thread2);
2206 mPlaybackThreads.add(id, thread);
2207 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002208 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002209 return id;
2210}
2211
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002212status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213{
Glenn Kastend96c5722012-04-25 13:44:49 -07002214 return closeOutput_nonvirtual(output);
2215}
2216
2217status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2218{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219 // keep strong reference on the playback thread so that
2220 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002221 sp<PlaybackThread> playbackThread;
2222 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223 {
2224 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002225 playbackThread = checkPlaybackThread_l(output);
2226 if (playbackThread != NULL) {
2227 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002228
Eric Laurent6acd1d42017-01-04 14:23:29 -08002229 if (playbackThread->type() == ThreadBase::MIXER) {
2230 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2231 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2232 DuplicatingThread *dupThread =
2233 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2234 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2235 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002236 }
2237 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002238
2239
Eric Laurent6acd1d42017-01-04 14:23:29 -08002240 mPlaybackThreads.removeItem(output);
2241 // save all effects to the default thread
2242 if (mPlaybackThreads.size()) {
2243 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2244 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002245 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002246 Mutex::Autolock _dl(dstThread->mLock);
2247 Mutex::Autolock _sl(playbackThread->mLock);
2248 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2249 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002250 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2251 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002252 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253 }
2254 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002255 } else {
2256 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2257 if (mmapThread == 0) {
2258 return BAD_VALUE;
2259 }
2260 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002261 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002263 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2264 ioDesc->mIoHandle = output;
2265 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002266 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002267 // The thread entity (active unit of execution) is no longer running here,
2268 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002269
Eric Laurent6acd1d42017-01-04 14:23:29 -08002270 if (playbackThread != 0) {
2271 playbackThread->exit();
2272 if (!playbackThread->isDuplicating()) {
2273 closeOutputFinish(playbackThread);
2274 }
2275 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002276 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002277 mmapThread->exit();
2278 AudioStreamOut *out = mmapThread->clearOutput();
2279 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2280 // from now on thread->mOutput is NULL
2281 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282 }
2283 return NO_ERROR;
2284}
2285
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002286void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002287{
2288 AudioStreamOut *out = thread->clearOutput();
2289 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2290 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002291 delete out;
2292}
2293
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002294void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002295{
2296 mPlaybackThreads.removeItem(thread->mId);
2297 thread->exit();
2298 closeOutputFinish(thread);
2299}
2300
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002301status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302{
2303 Mutex::Autolock _l(mLock);
2304 PlaybackThread *thread = checkPlaybackThread_l(output);
2305
2306 if (thread == NULL) {
2307 return BAD_VALUE;
2308 }
2309
Steve Block3856b092011-10-20 11:56:00 +01002310 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311 thread->suspend();
2312
2313 return NO_ERROR;
2314}
2315
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002316status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002317{
2318 Mutex::Autolock _l(mLock);
2319 PlaybackThread *thread = checkPlaybackThread_l(output);
2320
2321 if (thread == NULL) {
2322 return BAD_VALUE;
2323 }
2324
Steve Block3856b092011-10-20 11:56:00 +01002325 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326
2327 thread->restore();
2328
2329 return NO_ERROR;
2330}
2331
Eric Laurentcf2c0212014-07-25 16:20:43 -07002332status_t AudioFlinger::openInput(audio_module_handle_t module,
2333 audio_io_handle_t *input,
2334 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002335 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002336 const String8& address,
2337 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002338 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002339{
Eric Laurent83b88082014-06-20 18:31:16 -07002340 Mutex::Autolock _l(mLock);
2341
Glenn Kastene7d66712015-03-05 13:46:52 -08002342 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002343 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002344 }
2345
Eric Laurent6acd1d42017-01-04 14:23:29 -08002346 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002347
2348 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002349 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002350 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002351 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002353 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002354}
Dima Zavin799a70e2011-04-18 16:57:27 -07002355
Eric Laurent6acd1d42017-01-04 14:23:29 -08002356sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002357 audio_io_handle_t *input,
2358 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002359 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002360 const String8& address,
2361 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002362 audio_input_flags_t flags)
2363{
Glenn Kastene7d66712015-03-05 13:46:52 -08002364 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002365 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002366 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002367 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002368 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002369
Glenn Kasteneeecb982016-02-26 10:44:04 -08002370 // Audio Policy can request a specific handle for hardware hotword.
2371 // The goal here is not to re-open an already opened input.
2372 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002373 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002374 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2375 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2376 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2377 return 0;
2378 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2379 // This should not happen in a transient state with current design.
2380 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2381 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002382 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002383
Eric Laurentcf2c0212014-07-25 16:20:43 -07002384 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002385 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002386 sp<StreamInHalInterface> inStream;
2387 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002388 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002389 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2390 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002391 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002392 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002393 halconfig.sample_rate,
2394 halconfig.format,
2395 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002396 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002397 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002399 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002400 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002401 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002402 audio_is_linear_pcm(config->format) &&
2403 audio_is_linear_pcm(halconfig.format) &&
2404 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002405 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2406 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002407 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002408 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002409 inStream.clear();
2410 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002411 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002412 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002413 }
2414
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002415 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002416 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002417 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2418 sp<MmapCaptureThread> thread =
2419 new MmapCaptureThread(this, *input,
2420 inHwDev, inputStream,
2421 primaryOutputDevice_l(), devices, mSystemReady);
2422 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002423 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2424 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002425 return thread;
2426 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002427#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002428 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2429 // or (re-)create if current Pipe is idle and does not match the new format
2430 sp<NBAIO_Sink> teeSink;
2431 enum {
2432 TEE_SINK_NO, // don't copy input
2433 TEE_SINK_NEW, // copy input using a new pipe
2434 TEE_SINK_OLD, // copy input using an existing pipe
2435 } kind;
2436 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2437 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2438 if (!mTeeSinkInputEnabled) {
2439 kind = TEE_SINK_NO;
2440 } else if (!Format_isValid(format)) {
2441 kind = TEE_SINK_NO;
2442 } else if (mRecordTeeSink == 0) {
2443 kind = TEE_SINK_NEW;
2444 } else if (mRecordTeeSink->getStrongCount() != 1) {
2445 kind = TEE_SINK_NO;
2446 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2447 kind = TEE_SINK_OLD;
2448 } else {
2449 kind = TEE_SINK_NEW;
2450 }
2451 switch (kind) {
2452 case TEE_SINK_NEW: {
2453 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2454 size_t numCounterOffers = 0;
2455 const NBAIO_Format offers[1] = {format};
2456 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2457 ALOG_ASSERT(index == 0);
2458 PipeReader *pipeReader = new PipeReader(*pipe);
2459 numCounterOffers = 0;
2460 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2461 ALOG_ASSERT(index == 0);
2462 mRecordTeeSink = pipe;
2463 mRecordTeeSource = pipeReader;
2464 teeSink = pipe;
2465 }
2466 break;
2467 case TEE_SINK_OLD:
2468 teeSink = mRecordTeeSink;
2469 break;
2470 case TEE_SINK_NO:
2471 default:
2472 break;
2473 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002474#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002475
2476 // Start record thread
2477 // RecordThread requires both input and output device indication to forward to audio
2478 // pre processing modules
2479 sp<RecordThread> thread = new RecordThread(this,
2480 inputStream,
2481 *input,
2482 primaryOutputDevice_l(),
2483 devices,
2484 mSystemReady
2485#ifdef TEE_SINK
2486 , teeSink
2487#endif
2488 );
2489 mRecordThreads.add(*input, thread);
2490 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2491 return thread;
2492 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493 }
2494
Eric Laurentcf2c0212014-07-25 16:20:43 -07002495 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496 return 0;
2497}
2498
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002499status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500{
Glenn Kastend96c5722012-04-25 13:44:49 -07002501 return closeInput_nonvirtual(input);
2502}
2503
2504status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2505{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506 // keep strong reference on the record thread so that
2507 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002508 sp<RecordThread> recordThread;
2509 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 {
2511 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002512 recordThread = checkRecordThread_l(input);
2513 if (recordThread != 0) {
2514 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515
Eric Laurent6acd1d42017-01-04 14:23:29 -08002516 // If we still have effect chains, it means that a client still holds a handle
2517 // on at least one effect. We must either move the chain to an existing thread with the
2518 // same session ID or put it aside in case a new record thread is opened for a
2519 // new capture on the same session
2520 sp<EffectChain> chain;
2521 {
2522 Mutex::Autolock _sl(recordThread->mLock);
2523 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2524 // Note: maximum one chain per record thread
2525 if (effectChains.size() != 0) {
2526 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002527 }
2528 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002529 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002530 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002531 // This should only happen in case of overlap between one thread tear down and the
2532 // creation of its replacement
2533 size_t i;
2534 for (i = 0; i < mRecordThreads.size(); i++) {
2535 sp<RecordThread> t = mRecordThreads.valueAt(i);
2536 if (t == recordThread) {
2537 continue;
2538 }
2539 if (t->hasAudioSession(chain->sessionId()) != 0) {
2540 Mutex::Autolock _l(t->mLock);
2541 ALOGV("closeInput() found thread %d for effect session %d",
2542 t->id(), chain->sessionId());
2543 t->addEffectChain_l(chain);
2544 break;
2545 }
2546 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002547 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002548 if (i == mRecordThreads.size()) {
2549 putOrphanEffectChain_l(chain);
2550 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002551 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002552 mRecordThreads.removeItem(input);
2553 } else {
2554 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2555 if (mmapThread == 0) {
2556 return BAD_VALUE;
2557 }
2558 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002559 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002560 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2561 ioDesc->mIoHandle = input;
2562 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563 }
Eric Laurent83b88082014-06-20 18:31:16 -07002564 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2565 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002566 if (recordThread != 0) {
2567 closeInputFinish(recordThread);
2568 } else if (mmapThread != 0) {
2569 mmapThread->exit();
2570 AudioStreamIn *in = mmapThread->clearInput();
2571 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2572 // from now on thread->mInput is NULL
2573 delete in;
2574 }
Eric Laurent83b88082014-06-20 18:31:16 -07002575 return NO_ERROR;
2576}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002578void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002579{
2580 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002581 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002582 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002583 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002584 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002585}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002587void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002588{
2589 mRecordThreads.removeItem(thread->mId);
2590 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591}
2592
Glenn Kastend2304db2014-02-03 07:40:31 -08002593status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594{
2595 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002596 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002597
2598 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2599 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002600 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002601 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002602 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2603 mMmapThreads[i]->invalidateTracks(stream);
2604 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605 return NO_ERROR;
2606}
2607
2608
Glenn Kasteneeecb982016-02-26 10:44:04 -08002609audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610{
Glenn Kasten9d003132016-04-06 14:38:09 -07002611 // This is a binder API, so a malicious client could pass in a bad parameter.
2612 // Check for that before calling the internal API nextUniqueId().
2613 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2614 ALOGE("newAudioUniqueId invalid use %d", use);
2615 return AUDIO_UNIQUE_ID_ALLOCATE;
2616 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002617 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618}
2619
Glenn Kastend848eb42016-03-08 13:42:11 -08002620void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002621{
2622 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002623 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002624 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002625 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2626 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002627 caller = pid;
2628 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002629
Eric Laurent021cf962014-05-13 10:18:14 -07002630 {
2631 Mutex::Autolock _cl(mClientLock);
2632 // Ignore requests received from processes not known as notification client. The request
2633 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2634 // called from a different pid leaving a stale session reference. Also we don't know how
2635 // to clear this reference if the client process dies.
2636 if (mNotificationClients.indexOfKey(caller) < 0) {
2637 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2638 return;
2639 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002640 }
2641
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002642 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002643 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002644 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002645 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2646 ref->mCnt++;
2647 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002648 return;
2649 }
2650 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002651 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2652 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002653}
2654
Glenn Kastend848eb42016-03-08 13:42:11 -08002655void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002656{
2657 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002658 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002659 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002660 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2661 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002662 caller = pid;
2663 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002664 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002665 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002666 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002667 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2668 ref->mCnt--;
2669 ALOGV(" decremented refcount to %d", ref->mCnt);
2670 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002671 mAudioSessionRefs.removeAt(i);
2672 delete ref;
2673 purgeStaleEffects_l();
2674 }
2675 return;
2676 }
2677 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07002678 // If the caller is audioserver it is likely that the session being released was acquired
Eric Laurentd1b28d42013-09-18 18:47:13 -07002679 // on behalf of a process not in notification clients and we ignore the warning.
Andy Hung4ef19fa2018-05-15 19:35:29 -07002680 ALOGW_IF(!isAudioServerUid(callerUid),
2681 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002682}
2683
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002684bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2685{
2686 size_t num = mAudioSessionRefs.size();
2687 for (size_t i = 0; i < num; i++) {
2688 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2689 if (ref->mSessionid == audioSession) {
2690 return true;
2691 }
2692 }
2693 return false;
2694}
2695
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002696void AudioFlinger::purgeStaleEffects_l() {
2697
Steve Block3856b092011-10-20 11:56:00 +01002698 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002699
2700 Vector< sp<EffectChain> > chains;
2701
2702 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2703 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002704 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002705 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2706 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002707 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2708 chains.push(ec);
2709 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002710 }
2711 }
2712 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2713 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002714 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002715 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2716 sp<EffectChain> ec = t->mEffectChains[j];
2717 chains.push(ec);
2718 }
2719 }
2720
2721 for (size_t i = 0; i < chains.size(); i++) {
2722 sp<EffectChain> ec = chains[i];
2723 int sessionid = ec->sessionId();
2724 sp<ThreadBase> t = ec->mThread.promote();
2725 if (t == 0) {
2726 continue;
2727 }
2728 size_t numsessionrefs = mAudioSessionRefs.size();
2729 bool found = false;
2730 for (size_t k = 0; k < numsessionrefs; k++) {
2731 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002732 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002733 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002734 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002735 found = true;
2736 break;
2737 }
2738 }
2739 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002740 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002741 // remove all effects from the chain
2742 while (ec->mEffects.size()) {
2743 sp<EffectModule> effect = ec->mEffects[0];
2744 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002745 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002746 if (effect->purgeHandles()) {
2747 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002748 }
2749 AudioSystem::unregisterEffect(effect->id());
2750 }
2751 }
2752 }
2753 return;
2754}
2755
Glenn Kasteneeecb982016-02-26 10:44:04 -08002756// checkThread_l() must be called with AudioFlinger::mLock held
2757AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2758{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002759 ThreadBase *thread = checkMmapThread_l(ioHandle);
2760 if (thread == 0) {
2761 switch (audio_unique_id_get_use(ioHandle)) {
2762 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2763 thread = checkPlaybackThread_l(ioHandle);
2764 break;
2765 case AUDIO_UNIQUE_ID_USE_INPUT:
2766 thread = checkRecordThread_l(ioHandle);
2767 break;
2768 default:
2769 break;
2770 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002771 }
2772 return thread;
2773}
2774
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002776AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777{
Glenn Kastena1117922012-01-26 10:53:32 -08002778 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779}
2780
2781// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002782AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783{
2784 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002785 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002786}
2787
2788// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002789AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002790{
Glenn Kastena1117922012-01-26 10:53:32 -08002791 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002792}
2793
Eric Laurent6acd1d42017-01-04 14:23:29 -08002794// checkMmapThread_l() must be called with AudioFlinger::mLock held
2795AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2796{
2797 return mMmapThreads.valueFor(io).get();
2798}
2799
2800
2801// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2802AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2803{
Eric Laurent7459b902017-04-19 18:10:41 -07002804 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002805 if (volumeInterface == nullptr) {
2806 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2807 if (mmapThread != nullptr) {
2808 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002809 MmapPlaybackThread *mmapPlaybackThread =
2810 static_cast<MmapPlaybackThread *>(mmapThread);
2811 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002812 }
2813 }
2814 }
2815 return volumeInterface;
2816}
2817
2818Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2819{
2820 Vector <VolumeInterface *> volumeInterfaces;
2821 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002822 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002823 }
2824 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2825 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002826 MmapPlaybackThread *mmapPlaybackThread =
2827 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2828 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002829 }
2830 }
2831 return volumeInterfaces;
2832}
2833
Glenn Kasteneeecb982016-02-26 10:44:04 -08002834audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835{
Glenn Kasten9d003132016-04-06 14:38:09 -07002836 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002837 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002838 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2839 for (int retry = 0; retry < maxRetries; retry++) {
2840 // The cast allows wraparound from max positive to min negative instead of abort
2841 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2842 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2843 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2844 // allow wrap by skipping 0 and -1 for session ids
2845 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2846 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2847 return (audio_unique_id_t) (base | use);
2848 }
2849 }
2850 // We have no way of recovering from wraparound
2851 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2852 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853}
2854
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002855AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002856{
2857 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2858 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002859 if(thread->isDuplicating()) {
2860 continue;
2861 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002862 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002863 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002864 return thread;
2865 }
2866 }
2867 return NULL;
2868}
2869
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002870audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002871{
2872 PlaybackThread *thread = primaryPlaybackThread_l();
2873
2874 if (thread == NULL) {
2875 return 0;
2876 }
2877
Eric Laurentf1c04f92012-08-28 14:26:53 -07002878 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002879}
2880
Glenn Kastena7335632016-06-09 17:09:53 -07002881AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2882{
2883 size_t minFrameCount = 0;
2884 PlaybackThread *minThread = NULL;
2885 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2886 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2887 if (!thread->isDuplicating()) {
2888 size_t frameCount = thread->frameCountHAL();
2889 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2890 (frameCount == minFrameCount && thread->hasFastMixer() &&
2891 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2892 minFrameCount = frameCount;
2893 minThread = thread;
2894 }
2895 }
2896 }
2897 return minThread;
2898}
2899
Eric Laurenta011e352012-03-29 15:51:43 -07002900sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002901 audio_session_t triggerSession,
2902 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002903 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002904 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002905{
2906 Mutex::Autolock _l(mLock);
2907
2908 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2909 status_t playStatus = NAME_NOT_FOUND;
2910 status_t recStatus = NAME_NOT_FOUND;
2911 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2912 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2913 if (playStatus == NO_ERROR) {
2914 return event;
2915 }
2916 }
2917 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2918 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2919 if (recStatus == NO_ERROR) {
2920 return event;
2921 }
2922 }
2923 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2924 mPendingSyncEvents.add(event);
2925 } else {
2926 ALOGV("createSyncEvent() invalid event %d", event->type());
2927 event.clear();
2928 }
2929 return event;
2930}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002931
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932// ----------------------------------------------------------------------------
2933// Effect management
2934// ----------------------------------------------------------------------------
2935
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002936sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2937 return mEffectsFactoryHal;
2938}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939
Glenn Kastenf587ba52012-01-26 16:25:10 -08002940status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941{
2942 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002943 if (mEffectsFactoryHal.get()) {
2944 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2945 } else {
2946 return -ENODEV;
2947 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948}
2949
Glenn Kastenf587ba52012-01-26 16:25:10 -08002950status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002951{
2952 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002953 if (mEffectsFactoryHal.get()) {
2954 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2955 } else {
2956 return -ENODEV;
2957 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958}
2959
Glenn Kasten5e92a782012-01-30 07:40:52 -08002960status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002961 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002962{
2963 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002964 if (mEffectsFactoryHal.get()) {
2965 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2966 } else {
2967 return -ENODEV;
2968 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002969}
2970
2971
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002972sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002973 effect_descriptor_t *pDesc,
2974 const sp<IEffectClient>& effectClient,
2975 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002976 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002977 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002978 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002979 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980 status_t *status,
2981 int *id,
2982 int *enabled)
2983{
2984 status_t lStatus = NO_ERROR;
2985 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987
Eric Laurentb6436272016-12-07 19:24:50 -08002988 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002989 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08002990 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2991 ALOGW_IF(pid != -1 && pid != callingPid,
2992 "%s uid %d pid %d tried to pass itself off as pid %d",
2993 __func__, callingUid, callingPid, pid);
2994 pid = callingPid;
2995 }
2996
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002997 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2998 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002999
3000 if (pDesc == NULL) {
3001 lStatus = BAD_VALUE;
3002 goto Exit;
3003 }
3004
Eric Laurent84e9a102010-09-23 16:10:16 -07003005 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07003006 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003007 lStatus = PERMISSION_DENIED;
3008 goto Exit;
3009 }
3010
Dima Zavinfce7a472011-04-19 22:30:36 -07003011 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Andy Hung4ef19fa2018-05-15 19:35:29 -07003012 // that can only be created by audio policy manager
3013 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && !isAudioServerUid(callingUid)) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003014 lStatus = PERMISSION_DENIED;
3015 goto Exit;
3016 }
3017
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003018 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003019 lStatus = NO_INIT;
3020 goto Exit;
3021 }
3022
Mathias Agopian65ab4712010-07-14 17:59:35 -07003023 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003024 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003025 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003026 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003028 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003029 goto Exit;
3030 }
3031 } else {
3032 // if uuid is not specified, look for an available implementation
3033 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003034 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003035 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036 lStatus = BAD_VALUE;
3037 goto Exit;
3038 }
3039 uint32_t numEffects = 0;
3040 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003041 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042 bool found = false;
3043
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003044 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003045 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003046 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047 goto Exit;
3048 }
3049 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003050 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003051 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003052 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 continue;
3054 }
3055 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
3056 // If matching type found save effect descriptor. If the session is
3057 // 0 and the effect is not auxiliary, continue enumeration in case
3058 // an auxiliary version of this effect type is available
3059 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08003060 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07003061 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003062 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3063 break;
3064 }
3065 }
3066 }
3067 if (!found) {
3068 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00003069 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003070 goto Exit;
3071 }
3072 // For same effect type, chose auxiliary version over insert version if
3073 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07003074 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003075 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08003076 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077 }
3078 }
3079
3080 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003081 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003082 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3083 lStatus = INVALID_OPERATION;
3084 goto Exit;
3085 }
3086
Eric Laurent59255e42011-07-27 19:49:51 -07003087 // check recording permission for visualizer
3088 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003089 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003090 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003091 lStatus = PERMISSION_DENIED;
3092 goto Exit;
3093 }
3094
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003096 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003097 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003098 // if the output returned by getOutputForEffect() is removed before we lock the
3099 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3100 // and we will exit safely
3101 io = AudioSystem::getOutputForEffect(&desc);
3102 ALOGV("createEffect got output %d", io);
3103 }
3104
3105 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003106
3107 // If output is not specified try to find a matching audio session ID in one of the
3108 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003109 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3110 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003111 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003112 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003113 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3114 // output must be specified by AudioPolicyManager when using session
3115 // AUDIO_SESSION_OUTPUT_STAGE
3116 lStatus = BAD_VALUE;
3117 goto Exit;
3118 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003119 // look for the thread where the specified audio session is present
3120 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3121 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3122 io = mPlaybackThreads.keyAt(i);
3123 break;
3124 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003126 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003127 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3128 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3129 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003130 break;
3131 }
3132 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003133 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003134 if (io == AUDIO_IO_HANDLE_NONE) {
3135 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3136 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3137 io = mMmapThreads.keyAt(i);
3138 break;
3139 }
3140 }
3141 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003142 // If no output thread contains the requested session ID, default to
3143 // first output. The effect chain will be moved to the correct output
3144 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003145 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003146 io = mPlaybackThreads.keyAt(0);
3147 }
Steve Block3856b092011-10-20 11:56:00 +01003148 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003149 }
3150 ThreadBase *thread = checkRecordThread_l(io);
3151 if (thread == NULL) {
3152 thread = checkPlaybackThread_l(io);
3153 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003154 thread = checkMmapThread_l(io);
3155 if (thread == NULL) {
3156 ALOGE("createEffect() unknown output thread");
3157 lStatus = BAD_VALUE;
3158 goto Exit;
3159 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003160 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003161 } else {
3162 // Check if one effect chain was awaiting for an effect to be created on this
3163 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003164 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003165 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003166 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003167 thread->addEffectChain_l(chain);
3168 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003169 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003170
Eric Laurent021cf962014-05-13 10:18:14 -07003171 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003173 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003174 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003175 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003176 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003177 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003178 // remove local strong reference to Client with mClientLock held
3179 Mutex::Autolock _cl(mClientLock);
3180 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003181 } else {
3182 // handle must be valid here, but check again to be safe.
3183 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003184 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003185 }
3186
haobo101735295ff7b0d2017-03-17 17:44:03 +08003187 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3188 // handle must be cleared outside lock.
3189 handle.clear();
3190 }
3191
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003193 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194 return handle;
3195}
3196
Glenn Kastend848eb42016-03-08 13:42:11 -08003197status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003198 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003199{
Steve Block3856b092011-10-20 11:56:00 +01003200 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003201 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003202 Mutex::Autolock _l(mLock);
3203 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003204 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003205 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206 }
Eric Laurentde070132010-07-13 04:45:46 -07003207 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3208 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003209 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003210 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211 }
Eric Laurentde070132010-07-13 04:45:46 -07003212 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3213 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003214 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003215 return BAD_VALUE;
3216 }
3217
3218 Mutex::Autolock _dl(dstThread->mLock);
3219 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003220 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003221}
3222
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003223// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003224status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003225 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003226 AudioFlinger::PlaybackThread *dstThread,
3227 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003228{
Steve Block3856b092011-10-20 11:56:00 +01003229 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003230 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003231
Eric Laurent59255e42011-07-27 19:49:51 -07003232 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003233 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003234 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003235 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003236 return INVALID_OPERATION;
3237 }
3238
Eric Laurent4c415062016-06-17 16:14:16 -07003239 // Check whether the destination thread and all effects in the chain are compatible
3240 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003241 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003242 " destination thread %p is not compatible with effects in the chain",
3243 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003244 return INVALID_OPERATION;
3245 }
3246
Eric Laurent39e94f82010-07-28 01:32:47 -07003247 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003248 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003249 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003250 // removed.
3251 srcThread->removeEffectChain_l(chain);
3252
3253 // transfer all effects one by one so that new effect chain is created on new thread with
3254 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003255 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003256 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003257 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003258 Vector< sp<EffectModule> > removed;
3259 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003260 while (effect != 0) {
3261 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003262 removed.add(effect);
3263 status = dstThread->addEffect_l(effect);
3264 if (status != NO_ERROR) {
3265 break;
3266 }
Eric Laurentec35a142011-10-05 17:42:25 -07003267 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3268 if (effect->state() == EffectModule::ACTIVE ||
3269 effect->state() == EffectModule::STOPPING) {
3270 effect->start();
3271 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003272 // if the move request is not received from audio policy manager, the effect must be
3273 // re-registered with the new strategy and output
3274 if (dstChain == 0) {
3275 dstChain = effect->chain().promote();
3276 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003277 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003278 status = NO_INIT;
3279 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003280 }
3281 strategy = dstChain->strategy();
3282 }
3283 if (reRegister) {
3284 AudioSystem::unregisterEffect(effect->id());
3285 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003286 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003287 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003288 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003289 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003290 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003291 }
Eric Laurentde070132010-07-13 04:45:46 -07003292 effect = chain->getEffectFromId_l(0);
3293 }
3294
Eric Laurent5baf2af2013-09-12 17:37:00 -07003295 if (status != NO_ERROR) {
3296 for (size_t i = 0; i < removed.size(); i++) {
3297 srcThread->addEffect_l(removed[i]);
3298 if (dstChain != 0 && reRegister) {
3299 AudioSystem::unregisterEffect(removed[i]->id());
3300 AudioSystem::registerEffect(&removed[i]->desc(),
3301 srcThread->id(),
3302 strategy,
3303 sessionId,
3304 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003305 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003306 }
3307 }
3308 }
3309
3310 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311}
3312
Eric Laurent5baf2af2013-09-12 17:37:00 -07003313bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003314{
3315 if (mGlobalEffectEnableTime != 0 &&
3316 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3317 return true;
3318 }
3319
3320 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3321 sp<EffectChain> ec =
3322 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003323 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003324 return true;
3325 }
3326 }
3327 return false;
3328}
3329
Eric Laurent5baf2af2013-09-12 17:37:00 -07003330void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003331{
3332 Mutex::Autolock _l(mLock);
3333
3334 mGlobalEffectEnableTime = systemTime();
3335
3336 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3337 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3338 if (t->mType == ThreadBase::OFFLOAD) {
3339 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3340 }
3341 }
3342
3343}
3344
Eric Laurentaaa44472014-09-12 17:41:50 -07003345status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3346{
Eric Laurentd8365c52017-07-16 15:27:05 -07003347 // clear possible suspended state before parking the chain so that it starts in default state
3348 // when attached to a new record thread
3349 chain->setEffectSuspended_l(FX_IID_AEC, false);
3350 chain->setEffectSuspended_l(FX_IID_NS, false);
3351
Glenn Kastend848eb42016-03-08 13:42:11 -08003352 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003353 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003354 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003355 if (index >= 0) {
3356 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3357 return ALREADY_EXISTS;
3358 }
3359 mOrphanEffectChains.add(session, chain);
3360 return NO_ERROR;
3361}
3362
3363sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3364{
3365 sp<EffectChain> chain;
3366 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003367 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003368 if (index >= 0) {
3369 chain = mOrphanEffectChains.valueAt(index);
3370 mOrphanEffectChains.removeItemsAt(index);
3371 }
3372 return chain;
3373}
3374
3375bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3376{
3377 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003378 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003379 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003380 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003381 if (index >= 0) {
3382 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003383 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003384 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003385 mOrphanEffectChains.removeItemsAt(index);
3386 }
3387 return true;
3388 }
3389 return false;
3390}
3391
3392
Glenn Kastenda6ef132013-01-10 12:31:01 -08003393struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003394#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3395 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003396};
3397
3398int comparEntry(const void *p1, const void *p2)
3399{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003400 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003401}
3402
Glenn Kasten46909e72013-02-26 09:20:22 -08003403#ifdef TEE_SINK
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003404void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id, char suffix)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405{
Eric Laurent81784c32012-11-19 14:55:58 -08003406 NBAIO_Source *teeSource = source.get();
3407 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003408 // .wav rotation
3409 // There is a benign race condition if 2 threads call this simultaneously.
3410 // They would both traverse the directory, but the result would simply be
3411 // failures at unlink() which are ignored. It's also unlikely since
3412 // normally dumpsys is only done by bugreport or from the command line.
Andy Hungb1fe6e12018-04-19 19:20:00 -07003413 char teePath[PATH_MAX] = "/data/misc/audioserver";
Glenn Kastenda6ef132013-01-10 12:31:01 -08003414 size_t teePathLen = strlen(teePath);
3415 DIR *dir = opendir(teePath);
3416 teePath[teePathLen++] = '/';
3417 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003418#define TEE_MAX_SORT 20 // number of entries to sort
3419#define TEE_MAX_KEEP 10 // number of entries to keep
3420 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003421 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003422 while (entryCount < TEE_MAX_SORT) {
Andy Hungb1fe6e12018-04-19 19:20:00 -07003423 errno = 0; // clear errno before readdir() to track potential errors.
3424 const struct dirent *result = readdir(dir);
3425 if (result == nullptr) {
3426 ALOGW_IF(errno != 0, "tee readdir() failure %s", strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003427 break;
3428 }
3429 // ignore non .wav file entries
Andy Hungb1fe6e12018-04-19 19:20:00 -07003430 const size_t nameLen = strlen(result->d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003431 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Andy Hungb1fe6e12018-04-19 19:20:00 -07003432 strcmp(&result->d_name[nameLen - 4], ".wav")) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003433 continue;
3434 }
Andy Hungb1fe6e12018-04-19 19:20:00 -07003435 (void)audio_utils_strlcpy(entries[entryCount++].mFileName, result->d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003436 }
3437 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003438 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003439 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003440 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3441 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003442 (void) unlink(teePath);
3443 }
3444 }
3445 } else {
3446 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003447 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003448 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003449 }
3450 }
Eric Laurent81784c32012-11-19 14:55:58 -08003451 char teeTime[16];
3452 struct timeval tv;
3453 gettimeofday(&tv, NULL);
3454 struct tm tm;
3455 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003456 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
Glenn Kasten5b2191a2016-08-19 11:44:47 -07003457 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d_%c.wav", teeTime, id,
3458 suffix);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003459 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3460 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003461 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003462 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003463 char wavHeader[44];
3464 memcpy(wavHeader,
3465 "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
3466 sizeof(wavHeader));
3467 NBAIO_Format format = teeSource->format();
3468 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003469 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003470 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003471 wavHeader[22] = channelCount; // number of channels
3472 wavHeader[24] = sampleRate; // sample rate
3473 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003474 wavHeader[32] = frameSize; // block alignment
3475 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003476 write(teeFd, wavHeader, sizeof(wavHeader));
3477 size_t total = 0;
3478 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003479#define TEE_SINK_READ 1024 // frames per I/O operation
3480 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003481 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003482 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003483 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003484 bool wasFirstRead = firstRead;
3485 firstRead = false;
3486 if (actual <= 0) {
3487 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3488 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003489 }
Eric Laurent81784c32012-11-19 14:55:58 -08003490 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003491 }
Eric Laurent81784c32012-11-19 14:55:58 -08003492 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003493 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003494 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003495 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003496 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003497 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003498 uint32_t temp = 44 + total * frameSize - 8;
3499 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003500 write(teeFd, &temp, sizeof(temp));
3501 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003502 temp = total * frameSize;
3503 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003504 write(teeFd, &temp, sizeof(temp));
3505 close(teeFd);
Glenn Kasten9e756632017-10-03 13:01:09 -07003506 // TODO Should create file with temporary name and then rename to final if non-empty.
3507 if (total > 0) {
3508 if (fd >= 0) {
3509 dprintf(fd, "tee copied to %s\n", teePath);
3510 }
3511 } else {
3512 unlink(teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003513 }
Eric Laurent59255e42011-07-27 19:49:51 -07003514 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003515 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003516 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003517 }
Eric Laurent59255e42011-07-27 19:49:51 -07003518 }
3519 }
3520}
Glenn Kasten46909e72013-02-26 09:20:22 -08003521#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003522
Mathias Agopian65ab4712010-07-14 17:59:35 -07003523// ----------------------------------------------------------------------------
3524
3525status_t AudioFlinger::onTransact(
3526 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3527{
3528 return BnAudioFlinger::onTransact(code, data, reply, flags);
3529}
3530
Glenn Kasten63238ef2015-03-02 15:50:29 -08003531} // namespace android